1 //===-- Globals.cpp - Implement the GlobalValue & GlobalVariable 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 GlobalValue & GlobalVariable classes for the IR
13 //===----------------------------------------------------------------------===//
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"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
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");
40 bool GlobalValue::isMaterializable() const {
41 if (const Function *F = dyn_cast<Function>(this))
42 return F->isMaterializable();
45 Error GlobalValue::materialize() {
46 return getParent()->materialize(this);
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()!");
55 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
56 llvm_unreachable("Unsupported class for handleOperandChange()!");
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());
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();
73 // FIXME: we should also be able to handle:
74 // Alias = Global + Offset
78 return cast<GlobalObject>(this)->getAlignment();
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!");
91 unsigned GlobalObject::getGlobalObjectSubClassData() const {
92 unsigned ValueData = getGlobalValueSubClassData();
93 return ValueData >> GlobalObjectBits;
96 void GlobalObject::setGlobalObjectSubClassData(unsigned Val) {
97 unsigned OldData = getGlobalValueSubClassData();
98 setGlobalValueSubClassData((OldData & GlobalObjectMask) |
99 (Val << GlobalObjectBits));
100 assert(getGlobalObjectSubClassData() == Val && "representation error");
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());
111 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
112 GlobalValue::LinkageTypes Linkage,
113 StringRef FileName) {
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.
119 Name = Name.substr(1);
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>:");
130 NewName = NewName.insert(0, FileName.str() + ":");
135 std::string GlobalValue::getGlobalIdentifier() const {
136 return getGlobalIdentifier(getName(), getLinkage(),
137 getParent()->getSourceFileName());
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();
147 return cast<GlobalObject>(this)->getSection();
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();
157 // ifunc and its resolver are separate things so don't use resolver comdat.
158 if (isa<GlobalIFunc>(this))
160 return cast<GlobalObject>(this)->getComdat();
163 void GlobalObject::setSection(StringRef S) {
166 // The C api requires this to be null terminated.
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;
175 // Functions are definitions if they have a body.
176 if (const Function *F = dyn_cast<Function>(this))
177 return F->empty() && !F->isMaterializable();
179 // Aliases and ifuncs are always definitions.
180 assert(isa<GlobalIndirectSymbol>(this));
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())
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)
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.)
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.
216 // Conservatively assume ELF if there's no parent pointer.
218 (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
219 if (isELF && hasDefaultVisibility() && !hasLocalLinkage())
225 GlobalObject *GlobalValue::getBaseObject() {
226 if (auto *GO = dyn_cast<GlobalObject>(this))
228 if (auto *GA = dyn_cast<GlobalAlias>(this))
229 return GA->getBaseObject();
233 bool GlobalValue::isAbsoluteSymbolRef() const {
234 auto *GO = dyn_cast<GlobalObject>(this);
238 return GO->getMetadata(LLVMContext::MD_absolute_symbol);
241 Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
242 auto *GO = dyn_cast<GlobalObject>(this);
246 MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
250 return getConstantRangeFromMetadata(*MD);
253 //===----------------------------------------------------------------------===//
254 // GlobalVariable Implementation
255 //===----------------------------------------------------------------------===//
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);
268 assert(InitVal->getType() == Ty &&
269 "Initializer should be the same type as the GlobalVariable!");
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);
286 assert(InitVal->getType() == Ty &&
287 "Initializer should be the same type as the GlobalVariable!");
292 Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
294 M.getGlobalList().push_back(this);
297 void GlobalVariable::removeFromParent() {
298 getParent()->getGlobalList().remove(getIterator());
301 void GlobalVariable::eraseFromParent() {
302 getParent()->getGlobalList().erase(getIterator());
305 void GlobalVariable::setInitializer(Constant *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);
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);
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());
336 void GlobalVariable::dropAllReferences() {
337 User::dropAllReferences();
341 //===----------------------------------------------------------------------===//
342 // GlobalIndirectSymbol Implementation
343 //===----------------------------------------------------------------------===//
345 GlobalIndirectSymbol::GlobalIndirectSymbol(Type *Ty, ValueTy VTy,
346 unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name,
348 : GlobalValue(Ty, VTy, &Op<0>(), 1, Linkage, Name, AddressSpace) {
353 //===----------------------------------------------------------------------===//
354 // GlobalAlias Implementation
355 //===----------------------------------------------------------------------===//
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,
363 ParentModule->getAliasList().push_back(this);
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);
372 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
373 LinkageTypes Linkage, const Twine &Name,
375 return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
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());
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,
391 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
392 return create(Aliasee->getLinkage(), Name, Aliasee);
395 void GlobalAlias::removeFromParent() {
396 getParent()->getAliasList().remove(getIterator());
399 void GlobalAlias::eraseFromParent() {
400 getParent()->getAliasList().erase(getIterator());
403 void GlobalAlias::setAliasee(Constant *Aliasee) {
404 assert((!Aliasee || Aliasee->getType() == getType()) &&
405 "Alias and aliasee types should match!");
406 setIndirectSymbol(Aliasee);
409 //===----------------------------------------------------------------------===//
410 // GlobalIFunc Implementation
411 //===----------------------------------------------------------------------===//
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,
419 ParentModule->getIFuncList().push_back(this);
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);
428 void GlobalIFunc::removeFromParent() {
429 getParent()->getIFuncList().remove(getIterator());
432 void GlobalIFunc::eraseFromParent() {
433 getParent()->getIFuncList().erase(getIterator());