1 //===-- Value.cpp - Implement the Value class -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Value and User classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constant.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/InstrTypes.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/LeakDetector.h"
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 static inline const Type *checkType(const Type *Ty) {
31 assert(Ty && "Value defined with a null type: Error!");
35 Value::Value(const Type *ty, unsigned scid)
36 : SubclassID(scid), SubclassData(0), Ty(checkType(ty)),
38 if (isa<CallInst>(this) || isa<InvokeInst>(this))
39 assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||
40 isa<OpaqueType>(ty) || Ty->getTypeID() == Type::StructTyID) &&
41 "invalid CallInst type!");
42 else if (!isa<Constant>(this) && !isa<BasicBlock>(this))
43 assert((Ty->isFirstClassType() || Ty == Type::VoidTy ||
44 isa<OpaqueType>(ty)) &&
45 "Cannot create non-first-class values except for constants!");
49 #ifndef NDEBUG // Only in -g mode...
50 // Check to make sure that there are no uses of this value that are still
51 // around when the value is destroyed. If there are, then we have a dangling
52 // reference and something is wrong. This code is here to print out what is
53 // still being referenced. The value in question should be printed as
57 DOUT << "While deleting: " << *Ty << " %" << getNameStr() << "\n";
58 for (use_iterator I = use_begin(), E = use_end(); I != E; ++I)
59 DOUT << "Use still stuck around after Def is destroyed:"
63 assert(use_empty() && "Uses remain when a value is destroyed!");
65 // If this value is named, destroy the name. This should not be in a symtab
70 // There should be no uses of this object anymore, remove it.
71 LeakDetector::removeGarbageObject(this);
74 /// hasNUses - Return true if this Value has exactly N users.
76 bool Value::hasNUses(unsigned N) const {
77 use_const_iterator UI = use_begin(), E = use_end();
80 if (UI == E) return false; // Too few.
84 /// hasNUsesOrMore - Return true if this value has N users or more. This is
85 /// logically equivalent to getNumUses() >= N.
87 bool Value::hasNUsesOrMore(unsigned N) const {
88 use_const_iterator UI = use_begin(), E = use_end();
91 if (UI == E) return false; // Too few.
97 /// getNumUses - This method computes the number of uses of this Value. This
98 /// is a linear time operation. Use hasOneUse or hasNUses to check for specific
100 unsigned Value::getNumUses() const {
101 return (unsigned)std::distance(use_begin(), use_end());
104 static bool getSymTab(Value *V, ValueSymbolTable *&ST) {
106 if (Instruction *I = dyn_cast<Instruction>(V)) {
107 if (BasicBlock *P = I->getParent())
108 if (Function *PP = P->getParent())
109 ST = &PP->getValueSymbolTable();
110 } else if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
111 if (Function *P = BB->getParent())
112 ST = &P->getValueSymbolTable();
113 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
114 if (Module *P = GV->getParent())
115 ST = &P->getValueSymbolTable();
116 } else if (Argument *A = dyn_cast<Argument>(V)) {
117 if (Function *P = A->getParent())
118 ST = &P->getValueSymbolTable();
120 assert(isa<Constant>(V) && "Unknown value type!");
121 return true; // no name is setable for this.
126 /// getNameStart - Return a pointer to a null terminated string for this name.
127 /// Note that names can have null characters within the string as well as at
128 /// their end. This always returns a non-null pointer.
129 const char *Value::getNameStart() const {
130 if (Name == 0) return "";
131 return Name->getKeyData();
134 /// getNameLen - Return the length of the string, correctly handling nul
135 /// characters embedded into them.
136 unsigned Value::getNameLen() const {
137 return Name ? Name->getKeyLength() : 0;
140 /// isName - Return true if this value has the name specified by the provided
141 /// nul terminated string.
142 bool Value::isName(const char *N) const {
143 unsigned InLen = strlen(N);
144 return InLen == getNameLen() && memcmp(getNameStart(), N, InLen) == 0;
148 std::string Value::getNameStr() const {
149 if (Name == 0) return "";
150 return std::string(Name->getKeyData(),
151 Name->getKeyData()+Name->getKeyLength());
154 void Value::setName(const std::string &name) {
155 setName(&name[0], name.size());
158 void Value::setName(const char *Name) {
159 setName(Name, Name ? strlen(Name) : 0);
162 void Value::setName(const char *NameStr, unsigned NameLen) {
163 if (NameLen == 0 && !hasName()) return;
164 assert(getType() != Type::VoidTy && "Cannot assign a name to void values!");
166 // Get the symbol table to update for this object.
167 ValueSymbolTable *ST;
168 if (getSymTab(this, ST))
169 return; // Cannot set a name on this value (e.g. constant).
171 if (!ST) { // No symbol table to update? Just do the change.
173 // Free the name for this value.
180 // Name isn't changing?
181 if (NameLen == Name->getKeyLength() &&
182 !memcmp(Name->getKeyData(), NameStr, NameLen))
187 // NOTE: Could optimize for the case the name is shrinking to not deallocate
190 // Create the new name.
191 Name = ValueName::Create(NameStr, NameStr+NameLen);
192 Name->setValue(this);
196 // NOTE: Could optimize for the case the name is shrinking to not deallocate
199 // Name isn't changing?
200 if (NameLen == Name->getKeyLength() &&
201 !memcmp(Name->getKeyData(), NameStr, NameLen))
205 ST->removeValueName(Name);
213 // Name is changing to something new.
214 Name = ST->createValueName(NameStr, NameLen, this);
218 /// takeName - transfer the name from V to this value, setting V's name to
219 /// empty. It is an error to call V->takeName(V).
220 void Value::takeName(Value *V) {
221 ValueSymbolTable *ST = 0;
222 // If this value has a name, drop it.
224 // Get the symtab this is in.
225 if (getSymTab(this, ST)) {
226 // We can't set a name on this value, but we need to clear V's name if
228 if (V->hasName()) V->setName(0, 0);
229 return; // Cannot set a name on this value (e.g. constant).
234 ST->removeValueName(Name);
239 // Now we know that this has no name.
241 // If V has no name either, we're done.
242 if (!V->hasName()) return;
244 // Get this's symtab if we didn't before.
246 if (getSymTab(this, ST)) {
249 return; // Cannot set a name on this value (e.g. constant).
253 // Get V's ST, this should always succed, because V has a name.
254 ValueSymbolTable *VST;
255 bool Failure = getSymTab(V, VST);
256 assert(!Failure && "V has a name, so it should have a ST!");
258 // If these values are both in the same symtab, we can do this very fast.
259 // This works even if both values have no symtab yet.
264 Name->setValue(this);
268 // Otherwise, things are slightly more complex. Remove V's name from VST and
269 // then reinsert it into ST.
272 VST->removeValueName(V->Name);
275 Name->setValue(this);
278 ST->reinsertValue(this);
282 // uncheckedReplaceAllUsesWith - This is exactly the same as replaceAllUsesWith,
283 // except that it doesn't have all of the asserts. The asserts fail because we
284 // are half-way done resolving types, which causes some types to exist as two
285 // different Type*'s at the same time. This is a sledgehammer to work around
288 void Value::uncheckedReplaceAllUsesWith(Value *New) {
289 while (!use_empty()) {
291 // Must handle Constants specially, we cannot call replaceUsesOfWith on a
292 // constant because they are uniqued.
293 if (Constant *C = dyn_cast<Constant>(U.getUser())) {
294 if (!isa<GlobalValue>(C)) {
295 C->replaceUsesOfWithOnConstant(this, New, &U);
304 void Value::replaceAllUsesWith(Value *New) {
305 assert(New && "Value::replaceAllUsesWith(<null>) is invalid!");
306 assert(New != this && "this->replaceAllUsesWith(this) is NOT valid!");
307 assert(New->getType() == getType() &&
308 "replaceAllUses of value with new value of different type!");
310 uncheckedReplaceAllUsesWith(New);
313 Value *Value::stripPointerCasts() {
314 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
315 if (CE->getOpcode() == Instruction::BitCast) {
316 if (isa<PointerType>(CE->getOperand(0)->getType()))
317 return CE->getOperand(0)->stripPointerCasts();
318 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
319 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
320 if (!CE->getOperand(i)->isNullValue())
322 return CE->getOperand(0)->stripPointerCasts();
327 if (BitCastInst *CI = dyn_cast<BitCastInst>(this)) {
328 if (isa<PointerType>(CI->getOperand(0)->getType()))
329 return CI->getOperand(0)->stripPointerCasts();
330 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(this)) {
331 if (GEP->hasAllZeroIndices())
332 return GEP->getOperand(0)->stripPointerCasts();
337 //===----------------------------------------------------------------------===//
339 //===----------------------------------------------------------------------===//
341 // replaceUsesOfWith - Replaces all references to the "From" definition with
342 // references to the "To" definition.
344 void User::replaceUsesOfWith(Value *From, Value *To) {
345 if (From == To) return; // Duh what?
347 assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
348 "Cannot call User::replaceUsesofWith on a constant!");
350 for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
351 if (getOperand(i) == From) { // Is This operand is pointing to oldval?
352 // The side effects of this setOperand call include linking to
353 // "To", adding "this" to the uses list of To, and
354 // most importantly, removing "this" from the use list of "From".
355 setOperand(i, To); // Fix it now...
359 void *User::operator new(size_t s, unsigned Us) {
360 void *Storage = ::operator new(s + sizeof(Use) * Us);
361 Use *Start = static_cast<Use*>(Storage);
362 Use *End = Start + Us;
363 User *Obj = reinterpret_cast<User*>(End);
364 Obj->OperandList = Start;
365 Obj->NumOperands = Us;
366 Use::initTags(Start, End);
370 void User::operator delete(void *Usr) {
371 User *Start = static_cast<User*>(Usr);
372 Use *Storage = static_cast<Use*>(Usr) - Start->NumOperands;
373 ::operator delete(Storage == Start->OperandList