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