xref: /llvm-project-15.0.7/llvm/lib/IR/Globals.cpp (revision 5fedf7f4)
1 //===-- Globals.cpp - Implement the GlobalValue & GlobalVariable class ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the GlobalValue & GlobalVariable classes for the IR
10 // library.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "LLVMContextImpl.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/IR/ConstantRange.h"
18 #include "llvm/IR/Constants.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 // GlobalObject adds a comdat.
41 static_assert(sizeof(GlobalObject) == sizeof(GlobalValue) + sizeof(void *),
42               "unexpected GlobalObject size growth");
43 
44 bool GlobalValue::isMaterializable() const {
45   if (const Function *F = dyn_cast<Function>(this))
46     return F->isMaterializable();
47   return false;
48 }
49 Error GlobalValue::materialize() {
50   return getParent()->materialize(this);
51 }
52 
53 /// Override destroyConstantImpl to make sure it doesn't get called on
54 /// GlobalValue's because they shouldn't be treated like other constants.
55 void GlobalValue::destroyConstantImpl() {
56   llvm_unreachable("You can't GV->destroyConstantImpl()!");
57 }
58 
59 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
60   llvm_unreachable("Unsupported class for handleOperandChange()!");
61 }
62 
63 /// copyAttributesFrom - copy all additional attributes (those not needed to
64 /// create a GlobalValue) from the GlobalValue Src to this one.
65 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
66   setVisibility(Src->getVisibility());
67   setUnnamedAddr(Src->getUnnamedAddr());
68   setDLLStorageClass(Src->getDLLStorageClass());
69   setDSOLocal(Src->isDSOLocal());
70   setPartition(Src->getPartition());
71 }
72 
73 void GlobalValue::removeFromParent() {
74   switch (getValueID()) {
75 #define HANDLE_GLOBAL_VALUE(NAME)                                              \
76   case Value::NAME##Val:                                                       \
77     return static_cast<NAME *>(this)->removeFromParent();
78 #include "llvm/IR/Value.def"
79   default:
80     break;
81   }
82   llvm_unreachable("not a global");
83 }
84 
85 void GlobalValue::eraseFromParent() {
86   switch (getValueID()) {
87 #define HANDLE_GLOBAL_VALUE(NAME)                                              \
88   case Value::NAME##Val:                                                       \
89     return static_cast<NAME *>(this)->eraseFromParent();
90 #include "llvm/IR/Value.def"
91   default:
92     break;
93   }
94   llvm_unreachable("not a global");
95 }
96 
97 bool GlobalValue::isInterposable() const {
98   if (isInterposableLinkage(getLinkage()))
99     return true;
100   return getParent() && getParent()->getSemanticInterposition() &&
101          !isDSOLocal();
102 }
103 
104 unsigned GlobalValue::getAlignment() const {
105   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
106     // In general we cannot compute this at the IR level, but we try.
107     if (const GlobalObject *GO = GA->getBaseObject())
108       return GO->getAlignment();
109 
110     // FIXME: we should also be able to handle:
111     // Alias = Global + Offset
112     // Alias = Absolute
113     return 0;
114   }
115   return cast<GlobalObject>(this)->getAlignment();
116 }
117 
118 unsigned GlobalValue::getAddressSpace() const {
119   PointerType *PtrTy = getType();
120   return PtrTy->getAddressSpace();
121 }
122 
123 void GlobalObject::setAlignment(MaybeAlign Align) {
124   assert((!Align || Align <= MaximumAlignment) &&
125          "Alignment is greater than MaximumAlignment!");
126   unsigned AlignmentData = encode(Align);
127   unsigned OldData = getGlobalValueSubClassData();
128   setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
129   assert(MaybeAlign(getAlignment()) == Align &&
130          "Alignment representation error!");
131 }
132 
133 void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
134   GlobalValue::copyAttributesFrom(Src);
135   setAlignment(MaybeAlign(Src->getAlignment()));
136   setSection(Src->getSection());
137 }
138 
139 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
140                                              GlobalValue::LinkageTypes Linkage,
141                                              StringRef FileName) {
142 
143   // Value names may be prefixed with a binary '1' to indicate
144   // that the backend should not modify the symbols due to any platform
145   // naming convention. Do not include that '1' in the PGO profile name.
146   if (Name[0] == '\1')
147     Name = Name.substr(1);
148 
149   std::string NewName = std::string(Name);
150   if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
151     // For local symbols, prepend the main file name to distinguish them.
152     // Do not include the full path in the file name since there's no guarantee
153     // that it will stay the same, e.g., if the files are checked out from
154     // version control in different locations.
155     if (FileName.empty())
156       NewName = NewName.insert(0, "<unknown>:");
157     else
158       NewName = NewName.insert(0, FileName.str() + ":");
159   }
160   return NewName;
161 }
162 
163 std::string GlobalValue::getGlobalIdentifier() const {
164   return getGlobalIdentifier(getName(), getLinkage(),
165                              getParent()->getSourceFileName());
166 }
167 
168 StringRef GlobalValue::getSection() const {
169   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
170     // In general we cannot compute this at the IR level, but we try.
171     if (const GlobalObject *GO = GA->getBaseObject())
172       return GO->getSection();
173     return "";
174   }
175   return cast<GlobalObject>(this)->getSection();
176 }
177 
178 const Comdat *GlobalValue::getComdat() const {
179   if (auto *GA = dyn_cast<GlobalAlias>(this)) {
180     // In general we cannot compute this at the IR level, but we try.
181     if (const GlobalObject *GO = GA->getBaseObject())
182       return const_cast<GlobalObject *>(GO)->getComdat();
183     return nullptr;
184   }
185   // ifunc and its resolver are separate things so don't use resolver comdat.
186   if (isa<GlobalIFunc>(this))
187     return nullptr;
188   return cast<GlobalObject>(this)->getComdat();
189 }
190 
191 StringRef GlobalValue::getPartition() const {
192   if (!hasPartition())
193     return "";
194   return getContext().pImpl->GlobalValuePartitions[this];
195 }
196 
197 void GlobalValue::setPartition(StringRef S) {
198   // Do nothing if we're clearing the partition and it is already empty.
199   if (!hasPartition() && S.empty())
200     return;
201 
202   // Get or create a stable partition name string and put it in the table in the
203   // context.
204   if (!S.empty())
205     S = getContext().pImpl->Saver.save(S);
206   getContext().pImpl->GlobalValuePartitions[this] = S;
207 
208   // Update the HasPartition field. Setting the partition to the empty string
209   // means this global no longer has a partition.
210   HasPartition = !S.empty();
211 }
212 
213 StringRef GlobalObject::getSectionImpl() const {
214   assert(hasSection());
215   return getContext().pImpl->GlobalObjectSections[this];
216 }
217 
218 void GlobalObject::setSection(StringRef S) {
219   // Do nothing if we're clearing the section and it is already empty.
220   if (!hasSection() && S.empty())
221     return;
222 
223   // Get or create a stable section name string and put it in the table in the
224   // context.
225   if (!S.empty())
226     S = getContext().pImpl->Saver.save(S);
227   getContext().pImpl->GlobalObjectSections[this] = S;
228 
229   // Update the HasSectionHashEntryBit. Setting the section to the empty string
230   // means this global no longer has a section.
231   setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
232 }
233 
234 bool GlobalValue::isDeclaration() const {
235   // Globals are definitions if they have an initializer.
236   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
237     return GV->getNumOperands() == 0;
238 
239   // Functions are definitions if they have a body.
240   if (const Function *F = dyn_cast<Function>(this))
241     return F->empty() && !F->isMaterializable();
242 
243   // Aliases and ifuncs are always definitions.
244   assert(isa<GlobalIndirectSymbol>(this));
245   return false;
246 }
247 
248 bool GlobalValue::canIncreaseAlignment() const {
249   // Firstly, can only increase the alignment of a global if it
250   // is a strong definition.
251   if (!isStrongDefinitionForLinker())
252     return false;
253 
254   // It also has to either not have a section defined, or, not have
255   // alignment specified. (If it is assigned a section, the global
256   // could be densely packed with other objects in the section, and
257   // increasing the alignment could cause padding issues.)
258   if (hasSection() && getAlignment() > 0)
259     return false;
260 
261   // On ELF platforms, we're further restricted in that we can't
262   // increase the alignment of any variable which might be emitted
263   // into a shared library, and which is exported. If the main
264   // executable accesses a variable found in a shared-lib, the main
265   // exe actually allocates memory for and exports the symbol ITSELF,
266   // overriding the symbol found in the library. That is, at link
267   // time, the observed alignment of the variable is copied into the
268   // executable binary. (A COPY relocation is also generated, to copy
269   // the initial data from the shadowed variable in the shared-lib
270   // into the location in the main binary, before running code.)
271   //
272   // And thus, even though you might think you are defining the
273   // global, and allocating the memory for the global in your object
274   // file, and thus should be able to set the alignment arbitrarily,
275   // that's not actually true. Doing so can cause an ABI breakage; an
276   // executable might have already been built with the previous
277   // alignment of the variable, and then assuming an increased
278   // alignment will be incorrect.
279 
280   // Conservatively assume ELF if there's no parent pointer.
281   bool isELF =
282       (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
283   if (isELF && !isDSOLocal())
284     return false;
285 
286   return true;
287 }
288 
289 const GlobalObject *GlobalValue::getBaseObject() const {
290   if (auto *GO = dyn_cast<GlobalObject>(this))
291     return GO;
292   if (auto *GA = dyn_cast<GlobalIndirectSymbol>(this))
293     return GA->getBaseObject();
294   return nullptr;
295 }
296 
297 bool GlobalValue::isAbsoluteSymbolRef() const {
298   auto *GO = dyn_cast<GlobalObject>(this);
299   if (!GO)
300     return false;
301 
302   return GO->getMetadata(LLVMContext::MD_absolute_symbol);
303 }
304 
305 Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
306   auto *GO = dyn_cast<GlobalObject>(this);
307   if (!GO)
308     return None;
309 
310   MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
311   if (!MD)
312     return None;
313 
314   return getConstantRangeFromMetadata(*MD);
315 }
316 
317 bool GlobalValue::canBeOmittedFromSymbolTable() const {
318   if (!hasLinkOnceODRLinkage())
319     return false;
320 
321   // We assume that anyone who sets global unnamed_addr on a non-constant
322   // knows what they're doing.
323   if (hasGlobalUnnamedAddr())
324     return true;
325 
326   // If it is a non constant variable, it needs to be uniqued across shared
327   // objects.
328   if (auto *Var = dyn_cast<GlobalVariable>(this))
329     if (!Var->isConstant())
330       return false;
331 
332   return hasAtLeastLocalUnnamedAddr();
333 }
334 
335 //===----------------------------------------------------------------------===//
336 // GlobalVariable Implementation
337 //===----------------------------------------------------------------------===//
338 
339 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
340                                Constant *InitVal, const Twine &Name,
341                                ThreadLocalMode TLMode, unsigned AddressSpace,
342                                bool isExternallyInitialized)
343     : GlobalObject(Ty, Value::GlobalVariableVal,
344                    OperandTraits<GlobalVariable>::op_begin(this),
345                    InitVal != nullptr, Link, Name, AddressSpace),
346       isConstantGlobal(constant),
347       isExternallyInitializedConstant(isExternallyInitialized) {
348   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
349          "invalid type for global variable");
350   setThreadLocalMode(TLMode);
351   if (InitVal) {
352     assert(InitVal->getType() == Ty &&
353            "Initializer should be the same type as the GlobalVariable!");
354     Op<0>() = InitVal;
355   }
356 }
357 
358 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
359                                LinkageTypes Link, Constant *InitVal,
360                                const Twine &Name, GlobalVariable *Before,
361                                ThreadLocalMode TLMode, unsigned AddressSpace,
362                                bool isExternallyInitialized)
363     : GlobalObject(Ty, Value::GlobalVariableVal,
364                    OperandTraits<GlobalVariable>::op_begin(this),
365                    InitVal != nullptr, Link, Name, AddressSpace),
366       isConstantGlobal(constant),
367       isExternallyInitializedConstant(isExternallyInitialized) {
368   assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
369          "invalid type for global variable");
370   setThreadLocalMode(TLMode);
371   if (InitVal) {
372     assert(InitVal->getType() == Ty &&
373            "Initializer should be the same type as the GlobalVariable!");
374     Op<0>() = InitVal;
375   }
376 
377   if (Before)
378     Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
379   else
380     M.getGlobalList().push_back(this);
381 }
382 
383 void GlobalVariable::removeFromParent() {
384   getParent()->getGlobalList().remove(getIterator());
385 }
386 
387 void GlobalVariable::eraseFromParent() {
388   getParent()->getGlobalList().erase(getIterator());
389 }
390 
391 void GlobalVariable::setInitializer(Constant *InitVal) {
392   if (!InitVal) {
393     if (hasInitializer()) {
394       // Note, the num operands is used to compute the offset of the operand, so
395       // the order here matters.  Clearing the operand then clearing the num
396       // operands ensures we have the correct offset to the operand.
397       Op<0>().set(nullptr);
398       setGlobalVariableNumOperands(0);
399     }
400   } else {
401     assert(InitVal->getType() == getValueType() &&
402            "Initializer type must match GlobalVariable type");
403     // Note, the num operands is used to compute the offset of the operand, so
404     // the order here matters.  We need to set num operands to 1 first so that
405     // we get the correct offset to the first operand when we set it.
406     if (!hasInitializer())
407       setGlobalVariableNumOperands(1);
408     Op<0>().set(InitVal);
409   }
410 }
411 
412 /// Copy all additional attributes (those not needed to create a GlobalVariable)
413 /// from the GlobalVariable Src to this one.
414 void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
415   GlobalObject::copyAttributesFrom(Src);
416   setThreadLocalMode(Src->getThreadLocalMode());
417   setExternallyInitialized(Src->isExternallyInitialized());
418   setAttributes(Src->getAttributes());
419 }
420 
421 void GlobalVariable::dropAllReferences() {
422   User::dropAllReferences();
423   clearMetadata();
424 }
425 
426 //===----------------------------------------------------------------------===//
427 // GlobalIndirectSymbol Implementation
428 //===----------------------------------------------------------------------===//
429 
430 GlobalIndirectSymbol::GlobalIndirectSymbol(Type *Ty, ValueTy VTy,
431     unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name,
432     Constant *Symbol)
433     : GlobalValue(Ty, VTy, &Op<0>(), 1, Linkage, Name, AddressSpace) {
434     Op<0>() = Symbol;
435 }
436 
437 static const GlobalObject *
438 findBaseObject(const Constant *C, DenseSet<const GlobalAlias *> &Aliases) {
439   if (auto *GO = dyn_cast<GlobalObject>(C))
440     return GO;
441   if (auto *GA = dyn_cast<GlobalAlias>(C))
442     if (Aliases.insert(GA).second)
443       return findBaseObject(GA->getOperand(0), Aliases);
444   if (auto *CE = dyn_cast<ConstantExpr>(C)) {
445     switch (CE->getOpcode()) {
446     case Instruction::Add: {
447       auto *LHS = findBaseObject(CE->getOperand(0), Aliases);
448       auto *RHS = findBaseObject(CE->getOperand(1), Aliases);
449       if (LHS && RHS)
450         return nullptr;
451       return LHS ? LHS : RHS;
452     }
453     case Instruction::Sub: {
454       if (findBaseObject(CE->getOperand(1), Aliases))
455         return nullptr;
456       return findBaseObject(CE->getOperand(0), Aliases);
457     }
458     case Instruction::IntToPtr:
459     case Instruction::PtrToInt:
460     case Instruction::BitCast:
461     case Instruction::GetElementPtr:
462       return findBaseObject(CE->getOperand(0), Aliases);
463     default:
464       break;
465     }
466   }
467   return nullptr;
468 }
469 
470 const GlobalObject *GlobalIndirectSymbol::getBaseObject() const {
471   DenseSet<const GlobalAlias *> Aliases;
472   return findBaseObject(getOperand(0), Aliases);
473 }
474 
475 //===----------------------------------------------------------------------===//
476 // GlobalAlias Implementation
477 //===----------------------------------------------------------------------===//
478 
479 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
480                          const Twine &Name, Constant *Aliasee,
481                          Module *ParentModule)
482     : GlobalIndirectSymbol(Ty, Value::GlobalAliasVal, AddressSpace, Link, Name,
483                            Aliasee) {
484   if (ParentModule)
485     ParentModule->getAliasList().push_back(this);
486 }
487 
488 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
489                                  LinkageTypes Link, const Twine &Name,
490                                  Constant *Aliasee, Module *ParentModule) {
491   return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
492 }
493 
494 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
495                                  LinkageTypes Linkage, const Twine &Name,
496                                  Module *Parent) {
497   return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
498 }
499 
500 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
501                                  LinkageTypes Linkage, const Twine &Name,
502                                  GlobalValue *Aliasee) {
503   return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
504 }
505 
506 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
507                                  GlobalValue *Aliasee) {
508   PointerType *PTy = Aliasee->getType();
509   return create(PTy->getElementType(), PTy->getAddressSpace(), Link, Name,
510                 Aliasee);
511 }
512 
513 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
514   return create(Aliasee->getLinkage(), Name, Aliasee);
515 }
516 
517 void GlobalAlias::removeFromParent() {
518   getParent()->getAliasList().remove(getIterator());
519 }
520 
521 void GlobalAlias::eraseFromParent() {
522   getParent()->getAliasList().erase(getIterator());
523 }
524 
525 void GlobalAlias::setAliasee(Constant *Aliasee) {
526   assert((!Aliasee || Aliasee->getType() == getType()) &&
527          "Alias and aliasee types should match!");
528   setIndirectSymbol(Aliasee);
529 }
530 
531 //===----------------------------------------------------------------------===//
532 // GlobalIFunc Implementation
533 //===----------------------------------------------------------------------===//
534 
535 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
536                          const Twine &Name, Constant *Resolver,
537                          Module *ParentModule)
538     : GlobalIndirectSymbol(Ty, Value::GlobalIFuncVal, AddressSpace, Link, Name,
539                            Resolver) {
540   if (ParentModule)
541     ParentModule->getIFuncList().push_back(this);
542 }
543 
544 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
545                                  LinkageTypes Link, const Twine &Name,
546                                  Constant *Resolver, Module *ParentModule) {
547   return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
548 }
549 
550 void GlobalIFunc::removeFromParent() {
551   getParent()->getIFuncList().remove(getIterator());
552 }
553 
554 void GlobalIFunc::eraseFromParent() {
555   getParent()->getIFuncList().erase(getIterator());
556 }
557