[clang][bytecode][NFC] Only get expr when checking for UB (#125397)
[llvm-project.git] / llvm / lib / IR / Globals.cpp
blobdb5e1cb57b1bab86ce630d50fc6e10d51f81ab13
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.
12 //===----------------------------------------------------------------------===//
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/Support/MD5.h"
25 #include "llvm/TargetParser/Triple.h"
26 using namespace llvm;
28 //===----------------------------------------------------------------------===//
29 // GlobalValue Class
30 //===----------------------------------------------------------------------===//
32 // GlobalValue should be a Constant, plus a type, a module, some flags, and an
33 // intrinsic ID. Add an assert to prevent people from accidentally growing
34 // GlobalValue while adding flags.
35 static_assert(sizeof(GlobalValue) ==
36 sizeof(Constant) + 2 * sizeof(void *) + 2 * sizeof(unsigned),
37 "unexpected GlobalValue size growth");
39 // GlobalObject adds a comdat.
40 static_assert(sizeof(GlobalObject) == sizeof(GlobalValue) + sizeof(void *),
41 "unexpected GlobalObject size growth");
43 bool GlobalValue::isMaterializable() const {
44 if (const Function *F = dyn_cast<Function>(this))
45 return F->isMaterializable();
46 return false;
48 Error GlobalValue::materialize() { return getParent()->materialize(this); }
50 /// Override destroyConstantImpl to make sure it doesn't get called on
51 /// GlobalValue's because they shouldn't be treated like other constants.
52 void GlobalValue::destroyConstantImpl() {
53 llvm_unreachable("You can't GV->destroyConstantImpl()!");
56 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
57 llvm_unreachable("Unsupported class for handleOperandChange()!");
60 /// copyAttributesFrom - copy all additional attributes (those not needed to
61 /// create a GlobalValue) from the GlobalValue Src to this one.
62 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
63 setVisibility(Src->getVisibility());
64 setUnnamedAddr(Src->getUnnamedAddr());
65 setThreadLocalMode(Src->getThreadLocalMode());
66 setDLLStorageClass(Src->getDLLStorageClass());
67 setDSOLocal(Src->isDSOLocal());
68 setPartition(Src->getPartition());
69 if (Src->hasSanitizerMetadata())
70 setSanitizerMetadata(Src->getSanitizerMetadata());
71 else
72 removeSanitizerMetadata();
75 GlobalValue::GUID GlobalValue::getGUID(StringRef GlobalName) {
76 return MD5Hash(GlobalName);
79 void GlobalValue::removeFromParent() {
80 switch (getValueID()) {
81 #define HANDLE_GLOBAL_VALUE(NAME) \
82 case Value::NAME##Val: \
83 return static_cast<NAME *>(this)->removeFromParent();
84 #include "llvm/IR/Value.def"
85 default:
86 break;
88 llvm_unreachable("not a global");
91 void GlobalValue::eraseFromParent() {
92 switch (getValueID()) {
93 #define HANDLE_GLOBAL_VALUE(NAME) \
94 case Value::NAME##Val: \
95 return static_cast<NAME *>(this)->eraseFromParent();
96 #include "llvm/IR/Value.def"
97 default:
98 break;
100 llvm_unreachable("not a global");
103 GlobalObject::~GlobalObject() { setComdat(nullptr); }
105 bool GlobalValue::isInterposable() const {
106 if (isInterposableLinkage(getLinkage()))
107 return true;
108 return getParent() && getParent()->getSemanticInterposition() &&
109 !isDSOLocal();
112 bool GlobalValue::canBenefitFromLocalAlias() const {
113 if (isTagged()) {
114 // Cannot create local aliases to MTE tagged globals. The address of a
115 // tagged global includes a tag that is assigned by the loader in the
116 // GOT.
117 return false;
119 // See AsmPrinter::getSymbolPreferLocal(). For a deduplicate comdat kind,
120 // references to a discarded local symbol from outside the group are not
121 // allowed, so avoid the local alias.
122 auto isDeduplicateComdat = [](const Comdat *C) {
123 return C && C->getSelectionKind() != Comdat::NoDeduplicate;
125 return hasDefaultVisibility() &&
126 GlobalObject::isExternalLinkage(getLinkage()) && !isDeclaration() &&
127 !isa<GlobalIFunc>(this) && !isDeduplicateComdat(getComdat());
130 const DataLayout &GlobalValue::getDataLayout() const {
131 return getParent()->getDataLayout();
134 void GlobalObject::setAlignment(MaybeAlign Align) {
135 assert((!Align || *Align <= MaximumAlignment) &&
136 "Alignment is greater than MaximumAlignment!");
137 unsigned AlignmentData = encode(Align);
138 unsigned OldData = getGlobalValueSubClassData();
139 setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
140 assert(getAlign() == Align && "Alignment representation error!");
143 void GlobalObject::setAlignment(Align Align) {
144 assert(Align <= MaximumAlignment &&
145 "Alignment is greater than MaximumAlignment!");
146 unsigned AlignmentData = encode(Align);
147 unsigned OldData = getGlobalValueSubClassData();
148 setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
149 assert(getAlign() && *getAlign() == Align &&
150 "Alignment representation error!");
153 void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
154 GlobalValue::copyAttributesFrom(Src);
155 setAlignment(Src->getAlign());
156 setSection(Src->getSection());
159 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
160 GlobalValue::LinkageTypes Linkage,
161 StringRef FileName) {
162 // Value names may be prefixed with a binary '1' to indicate
163 // that the backend should not modify the symbols due to any platform
164 // naming convention. Do not include that '1' in the PGO profile name.
165 Name.consume_front("\1");
167 std::string GlobalName;
168 if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
169 // For local symbols, prepend the main file name to distinguish them.
170 // Do not include the full path in the file name since there's no guarantee
171 // that it will stay the same, e.g., if the files are checked out from
172 // version control in different locations.
173 if (FileName.empty())
174 GlobalName += "<unknown>";
175 else
176 GlobalName += FileName;
178 GlobalName += GlobalIdentifierDelimiter;
180 GlobalName += Name;
181 return GlobalName;
184 std::string GlobalValue::getGlobalIdentifier() const {
185 return getGlobalIdentifier(getName(), getLinkage(),
186 getParent()->getSourceFileName());
189 StringRef GlobalValue::getSection() const {
190 if (auto *GA = dyn_cast<GlobalAlias>(this)) {
191 // In general we cannot compute this at the IR level, but we try.
192 if (const GlobalObject *GO = GA->getAliaseeObject())
193 return GO->getSection();
194 return "";
196 return cast<GlobalObject>(this)->getSection();
199 const Comdat *GlobalValue::getComdat() const {
200 if (auto *GA = dyn_cast<GlobalAlias>(this)) {
201 // In general we cannot compute this at the IR level, but we try.
202 if (const GlobalObject *GO = GA->getAliaseeObject())
203 return const_cast<GlobalObject *>(GO)->getComdat();
204 return nullptr;
206 // ifunc and its resolver are separate things so don't use resolver comdat.
207 if (isa<GlobalIFunc>(this))
208 return nullptr;
209 return cast<GlobalObject>(this)->getComdat();
212 void GlobalObject::setComdat(Comdat *C) {
213 if (ObjComdat)
214 ObjComdat->removeUser(this);
215 ObjComdat = C;
216 if (C)
217 C->addUser(this);
220 StringRef GlobalValue::getPartition() const {
221 if (!hasPartition())
222 return "";
223 return getContext().pImpl->GlobalValuePartitions[this];
226 void GlobalValue::setPartition(StringRef S) {
227 // Do nothing if we're clearing the partition and it is already empty.
228 if (!hasPartition() && S.empty())
229 return;
231 // Get or create a stable partition name string and put it in the table in the
232 // context.
233 if (!S.empty())
234 S = getContext().pImpl->Saver.save(S);
235 getContext().pImpl->GlobalValuePartitions[this] = S;
237 // Update the HasPartition field. Setting the partition to the empty string
238 // means this global no longer has a partition.
239 HasPartition = !S.empty();
242 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
243 const SanitizerMetadata &GlobalValue::getSanitizerMetadata() const {
244 assert(hasSanitizerMetadata());
245 assert(getContext().pImpl->GlobalValueSanitizerMetadata.count(this));
246 return getContext().pImpl->GlobalValueSanitizerMetadata[this];
249 void GlobalValue::setSanitizerMetadata(SanitizerMetadata Meta) {
250 getContext().pImpl->GlobalValueSanitizerMetadata[this] = Meta;
251 HasSanitizerMetadata = true;
254 void GlobalValue::removeSanitizerMetadata() {
255 DenseMap<const GlobalValue *, SanitizerMetadata> &MetadataMap =
256 getContext().pImpl->GlobalValueSanitizerMetadata;
257 MetadataMap.erase(this);
258 HasSanitizerMetadata = false;
261 void GlobalValue::setNoSanitizeMetadata() {
262 SanitizerMetadata Meta;
263 Meta.NoAddress = true;
264 Meta.NoHWAddress = true;
265 setSanitizerMetadata(Meta);
268 StringRef GlobalObject::getSectionImpl() const {
269 assert(hasSection());
270 return getContext().pImpl->GlobalObjectSections[this];
273 void GlobalObject::setSection(StringRef S) {
274 // Do nothing if we're clearing the section and it is already empty.
275 if (!hasSection() && S.empty())
276 return;
278 // Get or create a stable section name string and put it in the table in the
279 // context.
280 if (!S.empty())
281 S = getContext().pImpl->Saver.save(S);
282 getContext().pImpl->GlobalObjectSections[this] = S;
284 // Update the HasSectionHashEntryBit. Setting the section to the empty string
285 // means this global no longer has a section.
286 setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
289 bool GlobalValue::isNobuiltinFnDef() const {
290 const Function *F = dyn_cast<Function>(this);
291 if (!F || F->empty())
292 return false;
293 return F->hasFnAttribute(Attribute::NoBuiltin);
296 bool GlobalValue::isDeclaration() const {
297 // Globals are definitions if they have an initializer.
298 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
299 return GV->getNumOperands() == 0;
301 // Functions are definitions if they have a body.
302 if (const Function *F = dyn_cast<Function>(this))
303 return F->empty() && !F->isMaterializable();
305 // Aliases and ifuncs are always definitions.
306 assert(isa<GlobalAlias>(this) || isa<GlobalIFunc>(this));
307 return false;
310 bool GlobalObject::canIncreaseAlignment() const {
311 // Firstly, can only increase the alignment of a global if it
312 // is a strong definition.
313 if (!isStrongDefinitionForLinker())
314 return false;
316 // It also has to either not have a section defined, or, not have
317 // alignment specified. (If it is assigned a section, the global
318 // could be densely packed with other objects in the section, and
319 // increasing the alignment could cause padding issues.)
320 if (hasSection() && getAlign())
321 return false;
323 // On ELF platforms, we're further restricted in that we can't
324 // increase the alignment of any variable which might be emitted
325 // into a shared library, and which is exported. If the main
326 // executable accesses a variable found in a shared-lib, the main
327 // exe actually allocates memory for and exports the symbol ITSELF,
328 // overriding the symbol found in the library. That is, at link
329 // time, the observed alignment of the variable is copied into the
330 // executable binary. (A COPY relocation is also generated, to copy
331 // the initial data from the shadowed variable in the shared-lib
332 // into the location in the main binary, before running code.)
334 // And thus, even though you might think you are defining the
335 // global, and allocating the memory for the global in your object
336 // file, and thus should be able to set the alignment arbitrarily,
337 // that's not actually true. Doing so can cause an ABI breakage; an
338 // executable might have already been built with the previous
339 // alignment of the variable, and then assuming an increased
340 // alignment will be incorrect.
342 // Conservatively assume ELF if there's no parent pointer.
343 bool isELF =
344 (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
345 if (isELF && !isDSOLocal())
346 return false;
348 // GV with toc-data attribute is defined in a TOC entry. To mitigate TOC
349 // overflow, the alignment of such symbol should not be increased. Otherwise,
350 // padding is needed thus more TOC entries are wasted.
351 bool isXCOFF =
352 (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatXCOFF());
353 if (isXCOFF)
354 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
355 if (GV->hasAttribute("toc-data"))
356 return false;
358 return true;
361 template <typename Operation>
362 static const GlobalObject *
363 findBaseObject(const Constant *C, DenseSet<const GlobalAlias *> &Aliases,
364 const Operation &Op) {
365 if (auto *GO = dyn_cast<GlobalObject>(C)) {
366 Op(*GO);
367 return GO;
369 if (auto *GA = dyn_cast<GlobalAlias>(C)) {
370 Op(*GA);
371 if (Aliases.insert(GA).second)
372 return findBaseObject(GA->getOperand(0), Aliases, Op);
374 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
375 switch (CE->getOpcode()) {
376 case Instruction::Add: {
377 auto *LHS = findBaseObject(CE->getOperand(0), Aliases, Op);
378 auto *RHS = findBaseObject(CE->getOperand(1), Aliases, Op);
379 if (LHS && RHS)
380 return nullptr;
381 return LHS ? LHS : RHS;
383 case Instruction::Sub: {
384 if (findBaseObject(CE->getOperand(1), Aliases, Op))
385 return nullptr;
386 return findBaseObject(CE->getOperand(0), Aliases, Op);
388 case Instruction::IntToPtr:
389 case Instruction::PtrToInt:
390 case Instruction::BitCast:
391 case Instruction::GetElementPtr:
392 return findBaseObject(CE->getOperand(0), Aliases, Op);
393 default:
394 break;
397 return nullptr;
400 const GlobalObject *GlobalValue::getAliaseeObject() const {
401 DenseSet<const GlobalAlias *> Aliases;
402 return findBaseObject(this, Aliases, [](const GlobalValue &) {});
405 bool GlobalValue::isAbsoluteSymbolRef() const {
406 auto *GO = dyn_cast<GlobalObject>(this);
407 if (!GO)
408 return false;
410 return GO->getMetadata(LLVMContext::MD_absolute_symbol);
413 std::optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
414 auto *GO = dyn_cast<GlobalObject>(this);
415 if (!GO)
416 return std::nullopt;
418 MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
419 if (!MD)
420 return std::nullopt;
422 return getConstantRangeFromMetadata(*MD);
425 bool GlobalValue::canBeOmittedFromSymbolTable() const {
426 if (!hasLinkOnceODRLinkage())
427 return false;
429 // We assume that anyone who sets global unnamed_addr on a non-constant
430 // knows what they're doing.
431 if (hasGlobalUnnamedAddr())
432 return true;
434 // If it is a non constant variable, it needs to be uniqued across shared
435 // objects.
436 if (auto *Var = dyn_cast<GlobalVariable>(this))
437 if (!Var->isConstant())
438 return false;
440 return hasAtLeastLocalUnnamedAddr();
443 //===----------------------------------------------------------------------===//
444 // GlobalVariable Implementation
445 //===----------------------------------------------------------------------===//
447 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
448 Constant *InitVal, const Twine &Name,
449 ThreadLocalMode TLMode, unsigned AddressSpace,
450 bool isExternallyInitialized)
451 : GlobalObject(Ty, Value::GlobalVariableVal, AllocMarker, Link, Name,
452 AddressSpace),
453 isConstantGlobal(constant),
454 isExternallyInitializedConstant(isExternallyInitialized) {
455 assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
456 "invalid type for global variable");
457 setThreadLocalMode(TLMode);
458 if (InitVal) {
459 assert(InitVal->getType() == Ty &&
460 "Initializer should be the same type as the GlobalVariable!");
461 Op<0>() = InitVal;
462 } else {
463 setGlobalVariableNumOperands(0);
467 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
468 LinkageTypes Link, Constant *InitVal,
469 const Twine &Name, GlobalVariable *Before,
470 ThreadLocalMode TLMode,
471 std::optional<unsigned> AddressSpace,
472 bool isExternallyInitialized)
473 : GlobalVariable(Ty, constant, Link, InitVal, Name, TLMode,
474 AddressSpace
475 ? *AddressSpace
476 : M.getDataLayout().getDefaultGlobalsAddressSpace(),
477 isExternallyInitialized) {
478 if (Before)
479 Before->getParent()->insertGlobalVariable(Before->getIterator(), this);
480 else
481 M.insertGlobalVariable(this);
484 void GlobalVariable::removeFromParent() {
485 getParent()->removeGlobalVariable(this);
488 void GlobalVariable::eraseFromParent() {
489 getParent()->eraseGlobalVariable(this);
492 void GlobalVariable::setInitializer(Constant *InitVal) {
493 if (!InitVal) {
494 if (hasInitializer()) {
495 // Note, the num operands is used to compute the offset of the operand, so
496 // the order here matters. Clearing the operand then clearing the num
497 // operands ensures we have the correct offset to the operand.
498 Op<0>().set(nullptr);
499 setGlobalVariableNumOperands(0);
501 } else {
502 assert(InitVal->getType() == getValueType() &&
503 "Initializer type must match GlobalVariable type");
504 // Note, the num operands is used to compute the offset of the operand, so
505 // the order here matters. We need to set num operands to 1 first so that
506 // we get the correct offset to the first operand when we set it.
507 if (!hasInitializer())
508 setGlobalVariableNumOperands(1);
509 Op<0>().set(InitVal);
513 void GlobalVariable::replaceInitializer(Constant *InitVal) {
514 assert(InitVal && "Can't compute type of null initializer");
515 ValueType = InitVal->getType();
516 setInitializer(InitVal);
519 /// Copy all additional attributes (those not needed to create a GlobalVariable)
520 /// from the GlobalVariable Src to this one.
521 void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
522 GlobalObject::copyAttributesFrom(Src);
523 setExternallyInitialized(Src->isExternallyInitialized());
524 setAttributes(Src->getAttributes());
525 if (auto CM = Src->getCodeModel())
526 setCodeModel(*CM);
529 void GlobalVariable::dropAllReferences() {
530 User::dropAllReferences();
531 clearMetadata();
534 void GlobalVariable::setCodeModel(CodeModel::Model CM) {
535 unsigned CodeModelData = static_cast<unsigned>(CM) + 1;
536 unsigned OldData = getGlobalValueSubClassData();
537 unsigned NewData = (OldData & ~(CodeModelMask << CodeModelShift)) |
538 (CodeModelData << CodeModelShift);
539 setGlobalValueSubClassData(NewData);
540 assert(getCodeModel() == CM && "Code model representation error!");
543 //===----------------------------------------------------------------------===//
544 // GlobalAlias Implementation
545 //===----------------------------------------------------------------------===//
547 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
548 const Twine &Name, Constant *Aliasee,
549 Module *ParentModule)
550 : GlobalValue(Ty, Value::GlobalAliasVal, AllocMarker, Link, Name,
551 AddressSpace) {
552 setAliasee(Aliasee);
553 if (ParentModule)
554 ParentModule->insertAlias(this);
557 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
558 LinkageTypes Link, const Twine &Name,
559 Constant *Aliasee, Module *ParentModule) {
560 return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
563 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
564 LinkageTypes Linkage, const Twine &Name,
565 Module *Parent) {
566 return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
569 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
570 LinkageTypes Linkage, const Twine &Name,
571 GlobalValue *Aliasee) {
572 return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
575 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
576 GlobalValue *Aliasee) {
577 return create(Aliasee->getValueType(), Aliasee->getAddressSpace(), Link, Name,
578 Aliasee);
581 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
582 return create(Aliasee->getLinkage(), Name, Aliasee);
585 void GlobalAlias::removeFromParent() { getParent()->removeAlias(this); }
587 void GlobalAlias::eraseFromParent() { getParent()->eraseAlias(this); }
589 void GlobalAlias::setAliasee(Constant *Aliasee) {
590 assert((!Aliasee || Aliasee->getType() == getType()) &&
591 "Alias and aliasee types should match!");
592 Op<0>().set(Aliasee);
595 const GlobalObject *GlobalAlias::getAliaseeObject() const {
596 DenseSet<const GlobalAlias *> Aliases;
597 return findBaseObject(getOperand(0), Aliases, [](const GlobalValue &) {});
600 //===----------------------------------------------------------------------===//
601 // GlobalIFunc Implementation
602 //===----------------------------------------------------------------------===//
604 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
605 const Twine &Name, Constant *Resolver,
606 Module *ParentModule)
607 : GlobalObject(Ty, Value::GlobalIFuncVal, AllocMarker, Link, Name,
608 AddressSpace) {
609 setResolver(Resolver);
610 if (ParentModule)
611 ParentModule->insertIFunc(this);
614 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
615 LinkageTypes Link, const Twine &Name,
616 Constant *Resolver, Module *ParentModule) {
617 return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
620 void GlobalIFunc::removeFromParent() { getParent()->removeIFunc(this); }
622 void GlobalIFunc::eraseFromParent() { getParent()->eraseIFunc(this); }
624 const Function *GlobalIFunc::getResolverFunction() const {
625 return dyn_cast<Function>(getResolver()->stripPointerCastsAndAliases());
628 void GlobalIFunc::applyAlongResolverPath(
629 function_ref<void(const GlobalValue &)> Op) const {
630 DenseSet<const GlobalAlias *> Aliases;
631 findBaseObject(getResolver(), Aliases, Op);