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