d64046a7bf9829f7fd2b59e48324622de8a98f31
[oota-llvm.git] / lib / IR / 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 IR
11 // library.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/IR/GlobalValue.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/GlobalAlias.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/LeakDetector.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Support/ErrorHandling.h"
25 using namespace llvm;
26
27 //===----------------------------------------------------------------------===//
28 //                            GlobalValue Class
29 //===----------------------------------------------------------------------===//
30
31 bool GlobalValue::isMaterializable() const {
32   return getParent() && getParent()->isMaterializable(this);
33 }
34 bool GlobalValue::isDematerializable() const {
35   return getParent() && getParent()->isDematerializable(this);
36 }
37 bool GlobalValue::Materialize(std::string *ErrInfo) {
38   return getParent()->Materialize(this, ErrInfo);
39 }
40 void GlobalValue::Dematerialize() {
41   getParent()->Dematerialize(this);
42 }
43
44 const DataLayout *GlobalValue::getDataLayout() const {
45   return getParent()->getDataLayout();
46 }
47
48 /// Override destroyConstant to make sure it doesn't get called on
49 /// GlobalValue's because they shouldn't be treated like other constants.
50 void GlobalValue::destroyConstant() {
51   llvm_unreachable("You can't GV->destroyConstant()!");
52 }
53
54 /// copyAttributesFrom - copy all additional attributes (those not needed to
55 /// create a GlobalValue) from the GlobalValue Src to this one.
56 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
57   setVisibility(Src->getVisibility());
58   setUnnamedAddr(Src->hasUnnamedAddr());
59   setDLLStorageClass(Src->getDLLStorageClass());
60 }
61
62 unsigned GlobalValue::getAlignment() const {
63   if (auto *GA = dyn_cast<GlobalAlias>(this))
64     return GA->getAliasedGlobal()->getAlignment();
65
66   return cast<GlobalObject>(this)->getAlignment();
67 }
68
69 void GlobalObject::setAlignment(unsigned Align) {
70   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
71   assert(Align <= MaximumAlignment &&
72          "Alignment is greater than MaximumAlignment!");
73   setGlobalValueSubClassData(Log2_32(Align) + 1);
74   assert(getAlignment() == Align && "Alignment representation error!");
75 }
76
77 void GlobalObject::copyAttributesFrom(const GlobalValue *Src) {
78   const auto *GV = cast<GlobalObject>(Src);
79   GlobalValue::copyAttributesFrom(GV);
80   setAlignment(GV->getAlignment());
81   setSection(GV->getSection());
82 }
83
84 const std::string &GlobalValue::getSection() const {
85   if (auto *GA = dyn_cast<GlobalAlias>(this))
86     return GA->getAliasedGlobal()->getSection();
87   return cast<GlobalObject>(this)->getSection();
88 }
89
90 void GlobalObject::setSection(StringRef S) { Section = S; }
91
92 bool GlobalValue::isDeclaration() const {
93   // Globals are definitions if they have an initializer.
94   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
95     return GV->getNumOperands() == 0;
96
97   // Functions are definitions if they have a body.
98   if (const Function *F = dyn_cast<Function>(this))
99     return F->empty();
100
101   // Aliases are always definitions.
102   assert(isa<GlobalAlias>(this));
103   return false;
104 }
105
106 //===----------------------------------------------------------------------===//
107 // GlobalVariable Implementation
108 //===----------------------------------------------------------------------===//
109
110 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
111                                Constant *InitVal, const Twine &Name,
112                                ThreadLocalMode TLMode, unsigned AddressSpace,
113                                bool isExternallyInitialized)
114     : GlobalObject(PointerType::get(Ty, AddressSpace), Value::GlobalVariableVal,
115                    OperandTraits<GlobalVariable>::op_begin(this),
116                    InitVal != nullptr, Link, Name),
117       isConstantGlobal(constant), threadLocalMode(TLMode),
118       isExternallyInitializedConstant(isExternallyInitialized) {
119   if (InitVal) {
120     assert(InitVal->getType() == Ty &&
121            "Initializer should be the same type as the GlobalVariable!");
122     Op<0>() = InitVal;
123   }
124
125   LeakDetector::addGarbageObject(this);
126 }
127
128 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
129                                LinkageTypes Link, Constant *InitVal,
130                                const Twine &Name, GlobalVariable *Before,
131                                ThreadLocalMode TLMode, unsigned AddressSpace,
132                                bool isExternallyInitialized)
133     : GlobalObject(PointerType::get(Ty, AddressSpace), Value::GlobalVariableVal,
134                    OperandTraits<GlobalVariable>::op_begin(this),
135                    InitVal != nullptr, Link, Name),
136       isConstantGlobal(constant), threadLocalMode(TLMode),
137       isExternallyInitializedConstant(isExternallyInitialized) {
138   if (InitVal) {
139     assert(InitVal->getType() == Ty &&
140            "Initializer should be the same type as the GlobalVariable!");
141     Op<0>() = InitVal;
142   }
143
144   LeakDetector::addGarbageObject(this);
145
146   if (Before)
147     Before->getParent()->getGlobalList().insert(Before, this);
148   else
149     M.getGlobalList().push_back(this);
150 }
151
152 void GlobalVariable::setParent(Module *parent) {
153   if (getParent())
154     LeakDetector::addGarbageObject(this);
155   Parent = parent;
156   if (getParent())
157     LeakDetector::removeGarbageObject(this);
158 }
159
160 void GlobalVariable::removeFromParent() {
161   getParent()->getGlobalList().remove(this);
162 }
163
164 void GlobalVariable::eraseFromParent() {
165   getParent()->getGlobalList().erase(this);
166 }
167
168 void GlobalVariable::replaceUsesOfWithOnConstant(Value *From, Value *To,
169                                                  Use *U) {
170   // If you call this, then you better know this GVar has a constant
171   // initializer worth replacing. Enforce that here.
172   assert(getNumOperands() == 1 &&
173          "Attempt to replace uses of Constants on a GVar with no initializer");
174
175   // And, since you know it has an initializer, the From value better be
176   // the initializer :)
177   assert(getOperand(0) == From &&
178          "Attempt to replace wrong constant initializer in GVar");
179
180   // And, you better have a constant for the replacement value
181   assert(isa<Constant>(To) &&
182          "Attempt to replace GVar initializer with non-constant");
183
184   // Okay, preconditions out of the way, replace the constant initializer.
185   this->setOperand(0, cast<Constant>(To));
186 }
187
188 void GlobalVariable::setInitializer(Constant *InitVal) {
189   if (!InitVal) {
190     if (hasInitializer()) {
191       Op<0>().set(nullptr);
192       NumOperands = 0;
193     }
194   } else {
195     assert(InitVal->getType() == getType()->getElementType() &&
196            "Initializer type must match GlobalVariable type");
197     if (!hasInitializer())
198       NumOperands = 1;
199     Op<0>().set(InitVal);
200   }
201 }
202
203 /// copyAttributesFrom - copy all additional attributes (those not needed to
204 /// create a GlobalVariable) from the GlobalVariable Src to this one.
205 void GlobalVariable::copyAttributesFrom(const GlobalValue *Src) {
206   assert(isa<GlobalVariable>(Src) && "Expected a GlobalVariable!");
207   GlobalObject::copyAttributesFrom(Src);
208   const GlobalVariable *SrcVar = cast<GlobalVariable>(Src);
209   setThreadLocalMode(SrcVar->getThreadLocalMode());
210 }
211
212
213 //===----------------------------------------------------------------------===//
214 // GlobalAlias Implementation
215 //===----------------------------------------------------------------------===//
216
217 GlobalAlias::GlobalAlias(Type *Ty, LinkageTypes Link,
218                          const Twine &Name, Constant* aliasee,
219                          Module *ParentModule)
220   : GlobalValue(Ty, Value::GlobalAliasVal, &Op<0>(), 1, Link, Name) {
221   LeakDetector::addGarbageObject(this);
222
223   if (aliasee)
224     assert(aliasee->getType() == Ty && "Alias and aliasee types should match!");
225   Op<0>() = aliasee;
226
227   if (ParentModule)
228     ParentModule->getAliasList().push_back(this);
229 }
230
231 void GlobalAlias::setParent(Module *parent) {
232   if (getParent())
233     LeakDetector::addGarbageObject(this);
234   Parent = parent;
235   if (getParent())
236     LeakDetector::removeGarbageObject(this);
237 }
238
239 void GlobalAlias::removeFromParent() {
240   getParent()->getAliasList().remove(this);
241 }
242
243 void GlobalAlias::eraseFromParent() {
244   getParent()->getAliasList().erase(this);
245 }
246
247 void GlobalAlias::setAliasee(Constant *Aliasee) {
248   assert((!Aliasee || Aliasee->getType() == getType()) &&
249          "Alias and aliasee types should match!");
250
251   setOperand(0, Aliasee);
252 }
253
254 static GlobalValue *getAliaseeGV(GlobalAlias *GA) {
255   Constant *C = GA->getAliasee();
256   assert(C && "Must alias something");
257
258   if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
259     return GV;
260
261   ConstantExpr *CE = cast<ConstantExpr>(C);
262   assert((CE->getOpcode() == Instruction::BitCast ||
263           CE->getOpcode() == Instruction::AddrSpaceCast ||
264           CE->getOpcode() == Instruction::GetElementPtr) &&
265          "Unsupported aliasee");
266
267   return cast<GlobalValue>(CE->getOperand(0));
268 }
269
270 GlobalObject *GlobalAlias::getAliasedGlobal() {
271   SmallPtrSet<GlobalValue*, 3> Visited;
272
273   GlobalAlias *GA = this;
274
275   for (;;) {
276     GlobalValue *GV = getAliaseeGV(GA);
277     if (!Visited.insert(GV))
278       return nullptr;
279
280     // Iterate over aliasing chain.
281     GA = dyn_cast<GlobalAlias>(GV);
282     if (!GA)
283       return cast<GlobalObject>(GV);
284   }
285 }
286
287 uint64_t GlobalAlias::calculateOffset(const DataLayout &DL) const {
288   uint64_t Offset = 0;
289   const Constant *C = this;
290   while (C) {
291     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(C)) {
292       C = GA->getAliasee();
293     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
294       if (CE->getOpcode() == Instruction::GetElementPtr) {
295         std::vector<Value*> Args;
296         for (unsigned I = 1; I < CE->getNumOperands(); ++I)
297           Args.push_back(CE->getOperand(I));
298         Offset += DL.getIndexedOffset(CE->getOperand(0)->getType(), Args);
299       }
300       C = CE->getOperand(0);
301     } else if (isa<GlobalValue>(C)) {
302       return Offset;
303     } else {
304       assert(0 && "Unexpected type in alias chain!");
305       return 0;
306     }
307   }
308   return Offset;
309 }