Sets insertion point of fake cond branch to the last phi node in the block
[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/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/GlobalAlias.h"
20 #include "llvm/IR/GlobalValue.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/Support/ErrorHandling.h"
25 using namespace llvm;
26
27 //===----------------------------------------------------------------------===//
28 //                            GlobalValue Class
29 //===----------------------------------------------------------------------===//
30
31 bool GlobalValue::isMaterializable() const {
32   if (const Function *F = dyn_cast<Function>(this))
33     return F->isMaterializable();
34   return false;
35 }
36 std::error_code GlobalValue::materialize() {
37   return getParent()->materialize(this);
38 }
39
40 /// Override destroyConstantImpl to make sure it doesn't get called on
41 /// GlobalValue's because they shouldn't be treated like other constants.
42 void GlobalValue::destroyConstantImpl() {
43   llvm_unreachable("You can't GV->destroyConstantImpl()!");
44 }
45
46 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
47   llvm_unreachable("Unsupported class for handleOperandChange()!");
48 }
49
50 /// copyAttributesFrom - copy all additional attributes (those not needed to
51 /// create a GlobalValue) from the GlobalValue Src to this one.
52 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
53   setVisibility(Src->getVisibility());
54   setUnnamedAddr(Src->hasUnnamedAddr());
55   setDLLStorageClass(Src->getDLLStorageClass());
56 }
57
58 unsigned GlobalValue::getAlignment() const {
59   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
60     // In general we cannot compute this at the IR level, but we try.
61     if (const GlobalObject *GO = GA->getBaseObject())
62       return GO->getAlignment();
63
64     // FIXME: we should also be able to handle:
65     // Alias = Global + Offset
66     // Alias = Absolute
67     return 0;
68   }
69   return cast<GlobalObject>(this)->getAlignment();
70 }
71
72 void GlobalObject::setAlignment(unsigned Align) {
73   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
74   assert(Align <= MaximumAlignment &&
75          "Alignment is greater than MaximumAlignment!");
76   unsigned AlignmentData = Log2_32(Align) + 1;
77   unsigned OldData = getGlobalValueSubClassData();
78   setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
79   assert(getAlignment() == Align && "Alignment representation error!");
80 }
81
82 unsigned GlobalObject::getGlobalObjectSubClassData() const {
83   unsigned ValueData = getGlobalValueSubClassData();
84   return ValueData >> AlignmentBits;
85 }
86
87 void GlobalObject::setGlobalObjectSubClassData(unsigned Val) {
88   unsigned OldData = getGlobalValueSubClassData();
89   setGlobalValueSubClassData((OldData & AlignmentMask) |
90                              (Val << AlignmentBits));
91   assert(getGlobalObjectSubClassData() == Val && "representation error");
92 }
93
94 void GlobalObject::copyAttributesFrom(const GlobalValue *Src) {
95   GlobalValue::copyAttributesFrom(Src);
96   if (const auto *GV = dyn_cast<GlobalObject>(Src)) {
97     setAlignment(GV->getAlignment());
98     setSection(GV->getSection());
99   }
100 }
101
102 const char *GlobalValue::getSection() const {
103   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
104     // In general we cannot compute this at the IR level, but we try.
105     if (const GlobalObject *GO = GA->getBaseObject())
106       return GO->getSection();
107     return "";
108   }
109   return cast<GlobalObject>(this)->getSection();
110 }
111
112 Comdat *GlobalValue::getComdat() {
113   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
114     // In general we cannot compute this at the IR level, but we try.
115     if (const GlobalObject *GO = GA->getBaseObject())
116       return const_cast<GlobalObject *>(GO)->getComdat();
117     return nullptr;
118   }
119   return cast<GlobalObject>(this)->getComdat();
120 }
121
122 void GlobalObject::setSection(StringRef S) { Section = S; }
123
124 bool GlobalValue::isDeclaration() const {
125   // Globals are definitions if they have an initializer.
126   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
127     return GV->getNumOperands() == 0;
128
129   // Functions are definitions if they have a body.
130   if (const Function *F = dyn_cast<Function>(this))
131     return F->empty() && !F->isMaterializable();
132
133   // Aliases are always definitions.
134   assert(isa<GlobalAlias>(this));
135   return false;
136 }
137
138 bool GlobalValue::canIncreaseAlignment() const {
139   // Firstly, can only increase the alignment of a global if it
140   // is a strong definition.
141   if (!isStrongDefinitionForLinker())
142     return false;
143
144   // It also has to either not have a section defined, or, not have
145   // alignment specified. (If it is assigned a section, the global
146   // could be densely packed with other objects in the section, and
147   // increasing the alignment could cause padding issues.)
148   if (hasSection() && getAlignment() > 0)
149     return false;
150
151   // On ELF platforms, we're further restricted in that we can't
152   // increase the alignment of any variable which might be emitted
153   // into a shared library, and which is exported. If the main
154   // executable accesses a variable found in a shared-lib, the main
155   // exe actually allocates memory for and exports the symbol ITSELF,
156   // overriding the symbol found in the library. That is, at link
157   // time, the observed alignment of the variable is copied into the
158   // executable binary. (A COPY relocation is also generated, to copy
159   // the initial data from the shadowed variable in the shared-lib
160   // into the location in the main binary, before running code.)
161   //
162   // And thus, even though you might think you are defining the
163   // global, and allocating the memory for the global in your object
164   // file, and thus should be able to set the alignment arbitrarily,
165   // that's not actually true. Doing so can cause an ABI breakage; an
166   // executable might have already been built with the previous
167   // alignment of the variable, and then assuming an increased
168   // alignment will be incorrect.
169
170   // Conservatively assume ELF if there's no parent pointer.
171   bool isELF =
172       (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
173   if (isELF && hasDefaultVisibility() && !hasLocalLinkage())
174     return false;
175
176   return true;
177 }
178
179 //===----------------------------------------------------------------------===//
180 // GlobalVariable Implementation
181 //===----------------------------------------------------------------------===//
182
183 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
184                                Constant *InitVal, const Twine &Name,
185                                ThreadLocalMode TLMode, unsigned AddressSpace,
186                                bool isExternallyInitialized)
187     : GlobalObject(Ty, Value::GlobalVariableVal,
188                    OperandTraits<GlobalVariable>::op_begin(this),
189                    InitVal != nullptr, Link, Name, AddressSpace),
190       isConstantGlobal(constant),
191       isExternallyInitializedConstant(isExternallyInitialized) {
192   setThreadLocalMode(TLMode);
193   if (InitVal) {
194     assert(InitVal->getType() == Ty &&
195            "Initializer should be the same type as the GlobalVariable!");
196     Op<0>() = InitVal;
197   }
198 }
199
200 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
201                                LinkageTypes Link, Constant *InitVal,
202                                const Twine &Name, GlobalVariable *Before,
203                                ThreadLocalMode TLMode, unsigned AddressSpace,
204                                bool isExternallyInitialized)
205     : GlobalObject(Ty, Value::GlobalVariableVal,
206                    OperandTraits<GlobalVariable>::op_begin(this),
207                    InitVal != nullptr, Link, Name, AddressSpace),
208       isConstantGlobal(constant),
209       isExternallyInitializedConstant(isExternallyInitialized) {
210   setThreadLocalMode(TLMode);
211   if (InitVal) {
212     assert(InitVal->getType() == Ty &&
213            "Initializer should be the same type as the GlobalVariable!");
214     Op<0>() = InitVal;
215   }
216
217   if (Before)
218     Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
219   else
220     M.getGlobalList().push_back(this);
221 }
222
223 void GlobalVariable::setParent(Module *parent) {
224   Parent = parent;
225 }
226
227 void GlobalVariable::removeFromParent() {
228   getParent()->getGlobalList().remove(getIterator());
229 }
230
231 void GlobalVariable::eraseFromParent() {
232   getParent()->getGlobalList().erase(getIterator());
233 }
234
235 void GlobalVariable::setInitializer(Constant *InitVal) {
236   if (!InitVal) {
237     if (hasInitializer()) {
238       // Note, the num operands is used to compute the offset of the operand, so
239       // the order here matters.  Clearing the operand then clearing the num
240       // operands ensures we have the correct offset to the operand.
241       Op<0>().set(nullptr);
242       setGlobalVariableNumOperands(0);
243     }
244   } else {
245     assert(InitVal->getType() == getType()->getElementType() &&
246            "Initializer type must match GlobalVariable type");
247     // Note, the num operands is used to compute the offset of the operand, so
248     // the order here matters.  We need to set num operands to 1 first so that
249     // we get the correct offset to the first operand when we set it.
250     if (!hasInitializer())
251       setGlobalVariableNumOperands(1);
252     Op<0>().set(InitVal);
253   }
254 }
255
256 /// Copy all additional attributes (those not needed to create a GlobalVariable)
257 /// from the GlobalVariable Src to this one.
258 void GlobalVariable::copyAttributesFrom(const GlobalValue *Src) {
259   GlobalObject::copyAttributesFrom(Src);
260   if (const GlobalVariable *SrcVar = dyn_cast<GlobalVariable>(Src)) {
261     setThreadLocalMode(SrcVar->getThreadLocalMode());
262     setExternallyInitialized(SrcVar->isExternallyInitialized());
263   }
264 }
265
266
267 //===----------------------------------------------------------------------===//
268 // GlobalAlias Implementation
269 //===----------------------------------------------------------------------===//
270
271 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
272                          const Twine &Name, Constant *Aliasee,
273                          Module *ParentModule)
274     : GlobalValue(Ty, Value::GlobalAliasVal, &Op<0>(), 1, Link, Name,
275                   AddressSpace) {
276   Op<0>() = Aliasee;
277
278   if (ParentModule)
279     ParentModule->getAliasList().push_back(this);
280 }
281
282 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
283                                  LinkageTypes Link, const Twine &Name,
284                                  Constant *Aliasee, Module *ParentModule) {
285   return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
286 }
287
288 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
289                                  LinkageTypes Linkage, const Twine &Name,
290                                  Module *Parent) {
291   return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
292 }
293
294 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
295                                  LinkageTypes Linkage, const Twine &Name,
296                                  GlobalValue *Aliasee) {
297   return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
298 }
299
300 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
301                                  GlobalValue *Aliasee) {
302   PointerType *PTy = Aliasee->getType();
303   return create(PTy->getElementType(), PTy->getAddressSpace(), Link, Name,
304                 Aliasee);
305 }
306
307 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
308   return create(Aliasee->getLinkage(), Name, Aliasee);
309 }
310
311 void GlobalAlias::setParent(Module *parent) {
312   Parent = parent;
313 }
314
315 void GlobalAlias::removeFromParent() {
316   getParent()->getAliasList().remove(getIterator());
317 }
318
319 void GlobalAlias::eraseFromParent() {
320   getParent()->getAliasList().erase(getIterator());
321 }
322
323 void GlobalAlias::setAliasee(Constant *Aliasee) {
324   assert((!Aliasee || Aliasee->getType() == getType()) &&
325          "Alias and aliasee types should match!");
326   setOperand(0, Aliasee);
327 }