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