94bf3dea9ab3ca05b275286d61dfc476709f6f05
[oota-llvm.git] / lib / VMCore / Globals.cpp
1 //===-- Globals.cpp - Implement the GlobalValue & GlobalVariable 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 GlobalValue & GlobalVariable classes for the VMCore
11 // library.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Constants.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/GlobalAlias.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/LeakDetector.h"
23 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 //                            GlobalValue Class
27 //===----------------------------------------------------------------------===//
28
29 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
30 /// it.  This involves recursively eliminating any dead users of the
31 /// constantexpr.
32 static bool removeDeadUsersOfConstant(const Constant *C) {
33   if (isa<GlobalValue>(C)) return false; // Cannot remove this
34
35   while (!C->use_empty()) {
36     const Constant *User = dyn_cast<Constant>(C->use_back());
37     if (!User) return false; // Non-constant usage;
38     if (!removeDeadUsersOfConstant(User))
39       return false; // Constant wasn't dead
40   }
41
42   const_cast<Constant*>(C)->destroyConstant();
43   return true;
44 }
45
46 /// removeDeadConstantUsers - If there are any dead constant users dangling
47 /// off of this global value, remove them.  This method is useful for clients
48 /// that want to check to see if a global is unused, but don't want to deal
49 /// with potentially dead constants hanging off of the globals.
50 void GlobalValue::removeDeadConstantUsers() const {
51   Value::use_const_iterator I = use_begin(), E = use_end();
52   Value::use_const_iterator LastNonDeadUser = E;
53   while (I != E) {
54     if (const Constant *User = dyn_cast<Constant>(*I)) {
55       if (!removeDeadUsersOfConstant(User)) {
56         // If the constant wasn't dead, remember that this was the last live use
57         // and move on to the next constant.
58         LastNonDeadUser = I;
59         ++I;
60       } else {
61         // If the constant was dead, then the iterator is invalidated.
62         if (LastNonDeadUser == E) {
63           I = use_begin();
64           if (I == E) break;
65         } else {
66           I = LastNonDeadUser;
67           ++I;
68         }
69       }
70     } else {
71       LastNonDeadUser = I;
72       ++I;
73     }
74   }
75 }
76
77
78 /// Override destroyConstant to make sure it doesn't get called on
79 /// GlobalValue's because they shouldn't be treated like other constants.
80 void GlobalValue::destroyConstant() {
81   llvm_unreachable("You can't GV->destroyConstant()!");
82 }
83
84 /// copyAttributesFrom - copy all additional attributes (those not needed to
85 /// create a GlobalValue) from the GlobalValue Src to this one.
86 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
87   setAlignment(Src->getAlignment());
88   setSection(Src->getSection());
89   setVisibility(Src->getVisibility());
90 }
91
92
93 //===----------------------------------------------------------------------===//
94 // GlobalVariable Implementation
95 //===----------------------------------------------------------------------===//
96
97 GlobalVariable::GlobalVariable(const Type *Ty, bool constant, LinkageTypes Link,
98                                Constant *InitVal, const Twine &Name,
99                                bool ThreadLocal, unsigned AddressSpace)
100   : GlobalValue(PointerType::get(Ty, AddressSpace), 
101                 Value::GlobalVariableVal,
102                 OperandTraits<GlobalVariable>::op_begin(this),
103                 InitVal != 0, Link, Name),
104     isConstantGlobal(constant), isThreadLocalSymbol(ThreadLocal) {
105   if (InitVal) {
106     assert(InitVal->getType() == Ty &&
107            "Initializer should be the same type as the GlobalVariable!");
108     Op<0>() = InitVal;
109   }
110
111   LeakDetector::addGarbageObject(this);
112 }
113
114 GlobalVariable::GlobalVariable(Module &M, const Type *Ty, bool constant,
115                                LinkageTypes Link, Constant *InitVal,
116                                const Twine &Name,
117                                GlobalVariable *Before, bool ThreadLocal,
118                                unsigned AddressSpace)
119   : GlobalValue(PointerType::get(Ty, AddressSpace), 
120                 Value::GlobalVariableVal,
121                 OperandTraits<GlobalVariable>::op_begin(this),
122                 InitVal != 0, Link, Name),
123     isConstantGlobal(constant), isThreadLocalSymbol(ThreadLocal) {
124   if (InitVal) {
125     assert(InitVal->getType() == Ty &&
126            "Initializer should be the same type as the GlobalVariable!");
127     Op<0>() = InitVal;
128   }
129   
130   LeakDetector::addGarbageObject(this);
131   
132   if (Before)
133     Before->getParent()->getGlobalList().insert(Before, this);
134   else
135     M.getGlobalList().push_back(this);
136 }
137
138 void GlobalVariable::setParent(Module *parent) {
139   if (getParent())
140     LeakDetector::addGarbageObject(this);
141   Parent = parent;
142   if (getParent())
143     LeakDetector::removeGarbageObject(this);
144 }
145
146 void GlobalVariable::removeFromParent() {
147   getParent()->getGlobalList().remove(this);
148 }
149
150 void GlobalVariable::eraseFromParent() {
151   getParent()->getGlobalList().erase(this);
152 }
153
154 void GlobalVariable::replaceUsesOfWithOnConstant(Value *From, Value *To,
155                                                  Use *U) {
156   // If you call this, then you better know this GVar has a constant
157   // initializer worth replacing. Enforce that here.
158   assert(getNumOperands() == 1 &&
159          "Attempt to replace uses of Constants on a GVar with no initializer");
160
161   // And, since you know it has an initializer, the From value better be
162   // the initializer :)
163   assert(getOperand(0) == From &&
164          "Attempt to replace wrong constant initializer in GVar");
165
166   // And, you better have a constant for the replacement value
167   assert(isa<Constant>(To) &&
168          "Attempt to replace GVar initializer with non-constant");
169
170   // Okay, preconditions out of the way, replace the constant initializer.
171   this->setOperand(0, cast<Constant>(To));
172 }
173
174 void GlobalVariable::setInitializer(Constant *InitVal) {
175   if (InitVal == 0) {
176     if (hasInitializer()) {
177       Op<0>().set(0);
178       NumOperands = 0;
179     }
180   } else {
181     assert(InitVal->getType() == getType()->getElementType() &&
182            "Initializer type must match GlobalVariable type");
183     if (!hasInitializer())
184       NumOperands = 1;
185     Op<0>().set(InitVal);
186   }
187 }
188
189 /// copyAttributesFrom - copy all additional attributes (those not needed to
190 /// create a GlobalVariable) from the GlobalVariable Src to this one.
191 void GlobalVariable::copyAttributesFrom(const GlobalValue *Src) {
192   assert(isa<GlobalVariable>(Src) && "Expected a GlobalVariable!");
193   GlobalValue::copyAttributesFrom(Src);
194   const GlobalVariable *SrcVar = cast<GlobalVariable>(Src);
195   setThreadLocal(SrcVar->isThreadLocal());
196 }
197
198
199 //===----------------------------------------------------------------------===//
200 // GlobalAlias Implementation
201 //===----------------------------------------------------------------------===//
202
203 GlobalAlias::GlobalAlias(const Type *Ty, LinkageTypes Link,
204                          const Twine &Name, Constant* aliasee,
205                          Module *ParentModule)
206   : GlobalValue(Ty, Value::GlobalAliasVal, &Op<0>(), 1, Link, Name) {
207   LeakDetector::addGarbageObject(this);
208
209   if (aliasee)
210     assert(aliasee->getType() == Ty && "Alias and aliasee types should match!");
211   Op<0>() = aliasee;
212
213   if (ParentModule)
214     ParentModule->getAliasList().push_back(this);
215 }
216
217 void GlobalAlias::setParent(Module *parent) {
218   if (getParent())
219     LeakDetector::addGarbageObject(this);
220   Parent = parent;
221   if (getParent())
222     LeakDetector::removeGarbageObject(this);
223 }
224
225 void GlobalAlias::removeFromParent() {
226   getParent()->getAliasList().remove(this);
227 }
228
229 void GlobalAlias::eraseFromParent() {
230   getParent()->getAliasList().erase(this);
231 }
232
233 bool GlobalAlias::isDeclaration() const {
234   const GlobalValue* AV = getAliasedGlobal();
235   if (AV)
236     return AV->isDeclaration();
237   else
238     return false;
239 }
240
241 void GlobalAlias::setAliasee(Constant *Aliasee) 
242 {
243   if (Aliasee)
244     assert(Aliasee->getType() == getType() &&
245            "Alias and aliasee types should match!");
246   
247   setOperand(0, Aliasee);
248 }
249
250 const GlobalValue *GlobalAlias::getAliasedGlobal() const {
251   const Constant *C = getAliasee();
252   if (C) {
253     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
254       return GV;
255     else {
256       const ConstantExpr *CE = 0;
257       if ((CE = dyn_cast<ConstantExpr>(C)) &&
258           (CE->getOpcode() == Instruction::BitCast || 
259            CE->getOpcode() == Instruction::GetElementPtr))
260         return dyn_cast<GlobalValue>(CE->getOperand(0));
261       else
262         llvm_unreachable("Unsupported aliasee");
263     }
264   }
265   return 0;
266 }
267
268 const GlobalValue *GlobalAlias::resolveAliasedGlobal(bool stopOnWeak) const {
269   SmallPtrSet<const GlobalValue*, 3> Visited;
270
271   // Check if we need to stop early.
272   if (stopOnWeak && mayBeOverridden())
273     return this;
274
275   const GlobalValue *GV = getAliasedGlobal();
276   Visited.insert(GV);
277
278   // Iterate over aliasing chain, stopping on weak alias if necessary.
279   while (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) {
280     if (stopOnWeak && GA->mayBeOverridden())
281       break;
282
283     GV = GA->getAliasedGlobal();
284
285     if (!Visited.insert(GV))
286       return NULL;
287   }
288
289   return GV;
290 }