]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/IR/Globals.cpp
Merge compiler-rt r291274.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/ConstantRange.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/GlobalAlias.h"
21 #include "llvm/IR/GlobalValue.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/Support/Error.h"
26 #include "llvm/Support/ErrorHandling.h"
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 //                            GlobalValue Class
31 //===----------------------------------------------------------------------===//
32
33 // GlobalValue should be a Constant, plus a type, a module, some flags, and an
34 // intrinsic ID. Add an assert to prevent people from accidentally growing
35 // GlobalValue while adding flags.
36 static_assert(sizeof(GlobalValue) ==
37                   sizeof(Constant) + 2 * sizeof(void *) + 2 * sizeof(unsigned),
38               "unexpected GlobalValue size growth");
39
40 bool GlobalValue::isMaterializable() const {
41   if (const Function *F = dyn_cast<Function>(this))
42     return F->isMaterializable();
43   return false;
44 }
45 Error GlobalValue::materialize() {
46   return getParent()->materialize(this);
47 }
48
49 /// Override destroyConstantImpl to make sure it doesn't get called on
50 /// GlobalValue's because they shouldn't be treated like other constants.
51 void GlobalValue::destroyConstantImpl() {
52   llvm_unreachable("You can't GV->destroyConstantImpl()!");
53 }
54
55 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
56   llvm_unreachable("Unsupported class for handleOperandChange()!");
57 }
58
59 /// copyAttributesFrom - copy all additional attributes (those not needed to
60 /// create a GlobalValue) from the GlobalValue Src to this one.
61 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
62   setVisibility(Src->getVisibility());
63   setUnnamedAddr(Src->getUnnamedAddr());
64   setDLLStorageClass(Src->getDLLStorageClass());
65 }
66
67 unsigned GlobalValue::getAlignment() const {
68   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
69     // In general we cannot compute this at the IR level, but we try.
70     if (const GlobalObject *GO = GA->getBaseObject())
71       return GO->getAlignment();
72
73     // FIXME: we should also be able to handle:
74     // Alias = Global + Offset
75     // Alias = Absolute
76     return 0;
77   }
78   return cast<GlobalObject>(this)->getAlignment();
79 }
80
81 void GlobalObject::setAlignment(unsigned Align) {
82   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
83   assert(Align <= MaximumAlignment &&
84          "Alignment is greater than MaximumAlignment!");
85   unsigned AlignmentData = Log2_32(Align) + 1;
86   unsigned OldData = getGlobalValueSubClassData();
87   setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
88   assert(getAlignment() == Align && "Alignment representation error!");
89 }
90
91 unsigned GlobalObject::getGlobalObjectSubClassData() const {
92   unsigned ValueData = getGlobalValueSubClassData();
93   return ValueData >> GlobalObjectBits;
94 }
95
96 void GlobalObject::setGlobalObjectSubClassData(unsigned Val) {
97   unsigned OldData = getGlobalValueSubClassData();
98   setGlobalValueSubClassData((OldData & GlobalObjectMask) |
99                              (Val << GlobalObjectBits));
100   assert(getGlobalObjectSubClassData() == Val && "representation error");
101 }
102
103 void GlobalObject::copyAttributesFrom(const GlobalValue *Src) {
104   GlobalValue::copyAttributesFrom(Src);
105   if (const auto *GV = dyn_cast<GlobalObject>(Src)) {
106     setAlignment(GV->getAlignment());
107     setSection(GV->getSection());
108   }
109 }
110
111 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
112                                              GlobalValue::LinkageTypes Linkage,
113                                              StringRef FileName) {
114
115   // Value names may be prefixed with a binary '1' to indicate
116   // that the backend should not modify the symbols due to any platform
117   // naming convention. Do not include that '1' in the PGO profile name.
118   if (Name[0] == '\1')
119     Name = Name.substr(1);
120
121   std::string NewName = Name;
122   if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
123     // For local symbols, prepend the main file name to distinguish them.
124     // Do not include the full path in the file name since there's no guarantee
125     // that it will stay the same, e.g., if the files are checked out from
126     // version control in different locations.
127     if (FileName.empty())
128       NewName = NewName.insert(0, "<unknown>:");
129     else
130       NewName = NewName.insert(0, FileName.str() + ":");
131   }
132   return NewName;
133 }
134
135 std::string GlobalValue::getGlobalIdentifier() const {
136   return getGlobalIdentifier(getName(), getLinkage(),
137                              getParent()->getSourceFileName());
138 }
139
140 StringRef GlobalValue::getSection() const {
141   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
142     // In general we cannot compute this at the IR level, but we try.
143     if (const GlobalObject *GO = GA->getBaseObject())
144       return GO->getSection();
145     return "";
146   }
147   return cast<GlobalObject>(this)->getSection();
148 }
149
150 Comdat *GlobalValue::getComdat() {
151   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
152     // In general we cannot compute this at the IR level, but we try.
153     if (const GlobalObject *GO = GA->getBaseObject())
154       return const_cast<GlobalObject *>(GO)->getComdat();
155     return nullptr;
156   }
157   // ifunc and its resolver are separate things so don't use resolver comdat.
158   if (isa<GlobalIFunc>(this))
159     return nullptr;
160   return cast<GlobalObject>(this)->getComdat();
161 }
162
163 void GlobalObject::setSection(StringRef S) {
164   Section = S;
165
166   // The C api requires this to be null terminated.
167   Section.c_str();
168 }
169
170 bool GlobalValue::isDeclaration() const {
171   // Globals are definitions if they have an initializer.
172   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
173     return GV->getNumOperands() == 0;
174
175   // Functions are definitions if they have a body.
176   if (const Function *F = dyn_cast<Function>(this))
177     return F->empty() && !F->isMaterializable();
178
179   // Aliases and ifuncs are always definitions.
180   assert(isa<GlobalIndirectSymbol>(this));
181   return false;
182 }
183
184 bool GlobalValue::canIncreaseAlignment() const {
185   // Firstly, can only increase the alignment of a global if it
186   // is a strong definition.
187   if (!isStrongDefinitionForLinker())
188     return false;
189
190   // It also has to either not have a section defined, or, not have
191   // alignment specified. (If it is assigned a section, the global
192   // could be densely packed with other objects in the section, and
193   // increasing the alignment could cause padding issues.)
194   if (hasSection() && getAlignment() > 0)
195     return false;
196
197   // On ELF platforms, we're further restricted in that we can't
198   // increase the alignment of any variable which might be emitted
199   // into a shared library, and which is exported. If the main
200   // executable accesses a variable found in a shared-lib, the main
201   // exe actually allocates memory for and exports the symbol ITSELF,
202   // overriding the symbol found in the library. That is, at link
203   // time, the observed alignment of the variable is copied into the
204   // executable binary. (A COPY relocation is also generated, to copy
205   // the initial data from the shadowed variable in the shared-lib
206   // into the location in the main binary, before running code.)
207   //
208   // And thus, even though you might think you are defining the
209   // global, and allocating the memory for the global in your object
210   // file, and thus should be able to set the alignment arbitrarily,
211   // that's not actually true. Doing so can cause an ABI breakage; an
212   // executable might have already been built with the previous
213   // alignment of the variable, and then assuming an increased
214   // alignment will be incorrect.
215
216   // Conservatively assume ELF if there's no parent pointer.
217   bool isELF =
218       (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
219   if (isELF && hasDefaultVisibility() && !hasLocalLinkage())
220     return false;
221
222   return true;
223 }
224
225 GlobalObject *GlobalValue::getBaseObject() {
226   if (auto *GO = dyn_cast<GlobalObject>(this))
227     return GO;
228   if (auto *GA = dyn_cast<GlobalAlias>(this))
229     return GA->getBaseObject();
230   return nullptr;
231 }
232
233 bool GlobalValue::isAbsoluteSymbolRef() const {
234   auto *GO = dyn_cast<GlobalObject>(this);
235   if (!GO)
236     return false;
237
238   return GO->getMetadata(LLVMContext::MD_absolute_symbol);
239 }
240
241 Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
242   auto *GO = dyn_cast<GlobalObject>(this);
243   if (!GO)
244     return None;
245
246   MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
247   if (!MD)
248     return None;
249
250   return getConstantRangeFromMetadata(*MD);
251 }
252
253 //===----------------------------------------------------------------------===//
254 // GlobalVariable Implementation
255 //===----------------------------------------------------------------------===//
256
257 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
258                                Constant *InitVal, const Twine &Name,
259                                ThreadLocalMode TLMode, unsigned AddressSpace,
260                                bool isExternallyInitialized)
261     : GlobalObject(Ty, Value::GlobalVariableVal,
262                    OperandTraits<GlobalVariable>::op_begin(this),
263                    InitVal != nullptr, Link, Name, AddressSpace),
264       isConstantGlobal(constant),
265       isExternallyInitializedConstant(isExternallyInitialized) {
266   setThreadLocalMode(TLMode);
267   if (InitVal) {
268     assert(InitVal->getType() == Ty &&
269            "Initializer should be the same type as the GlobalVariable!");
270     Op<0>() = InitVal;
271   }
272 }
273
274 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
275                                LinkageTypes Link, Constant *InitVal,
276                                const Twine &Name, GlobalVariable *Before,
277                                ThreadLocalMode TLMode, unsigned AddressSpace,
278                                bool isExternallyInitialized)
279     : GlobalObject(Ty, Value::GlobalVariableVal,
280                    OperandTraits<GlobalVariable>::op_begin(this),
281                    InitVal != nullptr, Link, Name, AddressSpace),
282       isConstantGlobal(constant),
283       isExternallyInitializedConstant(isExternallyInitialized) {
284   setThreadLocalMode(TLMode);
285   if (InitVal) {
286     assert(InitVal->getType() == Ty &&
287            "Initializer should be the same type as the GlobalVariable!");
288     Op<0>() = InitVal;
289   }
290
291   if (Before)
292     Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
293   else
294     M.getGlobalList().push_back(this);
295 }
296
297 void GlobalVariable::removeFromParent() {
298   getParent()->getGlobalList().remove(getIterator());
299 }
300
301 void GlobalVariable::eraseFromParent() {
302   getParent()->getGlobalList().erase(getIterator());
303 }
304
305 void GlobalVariable::setInitializer(Constant *InitVal) {
306   if (!InitVal) {
307     if (hasInitializer()) {
308       // Note, the num operands is used to compute the offset of the operand, so
309       // the order here matters.  Clearing the operand then clearing the num
310       // operands ensures we have the correct offset to the operand.
311       Op<0>().set(nullptr);
312       setGlobalVariableNumOperands(0);
313     }
314   } else {
315     assert(InitVal->getType() == getValueType() &&
316            "Initializer type must match GlobalVariable type");
317     // Note, the num operands is used to compute the offset of the operand, so
318     // the order here matters.  We need to set num operands to 1 first so that
319     // we get the correct offset to the first operand when we set it.
320     if (!hasInitializer())
321       setGlobalVariableNumOperands(1);
322     Op<0>().set(InitVal);
323   }
324 }
325
326 /// Copy all additional attributes (those not needed to create a GlobalVariable)
327 /// from the GlobalVariable Src to this one.
328 void GlobalVariable::copyAttributesFrom(const GlobalValue *Src) {
329   GlobalObject::copyAttributesFrom(Src);
330   if (const GlobalVariable *SrcVar = dyn_cast<GlobalVariable>(Src)) {
331     setThreadLocalMode(SrcVar->getThreadLocalMode());
332     setExternallyInitialized(SrcVar->isExternallyInitialized());
333   }
334 }
335
336 void GlobalVariable::dropAllReferences() {
337   User::dropAllReferences();
338   clearMetadata();
339 }
340
341 //===----------------------------------------------------------------------===//
342 // GlobalIndirectSymbol Implementation
343 //===----------------------------------------------------------------------===//
344
345 GlobalIndirectSymbol::GlobalIndirectSymbol(Type *Ty, ValueTy VTy,
346     unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name,
347     Constant *Symbol)
348     : GlobalValue(Ty, VTy, &Op<0>(), 1, Linkage, Name, AddressSpace) {
349     Op<0>() = Symbol;
350 }
351
352
353 //===----------------------------------------------------------------------===//
354 // GlobalAlias Implementation
355 //===----------------------------------------------------------------------===//
356
357 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
358                          const Twine &Name, Constant *Aliasee,
359                          Module *ParentModule)
360     : GlobalIndirectSymbol(Ty, Value::GlobalAliasVal, AddressSpace, Link, Name,
361                            Aliasee) {
362   if (ParentModule)
363     ParentModule->getAliasList().push_back(this);
364 }
365
366 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
367                                  LinkageTypes Link, const Twine &Name,
368                                  Constant *Aliasee, Module *ParentModule) {
369   return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
370 }
371
372 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
373                                  LinkageTypes Linkage, const Twine &Name,
374                                  Module *Parent) {
375   return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
376 }
377
378 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
379                                  LinkageTypes Linkage, const Twine &Name,
380                                  GlobalValue *Aliasee) {
381   return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
382 }
383
384 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
385                                  GlobalValue *Aliasee) {
386   PointerType *PTy = Aliasee->getType();
387   return create(PTy->getElementType(), PTy->getAddressSpace(), Link, Name,
388                 Aliasee);
389 }
390
391 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
392   return create(Aliasee->getLinkage(), Name, Aliasee);
393 }
394
395 void GlobalAlias::removeFromParent() {
396   getParent()->getAliasList().remove(getIterator());
397 }
398
399 void GlobalAlias::eraseFromParent() {
400   getParent()->getAliasList().erase(getIterator());
401 }
402
403 void GlobalAlias::setAliasee(Constant *Aliasee) {
404   assert((!Aliasee || Aliasee->getType() == getType()) &&
405          "Alias and aliasee types should match!");
406   setIndirectSymbol(Aliasee);
407 }
408
409 //===----------------------------------------------------------------------===//
410 // GlobalIFunc Implementation
411 //===----------------------------------------------------------------------===//
412
413 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
414                          const Twine &Name, Constant *Resolver,
415                          Module *ParentModule)
416     : GlobalIndirectSymbol(Ty, Value::GlobalIFuncVal, AddressSpace, Link, Name,
417                            Resolver) {
418   if (ParentModule)
419     ParentModule->getIFuncList().push_back(this);
420 }
421
422 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
423                                  LinkageTypes Link, const Twine &Name,
424                                  Constant *Resolver, Module *ParentModule) {
425   return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
426 }
427
428 void GlobalIFunc::removeFromParent() {
429   getParent()->getIFuncList().remove(getIterator());
430 }
431
432 void GlobalIFunc::eraseFromParent() {
433   getParent()->getIFuncList().erase(getIterator());
434 }