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/DataLayout.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/MDBuilder.h"
23#include "llvm/IR/Module.h"
24#include "llvm/Support/Error.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/MD5.h"
27#include "llvm/TargetParser/Triple.h"
28using namespace llvm;
29
30//===----------------------------------------------------------------------===//
31// GlobalValue Class
32//===----------------------------------------------------------------------===//
33
34// GlobalValue should be a Constant, plus a type, a module, some flags, and an
35// intrinsic ID. Add an assert to prevent people from accidentally growing
36// GlobalValue while adding flags.
37static_assert(sizeof(GlobalValue) ==
38 sizeof(Constant) + 2 * sizeof(void *) + 2 * sizeof(unsigned),
39 "unexpected GlobalValue size growth");
40
41// GlobalObject adds a comdat.
42static_assert(sizeof(GlobalObject) == sizeof(GlobalValue) + sizeof(void *),
43 "unexpected GlobalObject size growth");
44
45bool GlobalValue::isMaterializable() const {
46 if (const Function *F = dyn_cast<Function>(Val: this))
47 return F->isMaterializable();
48 return false;
49}
50Error GlobalValue::materialize() { return getParent()->materialize(GV: this); }
51
52/// Override destroyConstantImpl to make sure it doesn't get called on
53/// GlobalValue's because they shouldn't be treated like other constants.
54void GlobalValue::destroyConstantImpl() {
55 llvm_unreachable("You can't GV->destroyConstantImpl()!");
56}
57
58Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
59 llvm_unreachable("Unsupported class for handleOperandChange()!");
60}
61
62/// copyAttributesFrom - copy all additional attributes (those not needed to
63/// create a GlobalValue) from the GlobalValue Src to this one.
64void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
65 setVisibility(Src->getVisibility());
66 setUnnamedAddr(Src->getUnnamedAddr());
67 setThreadLocalMode(Src->getThreadLocalMode());
68 setDLLStorageClass(Src->getDLLStorageClass());
69 setDSOLocal(Src->isDSOLocal());
70 setPartition(Src->getPartition());
71 if (Src->hasSanitizerMetadata())
72 setSanitizerMetadata(Src->getSanitizerMetadata());
73 else
74 removeSanitizerMetadata();
75}
76
77GlobalValue::GUID
78GlobalValue::getGUIDAssumingExternalLinkage(StringRef GlobalIdentifier) {
79 return MD5Hash(Str: GlobalIdentifier);
80}
81
82void GlobalValue::removeFromParent() {
83 switch (getValueID()) {
84#define HANDLE_GLOBAL_VALUE(NAME) \
85 case Value::NAME##Val: \
86 return static_cast<NAME *>(this)->removeFromParent();
87#include "llvm/IR/Value.def"
88 default:
89 break;
90 }
91 llvm_unreachable("not a global");
92}
93
94void GlobalValue::eraseFromParent() {
95 switch (getValueID()) {
96#define HANDLE_GLOBAL_VALUE(NAME) \
97 case Value::NAME##Val: \
98 return static_cast<NAME *>(this)->eraseFromParent();
99#include "llvm/IR/Value.def"
100 default:
101 break;
102 }
103 llvm_unreachable("not a global");
104}
105
106GlobalObject::~GlobalObject() { setComdat(nullptr); }
107
108bool GlobalValue::isInterposable() const {
109 if (isInterposableLinkage(Linkage: getLinkage()))
110 return true;
111 return getParent() && getParent()->getSemanticInterposition() &&
112 !isDSOLocal();
113}
114
115bool GlobalValue::canBenefitFromLocalAlias() const {
116 if (isTagged()) {
117 // Cannot create local aliases to MTE tagged globals. The address of a
118 // tagged global includes a tag that is assigned by the loader in the
119 // GOT.
120 return false;
121 }
122 // See AsmPrinter::getSymbolPreferLocal(). For a deduplicate comdat kind,
123 // references to a discarded local symbol from outside the group are not
124 // allowed, so avoid the local alias.
125 auto isDeduplicateComdat = [](const Comdat *C) {
126 return C && C->getSelectionKind() != Comdat::NoDeduplicate;
127 };
128 return hasDefaultVisibility() &&
129 GlobalObject::isExternalLinkage(Linkage: getLinkage()) && !isDeclaration() &&
130 !isa<GlobalIFunc>(Val: this) && !isDeduplicateComdat(getComdat());
131}
132
133const DataLayout &GlobalValue::getDataLayout() const {
134 return getParent()->getDataLayout();
135}
136
137void GlobalObject::setAlignment(MaybeAlign Align) {
138 assert((!Align || *Align <= MaximumAlignment) &&
139 "Alignment is greater than MaximumAlignment!");
140 unsigned AlignmentData = encode(A: Align);
141 unsigned OldData = getGlobalValueSubClassData();
142 setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
143 assert(getAlign() == Align && "Alignment representation error!");
144}
145
146void GlobalObject::setAlignment(Align Align) {
147 assert(Align <= MaximumAlignment &&
148 "Alignment is greater than MaximumAlignment!");
149 unsigned AlignmentData = encode(A: Align);
150 unsigned OldData = getGlobalValueSubClassData();
151 setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
152 assert(getAlign() && *getAlign() == Align &&
153 "Alignment representation error!");
154}
155
156void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
157 GlobalValue::copyAttributesFrom(Src);
158 setAlignment(Src->getAlign());
159 setSection(Src->getSection());
160}
161
162std::string GlobalValue::getGlobalIdentifier(StringRef Name,
163 GlobalValue::LinkageTypes Linkage,
164 StringRef FileName) {
165 // Value names may be prefixed with a binary '1' to indicate
166 // that the backend should not modify the symbols due to any platform
167 // naming convention. Do not include that '1' in the PGO profile name.
168 Name.consume_front(Prefix: "\1");
169
170 std::string GlobalName;
171 if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
172 // For local symbols, prepend the main file name to distinguish them.
173 // Do not include the full path in the file name since there's no guarantee
174 // that it will stay the same, e.g., if the files are checked out from
175 // version control in different locations.
176 if (FileName.empty())
177 GlobalName += "<unknown>";
178 else
179 GlobalName += FileName;
180
181 GlobalName += GlobalIdentifierDelimiter;
182 }
183 GlobalName += Name;
184 return GlobalName;
185}
186
187std::string GlobalValue::getGlobalIdentifier() const {
188 return getGlobalIdentifier(Name: getName(), Linkage: getLinkage(),
189 FileName: getParent()->getSourceFileName());
190}
191
192StringRef GlobalValue::getSection() const {
193 if (auto *GA = dyn_cast<GlobalAlias>(Val: this)) {
194 // In general we cannot compute this at the IR level, but we try.
195 if (const GlobalObject *GO = GA->getAliaseeObject())
196 return GO->getSection();
197 return "";
198 }
199 return cast<GlobalObject>(Val: this)->getSection();
200}
201
202const Comdat *GlobalValue::getComdat() const {
203 if (auto *GA = dyn_cast<GlobalAlias>(Val: this)) {
204 // In general we cannot compute this at the IR level, but we try.
205 if (const GlobalObject *GO = GA->getAliaseeObject())
206 return const_cast<GlobalObject *>(GO)->getComdat();
207 return nullptr;
208 }
209 // ifunc and its resolver are separate things so don't use resolver comdat.
210 if (isa<GlobalIFunc>(Val: this))
211 return nullptr;
212 return cast<GlobalObject>(Val: this)->getComdat();
213}
214
215void GlobalObject::setComdat(Comdat *C) {
216 if (ObjComdat)
217 ObjComdat->removeUser(GO: this);
218 ObjComdat = C;
219 if (C)
220 C->addUser(GO: this);
221}
222
223StringRef GlobalValue::getPartition() const {
224 if (!hasPartition())
225 return "";
226 return getContext().pImpl->GlobalValuePartitions[this];
227}
228
229void GlobalValue::setPartition(StringRef S) {
230 // Do nothing if we're clearing the partition and it is already empty.
231 if (!hasPartition() && S.empty())
232 return;
233
234 // Get or create a stable partition name string and put it in the table in the
235 // context.
236 if (!S.empty())
237 S = getContext().pImpl->Saver.save(S);
238 getContext().pImpl->GlobalValuePartitions[this] = S;
239
240 // Update the HasPartition field. Setting the partition to the empty string
241 // means this global no longer has a partition.
242 HasPartition = !S.empty();
243}
244
245using SanitizerMetadata = GlobalValue::SanitizerMetadata;
246const SanitizerMetadata &GlobalValue::getSanitizerMetadata() const {
247 assert(hasSanitizerMetadata());
248 assert(getContext().pImpl->GlobalValueSanitizerMetadata.count(this));
249 return getContext().pImpl->GlobalValueSanitizerMetadata[this];
250}
251
252void GlobalValue::setSanitizerMetadata(SanitizerMetadata Meta) {
253 getContext().pImpl->GlobalValueSanitizerMetadata[this] = Meta;
254 HasSanitizerMetadata = true;
255}
256
257void GlobalValue::removeSanitizerMetadata() {
258 DenseMap<const GlobalValue *, SanitizerMetadata> &MetadataMap =
259 getContext().pImpl->GlobalValueSanitizerMetadata;
260 MetadataMap.erase(Val: this);
261 HasSanitizerMetadata = false;
262}
263
264void GlobalValue::setNoSanitizeMetadata() {
265 SanitizerMetadata Meta;
266 Meta.NoAddress = true;
267 Meta.NoHWAddress = true;
268 setSanitizerMetadata(Meta);
269}
270
271StringRef GlobalObject::getSectionImpl() const {
272 assert(hasSection());
273 return getContext().pImpl->GlobalObjectSections[this];
274}
275
276void GlobalObject::setSection(StringRef S) {
277 // Do nothing if we're clearing the section and it is already empty.
278 if (!hasSection() && S.empty())
279 return;
280
281 // Get or create a stable section name string and put it in the table in the
282 // context.
283 if (!S.empty())
284 S = getContext().pImpl->Saver.save(S);
285 getContext().pImpl->GlobalObjectSections[this] = S;
286
287 // Update the HasSectionHashEntryBit. Setting the section to the empty string
288 // means this global no longer has a section.
289 setGlobalObjectFlag(Bit: HasSectionHashEntryBit, Val: !S.empty());
290}
291
292bool GlobalObject::setSectionPrefix(StringRef Prefix) {
293 StringRef ExistingPrefix;
294 if (std::optional<StringRef> MaybePrefix = getSectionPrefix())
295 ExistingPrefix = *MaybePrefix;
296
297 if (ExistingPrefix == Prefix)
298 return false;
299
300 if (Prefix.empty()) {
301 setMetadata(KindID: LLVMContext::MD_section_prefix, Node: nullptr);
302 return true;
303 }
304 MDBuilder MDB(getContext());
305 setMetadata(KindID: LLVMContext::MD_section_prefix,
306 Node: MDB.createGlobalObjectSectionPrefix(Prefix));
307 return true;
308}
309
310std::optional<StringRef> GlobalObject::getSectionPrefix() const {
311 if (MDNode *MD = getMetadata(KindID: LLVMContext::MD_section_prefix)) {
312 [[maybe_unused]] StringRef MDName =
313 cast<MDString>(Val: MD->getOperand(I: 0))->getString();
314 assert((MDName == "section_prefix" ||
315 (isa<Function>(this) && MDName == "function_section_prefix")) &&
316 "Metadata not match");
317 return cast<MDString>(Val: MD->getOperand(I: 1))->getString();
318 }
319 return std::nullopt;
320}
321
322bool GlobalValue::isNobuiltinFnDef() const {
323 const Function *F = dyn_cast<Function>(Val: this);
324 if (!F || F->empty())
325 return false;
326 return F->hasFnAttribute(Kind: Attribute::NoBuiltin);
327}
328
329bool GlobalValue::isDeclaration() const {
330 // Globals are definitions if they have an initializer.
331 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: this))
332 return GV->getNumOperands() == 0;
333
334 // Functions are definitions if they have a body.
335 if (const Function *F = dyn_cast<Function>(Val: this))
336 return F->empty() && !F->isMaterializable();
337
338 // Aliases and ifuncs are always definitions.
339 assert(isa<GlobalAlias>(this) || isa<GlobalIFunc>(this));
340 return false;
341}
342
343bool GlobalObject::canIncreaseAlignment() const {
344 // Firstly, can only increase the alignment of a global if it
345 // is a strong definition.
346 if (!isStrongDefinitionForLinker())
347 return false;
348
349 // It also has to either not have a section defined, or, not have
350 // alignment specified. (If it is assigned a section, the global
351 // could be densely packed with other objects in the section, and
352 // increasing the alignment could cause padding issues.)
353 if (hasSection() && getAlign())
354 return false;
355
356 // On ELF platforms, we're further restricted in that we can't
357 // increase the alignment of any variable which might be emitted
358 // into a shared library, and which is exported. If the main
359 // executable accesses a variable found in a shared-lib, the main
360 // exe actually allocates memory for and exports the symbol ITSELF,
361 // overriding the symbol found in the library. That is, at link
362 // time, the observed alignment of the variable is copied into the
363 // executable binary. (A COPY relocation is also generated, to copy
364 // the initial data from the shadowed variable in the shared-lib
365 // into the location in the main binary, before running code.)
366 //
367 // And thus, even though you might think you are defining the
368 // global, and allocating the memory for the global in your object
369 // file, and thus should be able to set the alignment arbitrarily,
370 // that's not actually true. Doing so can cause an ABI breakage; an
371 // executable might have already been built with the previous
372 // alignment of the variable, and then assuming an increased
373 // alignment will be incorrect.
374
375 // Conservatively assume ELF if there's no parent pointer.
376 bool isELF = (!Parent || Parent->getTargetTriple().isOSBinFormatELF());
377 if (isELF && !isDSOLocal())
378 return false;
379
380 // GV with toc-data attribute is defined in a TOC entry. To mitigate TOC
381 // overflow, the alignment of such symbol should not be increased. Otherwise,
382 // padding is needed thus more TOC entries are wasted.
383 bool isXCOFF = (!Parent || Parent->getTargetTriple().isOSBinFormatXCOFF());
384 if (isXCOFF)
385 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: this))
386 if (GV->hasAttribute(Kind: "toc-data"))
387 return false;
388
389 return true;
390}
391
392bool GlobalObject::hasMetadataOtherThanDebugLoc() const {
393 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
394 getAllMetadata(MDs);
395 for (const auto &V : MDs)
396 if (V.first != LLVMContext::MD_dbg)
397 return true;
398 return false;
399}
400
401template <typename Operation>
402static const GlobalObject *
403findBaseObject(const Constant *C, DenseSet<const GlobalAlias *> &Aliases,
404 const Operation &Op) {
405 if (auto *GO = dyn_cast<GlobalObject>(Val: C)) {
406 Op(*GO);
407 return GO;
408 }
409 if (auto *GA = dyn_cast<GlobalAlias>(Val: C)) {
410 Op(*GA);
411 if (Aliases.insert(V: GA).second)
412 return findBaseObject(GA->getOperand(i_nocapture: 0), Aliases, Op);
413 }
414 if (auto *CE = dyn_cast<ConstantExpr>(Val: C)) {
415 switch (CE->getOpcode()) {
416 case Instruction::Add: {
417 auto *LHS = findBaseObject(CE->getOperand(i_nocapture: 0), Aliases, Op);
418 auto *RHS = findBaseObject(CE->getOperand(i_nocapture: 1), Aliases, Op);
419 if (LHS && RHS)
420 return nullptr;
421 return LHS ? LHS : RHS;
422 }
423 case Instruction::Sub: {
424 if (findBaseObject(CE->getOperand(i_nocapture: 1), Aliases, Op))
425 return nullptr;
426 return findBaseObject(CE->getOperand(i_nocapture: 0), Aliases, Op);
427 }
428 case Instruction::IntToPtr:
429 case Instruction::PtrToAddr:
430 case Instruction::PtrToInt:
431 case Instruction::BitCast:
432 case Instruction::AddrSpaceCast:
433 case Instruction::GetElementPtr:
434 return findBaseObject(CE->getOperand(i_nocapture: 0), Aliases, Op);
435 default:
436 break;
437 }
438 }
439 return nullptr;
440}
441
442const GlobalObject *GlobalValue::getAliaseeObject() const {
443 DenseSet<const GlobalAlias *> Aliases;
444 return findBaseObject(C: this, Aliases, Op: [](const GlobalValue &) {});
445}
446
447bool GlobalValue::isAbsoluteSymbolRef() const {
448 auto *GO = dyn_cast<GlobalObject>(Val: this);
449 if (!GO)
450 return false;
451
452 return GO->getMetadata(KindID: LLVMContext::MD_absolute_symbol);
453}
454
455std::optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
456 auto *GO = dyn_cast<GlobalObject>(Val: this);
457 if (!GO)
458 return std::nullopt;
459
460 MDNode *MD = GO->getMetadata(KindID: LLVMContext::MD_absolute_symbol);
461 if (!MD)
462 return std::nullopt;
463
464 return getConstantRangeFromMetadata(RangeMD: *MD);
465}
466
467bool GlobalValue::canBeOmittedFromSymbolTable() const {
468 if (!hasLinkOnceODRLinkage())
469 return false;
470
471 // We assume that anyone who sets global unnamed_addr on a non-constant
472 // knows what they're doing.
473 if (hasGlobalUnnamedAddr())
474 return true;
475
476 // If it is a non constant variable, it needs to be uniqued across shared
477 // objects.
478 if (auto *Var = dyn_cast<GlobalVariable>(Val: this))
479 if (!Var->isConstant())
480 return false;
481
482 return hasAtLeastLocalUnnamedAddr();
483}
484
485//===----------------------------------------------------------------------===//
486// GlobalVariable Implementation
487//===----------------------------------------------------------------------===//
488
489GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
490 Constant *InitVal, const Twine &Name,
491 ThreadLocalMode TLMode, unsigned AddressSpace,
492 bool isExternallyInitialized)
493 : GlobalObject(Ty, Value::GlobalVariableVal, AllocMarker, Link, Name,
494 AddressSpace),
495 isConstantGlobal(constant),
496 isExternallyInitializedConstant(isExternallyInitialized) {
497 assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
498 "invalid type for global variable");
499 setThreadLocalMode(TLMode);
500 if (InitVal) {
501 assert(InitVal->getType() == Ty &&
502 "Initializer should be the same type as the GlobalVariable!");
503 Op<0>() = InitVal;
504 } else {
505 setGlobalVariableNumOperands(0);
506 }
507}
508
509GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
510 LinkageTypes Link, Constant *InitVal,
511 const Twine &Name, GlobalVariable *Before,
512 ThreadLocalMode TLMode,
513 std::optional<unsigned> AddressSpace,
514 bool isExternallyInitialized)
515 : GlobalVariable(Ty, constant, Link, InitVal, Name, TLMode,
516 AddressSpace
517 ? *AddressSpace
518 : M.getDataLayout().getDefaultGlobalsAddressSpace(),
519 isExternallyInitialized) {
520 if (Before)
521 Before->getParent()->insertGlobalVariable(Where: Before->getIterator(), GV: this);
522 else
523 M.insertGlobalVariable(GV: this);
524}
525
526void GlobalVariable::removeFromParent() {
527 getParent()->removeGlobalVariable(GV: this);
528}
529
530void GlobalVariable::eraseFromParent() {
531 getParent()->eraseGlobalVariable(GV: this);
532}
533
534void GlobalVariable::setInitializer(Constant *InitVal) {
535 if (!InitVal) {
536 if (hasInitializer()) {
537 // Note, the num operands is used to compute the offset of the operand, so
538 // the order here matters. Clearing the operand then clearing the num
539 // operands ensures we have the correct offset to the operand.
540 Op<0>().set(nullptr);
541 setGlobalVariableNumOperands(0);
542 }
543 } else {
544 assert(InitVal->getType() == getValueType() &&
545 "Initializer type must match GlobalVariable type");
546 // Note, the num operands is used to compute the offset of the operand, so
547 // the order here matters. We need to set num operands to 1 first so that
548 // we get the correct offset to the first operand when we set it.
549 if (!hasInitializer())
550 setGlobalVariableNumOperands(1);
551 Op<0>().set(InitVal);
552 }
553}
554
555void GlobalVariable::replaceInitializer(Constant *InitVal) {
556 assert(InitVal && "Can't compute type of null initializer");
557 ValueType = InitVal->getType();
558 setInitializer(InitVal);
559}
560
561uint64_t GlobalVariable::getGlobalSize(const DataLayout &DL) const {
562 // We don't support scalable global variables.
563 return DL.getTypeAllocSize(Ty: getValueType()).getFixedValue();
564}
565
566/// Copy all additional attributes (those not needed to create a GlobalVariable)
567/// from the GlobalVariable Src to this one.
568void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
569 GlobalObject::copyAttributesFrom(Src);
570 setExternallyInitialized(Src->isExternallyInitialized());
571 setAttributes(Src->getAttributes());
572 if (auto CM = Src->getCodeModel())
573 setCodeModel(*CM);
574}
575
576void GlobalVariable::dropAllReferences() {
577 User::dropAllReferences();
578 clearMetadata();
579}
580
581void GlobalVariable::setCodeModel(CodeModel::Model CM) {
582 unsigned CodeModelData = static_cast<unsigned>(CM) + 1;
583 unsigned OldData = getGlobalValueSubClassData();
584 unsigned NewData = (OldData & ~(CodeModelMask << CodeModelShift)) |
585 (CodeModelData << CodeModelShift);
586 setGlobalValueSubClassData(NewData);
587 assert(getCodeModel() == CM && "Code model representation error!");
588}
589
590void GlobalVariable::clearCodeModel() {
591 unsigned CodeModelData = 0;
592 unsigned OldData = getGlobalValueSubClassData();
593 unsigned NewData = (OldData & ~(CodeModelMask << CodeModelShift)) |
594 (CodeModelData << CodeModelShift);
595 setGlobalValueSubClassData(NewData);
596 assert(getCodeModel() == std::nullopt && "Code model representation error!");
597}
598
599//===----------------------------------------------------------------------===//
600// GlobalAlias Implementation
601//===----------------------------------------------------------------------===//
602
603GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
604 const Twine &Name, Constant *Aliasee,
605 Module *ParentModule)
606 : GlobalValue(Ty, Value::GlobalAliasVal, AllocMarker, Link, Name,
607 AddressSpace) {
608 setAliasee(Aliasee);
609 if (ParentModule)
610 ParentModule->insertAlias(Alias: this);
611}
612
613GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
614 LinkageTypes Link, const Twine &Name,
615 Constant *Aliasee, Module *ParentModule) {
616 return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
617}
618
619GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
620 LinkageTypes Linkage, const Twine &Name,
621 Module *Parent) {
622 return create(Ty, AddressSpace, Link: Linkage, Name, Aliasee: nullptr, ParentModule: Parent);
623}
624
625GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
626 LinkageTypes Linkage, const Twine &Name,
627 GlobalValue *Aliasee) {
628 return create(Ty, AddressSpace, Link: Linkage, Name, Aliasee, ParentModule: Aliasee->getParent());
629}
630
631GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
632 GlobalValue *Aliasee) {
633 return create(Ty: Aliasee->getValueType(), AddressSpace: Aliasee->getAddressSpace(), Linkage: Link, Name,
634 Aliasee);
635}
636
637GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
638 return create(Link: Aliasee->getLinkage(), Name, Aliasee);
639}
640
641void GlobalAlias::removeFromParent() { getParent()->removeAlias(Alias: this); }
642
643void GlobalAlias::eraseFromParent() { getParent()->eraseAlias(Alias: this); }
644
645void GlobalAlias::setAliasee(Constant *Aliasee) {
646 assert((!Aliasee || Aliasee->getType() == getType()) &&
647 "Alias and aliasee types should match!");
648 Op<0>().set(Aliasee);
649}
650
651const GlobalObject *GlobalAlias::getAliaseeObject() const {
652 DenseSet<const GlobalAlias *> Aliases;
653 return findBaseObject(C: getOperand(i_nocapture: 0), Aliases, Op: [](const GlobalValue &) {});
654}
655
656//===----------------------------------------------------------------------===//
657// GlobalIFunc Implementation
658//===----------------------------------------------------------------------===//
659
660GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
661 const Twine &Name, Constant *Resolver,
662 Module *ParentModule)
663 : GlobalObject(Ty, Value::GlobalIFuncVal, AllocMarker, Link, Name,
664 AddressSpace) {
665 setResolver(Resolver);
666 if (ParentModule)
667 ParentModule->insertIFunc(IFunc: this);
668}
669
670GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
671 LinkageTypes Link, const Twine &Name,
672 Constant *Resolver, Module *ParentModule) {
673 return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
674}
675
676void GlobalIFunc::removeFromParent() { getParent()->removeIFunc(IFunc: this); }
677
678void GlobalIFunc::eraseFromParent() { getParent()->eraseIFunc(IFunc: this); }
679
680const Function *GlobalIFunc::getResolverFunction() const {
681 return dyn_cast<Function>(Val: getResolver()->stripPointerCastsAndAliases());
682}
683
684void GlobalIFunc::applyAlongResolverPath(
685 function_ref<void(const GlobalValue &)> Op) const {
686 DenseSet<const GlobalAlias *> Aliases;
687 findBaseObject(C: getResolver(), Aliases, Op);
688}
689