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