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