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