Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / llvm / lib / IR / Globals.cpp
blob7bd4503a689e4ae89079a762c42996b214eee944
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/TargetParser/Triple.h"
25 using namespace llvm;
27 //===----------------------------------------------------------------------===//
28 // GlobalValue Class
29 //===----------------------------------------------------------------------===//
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");
38 // GlobalObject adds a comdat.
39 static_assert(sizeof(GlobalObject) == sizeof(GlobalValue) + sizeof(void *),
40 "unexpected GlobalObject size growth");
42 bool GlobalValue::isMaterializable() const {
43 if (const Function *F = dyn_cast<Function>(this))
44 return F->isMaterializable();
45 return false;
47 Error GlobalValue::materialize() { return getParent()->materialize(this); }
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()!");
55 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
56 llvm_unreachable("Unsupported class for handleOperandChange()!");
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();
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;
83 llvm_unreachable("not a global");
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;
95 llvm_unreachable("not a global");
98 GlobalObject::~GlobalObject() { setComdat(nullptr); }
100 bool GlobalValue::isInterposable() const {
101 if (isInterposableLinkage(getLinkage()))
102 return true;
103 return getParent() && getParent()->getSemanticInterposition() &&
104 !isDSOLocal();
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;
114 return hasDefaultVisibility() &&
115 GlobalObject::isExternalLinkage(getLinkage()) && !isDeclaration() &&
116 !isa<GlobalIFunc>(this) && !isDeduplicateComdat(getComdat());
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!");
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!");
138 void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
139 GlobalValue::copyAttributesFrom(Src);
140 setAlignment(Src->getAlign());
141 setSection(Src->getSection());
144 std::string GlobalValue::getGlobalIdentifier(StringRef Name,
145 GlobalValue::LinkageTypes Linkage,
146 StringRef FileName) {
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);
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() + ":");
165 return NewName;
168 std::string GlobalValue::getGlobalIdentifier() const {
169 return getGlobalIdentifier(getName(), getLinkage(),
170 getParent()->getSourceFileName());
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 "";
180 return cast<GlobalObject>(this)->getSection();
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;
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();
196 void GlobalObject::setComdat(Comdat *C) {
197 if (ObjComdat)
198 ObjComdat->removeUser(this);
199 ObjComdat = C;
200 if (C)
201 C->addUser(this);
204 StringRef GlobalValue::getPartition() const {
205 if (!hasPartition())
206 return "";
207 return getContext().pImpl->GlobalValuePartitions[this];
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;
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;
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();
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];
233 void GlobalValue::setSanitizerMetadata(SanitizerMetadata Meta) {
234 getContext().pImpl->GlobalValueSanitizerMetadata[this] = Meta;
235 HasSanitizerMetadata = true;
238 void GlobalValue::removeSanitizerMetadata() {
239 DenseMap<const GlobalValue *, SanitizerMetadata> &MetadataMap =
240 getContext().pImpl->GlobalValueSanitizerMetadata;
241 MetadataMap.erase(this);
242 HasSanitizerMetadata = false;
245 StringRef GlobalObject::getSectionImpl() const {
246 assert(hasSection());
247 return getContext().pImpl->GlobalObjectSections[this];
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;
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;
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());
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);
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;
278 // Functions are definitions if they have a body.
279 if (const Function *F = dyn_cast<Function>(this))
280 return F->empty() && !F->isMaterializable();
282 // Aliases and ifuncs are always definitions.
283 assert(isa<GlobalAlias>(this) || isa<GlobalIFunc>(this));
284 return false;
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;
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;
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.)
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.
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;
325 return true;
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;
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);
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;
350 case Instruction::Sub: {
351 if (findBaseObject(CE->getOperand(1), Aliases, Op))
352 return nullptr;
353 return findBaseObject(CE->getOperand(0), Aliases, Op);
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;
364 return nullptr;
367 const GlobalObject *GlobalValue::getAliaseeObject() const {
368 DenseSet<const GlobalAlias *> Aliases;
369 return findBaseObject(this, Aliases, [](const GlobalValue &) {});
372 bool GlobalValue::isAbsoluteSymbolRef() const {
373 auto *GO = dyn_cast<GlobalObject>(this);
374 if (!GO)
375 return false;
377 return GO->getMetadata(LLVMContext::MD_absolute_symbol);
380 std::optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
381 auto *GO = dyn_cast<GlobalObject>(this);
382 if (!GO)
383 return std::nullopt;
385 MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
386 if (!MD)
387 return std::nullopt;
389 return getConstantRangeFromMetadata(*MD);
392 bool GlobalValue::canBeOmittedFromSymbolTable() const {
393 if (!hasLinkOnceODRLinkage())
394 return false;
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;
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;
407 return hasAtLeastLocalUnnamedAddr();
410 //===----------------------------------------------------------------------===//
411 // GlobalVariable Implementation
412 //===----------------------------------------------------------------------===//
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;
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);
450 void GlobalVariable::removeFromParent() {
451 getParent()->removeGlobalVariable(this);
454 void GlobalVariable::eraseFromParent() {
455 getParent()->eraseGlobalVariable(this);
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);
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);
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());
487 void GlobalVariable::dropAllReferences() {
488 User::dropAllReferences();
489 clearMetadata();
492 //===----------------------------------------------------------------------===//
493 // GlobalAlias Implementation
494 //===----------------------------------------------------------------------===//
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);
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);
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);
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());
524 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
525 GlobalValue *Aliasee) {
526 return create(Aliasee->getValueType(), Aliasee->getAddressSpace(), Link, Name,
527 Aliasee);
530 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
531 return create(Aliasee->getLinkage(), Name, Aliasee);
534 void GlobalAlias::removeFromParent() { getParent()->removeAlias(this); }
536 void GlobalAlias::eraseFromParent() { getParent()->eraseAlias(this); }
538 void GlobalAlias::setAliasee(Constant *Aliasee) {
539 assert((!Aliasee || Aliasee->getType() == getType()) &&
540 "Alias and aliasee types should match!");
541 Op<0>().set(Aliasee);
544 const GlobalObject *GlobalAlias::getAliaseeObject() const {
545 DenseSet<const GlobalAlias *> Aliases;
546 return findBaseObject(getOperand(0), Aliases, [](const GlobalValue &) {});
549 //===----------------------------------------------------------------------===//
550 // GlobalIFunc Implementation
551 //===----------------------------------------------------------------------===//
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);
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);
569 void GlobalIFunc::removeFromParent() { getParent()->removeIFunc(this); }
571 void GlobalIFunc::eraseFromParent() { getParent()->eraseIFunc(this); }
573 const Function *GlobalIFunc::getResolverFunction() const {
574 return dyn_cast<Function>(getResolver()->stripPointerCastsAndAliases());
577 void GlobalIFunc::applyAlongResolverPath(
578 function_ref<void(const GlobalValue &)> Op) const {
579 DenseSet<const GlobalAlias *> Aliases;
580 findBaseObject(getResolver(), Aliases, Op);