1 //===-- llvm/GlobalValue.h - Class to represent a global value --*- C++ -*-===//
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 is a common base class of all globally definable objects.  As such,
10 // it is subclassed by GlobalVariable, GlobalAlias and by Function.  This is
11 // used because you can do certain things with these global objects that you
12 // can't do to anything else.  For example, use the address of one as a
13 // constant.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #ifndef LLVM_IR_GLOBALVALUE_H
18 #define LLVM_IR_GLOBALVALUE_H
19 
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/IR/Constant.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Value.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MD5.h"
28 #include <cassert>
29 #include <cstdint>
30 #include <string>
31 
32 namespace llvm {
33 
34 class Comdat;
35 class ConstantRange;
36 class Error;
37 class GlobalObject;
38 class Module;
39 
40 namespace Intrinsic {
41 typedef unsigned ID;
42 } // end namespace Intrinsic
43 
44 // Choose ';' as the delimiter. ':' was used once but it doesn't work well for
45 // Objective-C functions which commonly have :'s in their names.
46 inline constexpr char kGlobalIdentifierDelimiter = ';';
47 
48 class GlobalValue : public Constant {
49 public:
50   /// An enumeration for the kinds of linkage for global values.
51   enum LinkageTypes {
52     ExternalLinkage = 0,///< Externally visible function
53     AvailableExternallyLinkage, ///< Available for inspection, not emission.
54     LinkOnceAnyLinkage, ///< Keep one copy of function when linking (inline)
55     LinkOnceODRLinkage, ///< Same, but only replaced by something equivalent.
56     WeakAnyLinkage,     ///< Keep one copy of named function when linking (weak)
57     WeakODRLinkage,     ///< Same, but only replaced by something equivalent.
58     AppendingLinkage,   ///< Special purpose, only applies to global arrays
59     InternalLinkage,    ///< Rename collisions when linking (static functions).
60     PrivateLinkage,     ///< Like Internal, but omit from symbol table.
61     ExternalWeakLinkage,///< ExternalWeak linkage description.
62     CommonLinkage       ///< Tentative definitions.
63   };
64 
65   /// An enumeration for the kinds of visibility of global values.
66   enum VisibilityTypes {
67     DefaultVisibility = 0,  ///< The GV is visible
68     HiddenVisibility,       ///< The GV is hidden
69     ProtectedVisibility     ///< The GV is protected
70   };
71 
72   /// Storage classes of global values for PE targets.
73   enum DLLStorageClassTypes {
74     DefaultStorageClass   = 0,
75     DLLImportStorageClass = 1, ///< Function to be imported from DLL
76     DLLExportStorageClass = 2  ///< Function to be accessible from DLL.
77   };
78 
79 protected:
GlobalValue(Type * Ty,ValueTy VTy,Use * Ops,unsigned NumOps,LinkageTypes Linkage,const Twine & Name,unsigned AddressSpace)80   GlobalValue(Type *Ty, ValueTy VTy, Use *Ops, unsigned NumOps,
81               LinkageTypes Linkage, const Twine &Name, unsigned AddressSpace)
82       : Constant(PointerType::get(Ty, AddressSpace), VTy, Ops, NumOps),
83         ValueType(Ty), Visibility(DefaultVisibility),
84         UnnamedAddrVal(unsigned(UnnamedAddr::None)),
85         DllStorageClass(DefaultStorageClass), ThreadLocal(NotThreadLocal),
86         HasLLVMReservedName(false), IsDSOLocal(false), HasPartition(false),
87         HasSanitizerMetadata(false) {
88     setLinkage(Linkage);
89     setName(Name);
90   }
91 
92   Type *ValueType;
93 
94   static const unsigned GlobalValueSubClassDataBits = 15;
95 
96   // All bitfields use unsigned as the underlying type so that MSVC will pack
97   // them.
98   unsigned Linkage : 4;       // The linkage of this global
99   unsigned Visibility : 2;    // The visibility style of this global
100   unsigned UnnamedAddrVal : 2; // This value's address is not significant
101   unsigned DllStorageClass : 2; // DLL storage class
102 
103   unsigned ThreadLocal : 3; // Is this symbol "Thread Local", if so, what is
104                             // the desired model?
105 
106   /// True if the function's name starts with "llvm.".  This corresponds to the
107   /// value of Function::isIntrinsic(), which may be true even if
108   /// Function::intrinsicID() returns Intrinsic::not_intrinsic.
109   unsigned HasLLVMReservedName : 1;
110 
111   /// If true then there is a definition within the same linkage unit and that
112   /// definition cannot be runtime preempted.
113   unsigned IsDSOLocal : 1;
114 
115   /// True if this symbol has a partition name assigned (see
116   /// https://lld.llvm.org/Partitions.html).
117   unsigned HasPartition : 1;
118 
119   /// True if this symbol has sanitizer metadata available. Should only happen
120   /// if sanitizers were enabled when building the translation unit which
121   /// contains this GV.
122   unsigned HasSanitizerMetadata : 1;
123 
124 private:
125   // Give subclasses access to what otherwise would be wasted padding.
126   // (15 + 4 + 2 + 2 + 2 + 3 + 1 + 1 + 1 + 1) == 32.
127   unsigned SubClassData : GlobalValueSubClassDataBits;
128 
129   friend class Constant;
130 
131   void destroyConstantImpl();
132   Value *handleOperandChangeImpl(Value *From, Value *To);
133 
134   /// Returns true if the definition of this global may be replaced by a
135   /// differently optimized variant of the same source level function at link
136   /// time.
mayBeDerefined()137   bool mayBeDerefined() const {
138     switch (getLinkage()) {
139     case WeakODRLinkage:
140     case LinkOnceODRLinkage:
141     case AvailableExternallyLinkage:
142       return true;
143 
144     case WeakAnyLinkage:
145     case LinkOnceAnyLinkage:
146     case CommonLinkage:
147     case ExternalWeakLinkage:
148     case ExternalLinkage:
149     case AppendingLinkage:
150     case InternalLinkage:
151     case PrivateLinkage:
152       // Optimizations may assume builtin semantics for functions defined as
153       // nobuiltin due to attributes at call-sites. To avoid applying IPO based
154       // on nobuiltin semantics, treat such function definitions as maybe
155       // derefined.
156       return isInterposable() || isNobuiltinFnDef();
157     }
158 
159     llvm_unreachable("Fully covered switch above!");
160   }
161 
162   /// Returns true if the global is a function definition with the nobuiltin
163   /// attribute.
164   bool isNobuiltinFnDef() const;
165 
166 protected:
167   /// The intrinsic ID for this subclass (which must be a Function).
168   ///
169   /// This member is defined by this class, but not used for anything.
170   /// Subclasses can use it to store their intrinsic ID, if they have one.
171   ///
172   /// This is stored here to save space in Function on 64-bit hosts.
173   Intrinsic::ID IntID = (Intrinsic::ID)0U;
174 
getGlobalValueSubClassData()175   unsigned getGlobalValueSubClassData() const {
176     return SubClassData;
177   }
setGlobalValueSubClassData(unsigned V)178   void setGlobalValueSubClassData(unsigned V) {
179     assert(V < (1 << GlobalValueSubClassDataBits) && "It will not fit");
180     SubClassData = V;
181   }
182 
183   Module *Parent = nullptr; // The containing module.
184 
185   // Used by SymbolTableListTraits.
setParent(Module * parent)186   void setParent(Module *parent) {
187     Parent = parent;
188   }
189 
~GlobalValue()190   ~GlobalValue() {
191     removeDeadConstantUsers();   // remove any dead constants using this.
192   }
193 
194 public:
195   enum ThreadLocalMode {
196     NotThreadLocal = 0,
197     GeneralDynamicTLSModel,
198     LocalDynamicTLSModel,
199     InitialExecTLSModel,
200     LocalExecTLSModel
201   };
202 
203   GlobalValue(const GlobalValue &) = delete;
204 
getAddressSpace()205   unsigned getAddressSpace() const {
206     return getType()->getAddressSpace();
207   }
208 
209   enum class UnnamedAddr {
210     None,
211     Local,
212     Global,
213   };
214 
hasGlobalUnnamedAddr()215   bool hasGlobalUnnamedAddr() const {
216     return getUnnamedAddr() == UnnamedAddr::Global;
217   }
218 
219   /// Returns true if this value's address is not significant in this module.
220   /// This attribute is intended to be used only by the code generator and LTO
221   /// to allow the linker to decide whether the global needs to be in the symbol
222   /// table. It should probably not be used in optimizations, as the value may
223   /// have uses outside the module; use hasGlobalUnnamedAddr() instead.
hasAtLeastLocalUnnamedAddr()224   bool hasAtLeastLocalUnnamedAddr() const {
225     return getUnnamedAddr() != UnnamedAddr::None;
226   }
227 
getUnnamedAddr()228   UnnamedAddr getUnnamedAddr() const {
229     return UnnamedAddr(UnnamedAddrVal);
230   }
setUnnamedAddr(UnnamedAddr Val)231   void setUnnamedAddr(UnnamedAddr Val) { UnnamedAddrVal = unsigned(Val); }
232 
getMinUnnamedAddr(UnnamedAddr A,UnnamedAddr B)233   static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B) {
234     if (A == UnnamedAddr::None || B == UnnamedAddr::None)
235       return UnnamedAddr::None;
236     if (A == UnnamedAddr::Local || B == UnnamedAddr::Local)
237       return UnnamedAddr::Local;
238     return UnnamedAddr::Global;
239   }
240 
hasComdat()241   bool hasComdat() const { return getComdat() != nullptr; }
242   const Comdat *getComdat() const;
getComdat()243   Comdat *getComdat() {
244     return const_cast<Comdat *>(
245                            static_cast<const GlobalValue *>(this)->getComdat());
246   }
247 
getVisibility()248   VisibilityTypes getVisibility() const { return VisibilityTypes(Visibility); }
hasDefaultVisibility()249   bool hasDefaultVisibility() const { return Visibility == DefaultVisibility; }
hasHiddenVisibility()250   bool hasHiddenVisibility() const { return Visibility == HiddenVisibility; }
hasProtectedVisibility()251   bool hasProtectedVisibility() const {
252     return Visibility == ProtectedVisibility;
253   }
setVisibility(VisibilityTypes V)254   void setVisibility(VisibilityTypes V) {
255     assert((!hasLocalLinkage() || V == DefaultVisibility) &&
256            "local linkage requires default visibility");
257     Visibility = V;
258     if (isImplicitDSOLocal())
259       setDSOLocal(true);
260   }
261 
262   /// If the value is "Thread Local", its value isn't shared by the threads.
isThreadLocal()263   bool isThreadLocal() const { return getThreadLocalMode() != NotThreadLocal; }
setThreadLocal(bool Val)264   void setThreadLocal(bool Val) {
265     setThreadLocalMode(Val ? GeneralDynamicTLSModel : NotThreadLocal);
266   }
setThreadLocalMode(ThreadLocalMode Val)267   void setThreadLocalMode(ThreadLocalMode Val) {
268     assert(Val == NotThreadLocal || getValueID() != Value::FunctionVal);
269     ThreadLocal = Val;
270   }
getThreadLocalMode()271   ThreadLocalMode getThreadLocalMode() const {
272     return static_cast<ThreadLocalMode>(ThreadLocal);
273   }
274 
getDLLStorageClass()275   DLLStorageClassTypes getDLLStorageClass() const {
276     return DLLStorageClassTypes(DllStorageClass);
277   }
hasDLLImportStorageClass()278   bool hasDLLImportStorageClass() const {
279     return DllStorageClass == DLLImportStorageClass;
280   }
hasDLLExportStorageClass()281   bool hasDLLExportStorageClass() const {
282     return DllStorageClass == DLLExportStorageClass;
283   }
setDLLStorageClass(DLLStorageClassTypes C)284   void setDLLStorageClass(DLLStorageClassTypes C) {
285     assert((!hasLocalLinkage() || C == DefaultStorageClass) &&
286            "local linkage requires DefaultStorageClass");
287     DllStorageClass = C;
288   }
289 
hasSection()290   bool hasSection() const { return !getSection().empty(); }
291   StringRef getSection() const;
292 
293   /// Global values are always pointers.
getType()294   PointerType *getType() const { return cast<PointerType>(User::getType()); }
295 
getValueType()296   Type *getValueType() const { return ValueType; }
297 
isImplicitDSOLocal()298   bool isImplicitDSOLocal() const {
299     return hasLocalLinkage() ||
300            (!hasDefaultVisibility() && !hasExternalWeakLinkage());
301   }
302 
setDSOLocal(bool Local)303   void setDSOLocal(bool Local) { IsDSOLocal = Local; }
304 
isDSOLocal()305   bool isDSOLocal() const {
306     return IsDSOLocal;
307   }
308 
hasPartition()309   bool hasPartition() const {
310     return HasPartition;
311   }
312   StringRef getPartition() const;
313   void setPartition(StringRef Part);
314 
315   // ASan, HWASan and Memtag sanitizers have some instrumentation that applies
316   // specifically to global variables.
317   struct SanitizerMetadata {
SanitizerMetadataSanitizerMetadata318     SanitizerMetadata()
319         : NoAddress(false), NoHWAddress(false),
320           Memtag(false), IsDynInit(false) {}
321     // For ASan and HWASan, this instrumentation is implicitly applied to all
322     // global variables when built with -fsanitize=*. What we need is a way to
323     // persist the information that a certain global variable should *not* have
324     // sanitizers applied, which occurs if:
325     //   1. The global variable is in the sanitizer ignore list, or
326     //   2. The global variable is created by the sanitizers itself for internal
327     //      usage, or
328     //   3. The global variable has __attribute__((no_sanitize("..."))) or
329     //      __attribute__((disable_sanitizer_instrumentation)).
330     //
331     // This is important, a some IR passes like GlobalMerge can delete global
332     // variables and replace them with new ones. If the old variables were
333     // marked to be unsanitized, then the new ones should also be.
334     unsigned NoAddress : 1;
335     unsigned NoHWAddress : 1;
336 
337     // Memtag sanitization works differently: sanitization is requested by clang
338     // when `-fsanitize=memtag-globals` is provided, and the request can be
339     // denied (and the attribute removed) by the AArch64 global tagging pass if
340     // it can't be fulfilled (e.g. the global variable is a TLS variable).
341     // Memtag sanitization has to interact with other parts of LLVM (like
342     // supressing certain optimisations, emitting assembly directives, or
343     // creating special relocation sections).
344     //
345     // Use `GlobalValue::isTagged()` to check whether tagging should be enabled
346     // for a global variable.
347     unsigned Memtag : 1;
348 
349     // ASan-specific metadata. Is this global variable dynamically initialized
350     // (from a C++ language perspective), and should therefore be checked for
351     // ODR violations.
352     unsigned IsDynInit : 1;
353   };
354 
hasSanitizerMetadata()355   bool hasSanitizerMetadata() const { return HasSanitizerMetadata; }
356   const SanitizerMetadata &getSanitizerMetadata() const;
357   // Note: Not byref as it's a POD and otherwise it's too easy to call
358   // G.setSanitizerMetadata(G2.getSanitizerMetadata()), and the argument becomes
359   // dangling when the backing storage allocates the metadata for `G`, as the
360   // storage is shared between `G1` and `G2`.
361   void setSanitizerMetadata(SanitizerMetadata Meta);
362   void removeSanitizerMetadata();
363 
isTagged()364   bool isTagged() const {
365     return hasSanitizerMetadata() && getSanitizerMetadata().Memtag;
366   }
367 
getLinkOnceLinkage(bool ODR)368   static LinkageTypes getLinkOnceLinkage(bool ODR) {
369     return ODR ? LinkOnceODRLinkage : LinkOnceAnyLinkage;
370   }
getWeakLinkage(bool ODR)371   static LinkageTypes getWeakLinkage(bool ODR) {
372     return ODR ? WeakODRLinkage : WeakAnyLinkage;
373   }
374 
isExternalLinkage(LinkageTypes Linkage)375   static bool isExternalLinkage(LinkageTypes Linkage) {
376     return Linkage == ExternalLinkage;
377   }
isAvailableExternallyLinkage(LinkageTypes Linkage)378   static bool isAvailableExternallyLinkage(LinkageTypes Linkage) {
379     return Linkage == AvailableExternallyLinkage;
380   }
isLinkOnceAnyLinkage(LinkageTypes Linkage)381   static bool isLinkOnceAnyLinkage(LinkageTypes Linkage) {
382     return Linkage == LinkOnceAnyLinkage;
383   }
isLinkOnceODRLinkage(LinkageTypes Linkage)384   static bool isLinkOnceODRLinkage(LinkageTypes Linkage) {
385     return Linkage == LinkOnceODRLinkage;
386   }
isLinkOnceLinkage(LinkageTypes Linkage)387   static bool isLinkOnceLinkage(LinkageTypes Linkage) {
388     return isLinkOnceAnyLinkage(Linkage) || isLinkOnceODRLinkage(Linkage);
389   }
isWeakAnyLinkage(LinkageTypes Linkage)390   static bool isWeakAnyLinkage(LinkageTypes Linkage) {
391     return Linkage == WeakAnyLinkage;
392   }
isWeakODRLinkage(LinkageTypes Linkage)393   static bool isWeakODRLinkage(LinkageTypes Linkage) {
394     return Linkage == WeakODRLinkage;
395   }
isWeakLinkage(LinkageTypes Linkage)396   static bool isWeakLinkage(LinkageTypes Linkage) {
397     return isWeakAnyLinkage(Linkage) || isWeakODRLinkage(Linkage);
398   }
isAppendingLinkage(LinkageTypes Linkage)399   static bool isAppendingLinkage(LinkageTypes Linkage) {
400     return Linkage == AppendingLinkage;
401   }
isInternalLinkage(LinkageTypes Linkage)402   static bool isInternalLinkage(LinkageTypes Linkage) {
403     return Linkage == InternalLinkage;
404   }
isPrivateLinkage(LinkageTypes Linkage)405   static bool isPrivateLinkage(LinkageTypes Linkage) {
406     return Linkage == PrivateLinkage;
407   }
isLocalLinkage(LinkageTypes Linkage)408   static bool isLocalLinkage(LinkageTypes Linkage) {
409     return isInternalLinkage(Linkage) || isPrivateLinkage(Linkage);
410   }
isExternalWeakLinkage(LinkageTypes Linkage)411   static bool isExternalWeakLinkage(LinkageTypes Linkage) {
412     return Linkage == ExternalWeakLinkage;
413   }
isCommonLinkage(LinkageTypes Linkage)414   static bool isCommonLinkage(LinkageTypes Linkage) {
415     return Linkage == CommonLinkage;
416   }
isValidDeclarationLinkage(LinkageTypes Linkage)417   static bool isValidDeclarationLinkage(LinkageTypes Linkage) {
418     return isExternalWeakLinkage(Linkage) || isExternalLinkage(Linkage);
419   }
420 
421   /// Whether the definition of this global may be replaced by something
422   /// non-equivalent at link time. For example, if a function has weak linkage
423   /// then the code defining it may be replaced by different code.
isInterposableLinkage(LinkageTypes Linkage)424   static bool isInterposableLinkage(LinkageTypes Linkage) {
425     switch (Linkage) {
426     case WeakAnyLinkage:
427     case LinkOnceAnyLinkage:
428     case CommonLinkage:
429     case ExternalWeakLinkage:
430       return true;
431 
432     case AvailableExternallyLinkage:
433     case LinkOnceODRLinkage:
434     case WeakODRLinkage:
435     // The above three cannot be overridden but can be de-refined.
436 
437     case ExternalLinkage:
438     case AppendingLinkage:
439     case InternalLinkage:
440     case PrivateLinkage:
441       return false;
442     }
443     llvm_unreachable("Fully covered switch above!");
444   }
445 
446   /// Whether the definition of this global may be discarded if it is not used
447   /// in its compilation unit.
isDiscardableIfUnused(LinkageTypes Linkage)448   static bool isDiscardableIfUnused(LinkageTypes Linkage) {
449     return isLinkOnceLinkage(Linkage) || isLocalLinkage(Linkage) ||
450            isAvailableExternallyLinkage(Linkage);
451   }
452 
453   /// Whether the definition of this global may be replaced at link time.  NB:
454   /// Using this method outside of the code generators is almost always a
455   /// mistake: when working at the IR level use isInterposable instead as it
456   /// knows about ODR semantics.
isWeakForLinker(LinkageTypes Linkage)457   static bool isWeakForLinker(LinkageTypes Linkage)  {
458     return Linkage == WeakAnyLinkage || Linkage == WeakODRLinkage ||
459            Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage ||
460            Linkage == CommonLinkage || Linkage == ExternalWeakLinkage;
461   }
462 
463   /// Return true if the currently visible definition of this global (if any) is
464   /// exactly the definition we will see at runtime.
465   ///
466   /// Non-exact linkage types inhibits most non-inlining IPO, since a
467   /// differently optimized variant of the same function can have different
468   /// observable or undefined behavior than in the variant currently visible.
469   /// For instance, we could have started with
470   ///
471   ///   void foo(int *v) {
472   ///     int t = 5 / v[0];
473   ///     (void) t;
474   ///   }
475   ///
476   /// and "refined" it to
477   ///
478   ///   void foo(int *v) { }
479   ///
480   /// However, we cannot infer readnone for `foo`, since that would justify
481   /// DSE'ing a store to `v[0]` across a call to `foo`, which can cause
482   /// undefined behavior if the linker replaces the actual call destination with
483   /// the unoptimized `foo`.
484   ///
485   /// Inlining is okay across non-exact linkage types as long as they're not
486   /// interposable (see \c isInterposable), since in such cases the currently
487   /// visible variant is *a* correct implementation of the original source
488   /// function; it just isn't the *only* correct implementation.
isDefinitionExact()489   bool isDefinitionExact() const {
490     return !mayBeDerefined();
491   }
492 
493   /// Return true if this global has an exact defintion.
hasExactDefinition()494   bool hasExactDefinition() const {
495     // While this computes exactly the same thing as
496     // isStrongDefinitionForLinker, the intended uses are different.  This
497     // function is intended to help decide if specific inter-procedural
498     // transforms are correct, while isStrongDefinitionForLinker's intended use
499     // is in low level code generation.
500     return !isDeclaration() && isDefinitionExact();
501   }
502 
503   /// Return true if this global's definition can be substituted with an
504   /// *arbitrary* definition at link time or load time. We cannot do any IPO or
505   /// inlining across interposable call edges, since the callee can be
506   /// replaced with something arbitrary.
507   bool isInterposable() const;
508   bool canBenefitFromLocalAlias() const;
509 
hasExternalLinkage()510   bool hasExternalLinkage() const { return isExternalLinkage(getLinkage()); }
hasAvailableExternallyLinkage()511   bool hasAvailableExternallyLinkage() const {
512     return isAvailableExternallyLinkage(getLinkage());
513   }
hasLinkOnceLinkage()514   bool hasLinkOnceLinkage() const { return isLinkOnceLinkage(getLinkage()); }
hasLinkOnceAnyLinkage()515   bool hasLinkOnceAnyLinkage() const {
516     return isLinkOnceAnyLinkage(getLinkage());
517   }
hasLinkOnceODRLinkage()518   bool hasLinkOnceODRLinkage() const {
519     return isLinkOnceODRLinkage(getLinkage());
520   }
hasWeakLinkage()521   bool hasWeakLinkage() const { return isWeakLinkage(getLinkage()); }
hasWeakAnyLinkage()522   bool hasWeakAnyLinkage() const { return isWeakAnyLinkage(getLinkage()); }
hasWeakODRLinkage()523   bool hasWeakODRLinkage() const { return isWeakODRLinkage(getLinkage()); }
hasAppendingLinkage()524   bool hasAppendingLinkage() const { return isAppendingLinkage(getLinkage()); }
hasInternalLinkage()525   bool hasInternalLinkage() const { return isInternalLinkage(getLinkage()); }
hasPrivateLinkage()526   bool hasPrivateLinkage() const { return isPrivateLinkage(getLinkage()); }
hasLocalLinkage()527   bool hasLocalLinkage() const { return isLocalLinkage(getLinkage()); }
hasExternalWeakLinkage()528   bool hasExternalWeakLinkage() const {
529     return isExternalWeakLinkage(getLinkage());
530   }
hasCommonLinkage()531   bool hasCommonLinkage() const { return isCommonLinkage(getLinkage()); }
hasValidDeclarationLinkage()532   bool hasValidDeclarationLinkage() const {
533     return isValidDeclarationLinkage(getLinkage());
534   }
535 
setLinkage(LinkageTypes LT)536   void setLinkage(LinkageTypes LT) {
537     if (isLocalLinkage(LT)) {
538       Visibility = DefaultVisibility;
539       DllStorageClass = DefaultStorageClass;
540     }
541     Linkage = LT;
542     if (isImplicitDSOLocal())
543       setDSOLocal(true);
544   }
getLinkage()545   LinkageTypes getLinkage() const { return LinkageTypes(Linkage); }
546 
isDiscardableIfUnused()547   bool isDiscardableIfUnused() const {
548     return isDiscardableIfUnused(getLinkage());
549   }
550 
isWeakForLinker()551   bool isWeakForLinker() const { return isWeakForLinker(getLinkage()); }
552 
553 protected:
554   /// Copy all additional attributes (those not needed to create a GlobalValue)
555   /// from the GlobalValue Src to this one.
556   void copyAttributesFrom(const GlobalValue *Src);
557 
558 public:
559   /// If the given string begins with the GlobalValue name mangling escape
560   /// character '\1', drop it.
561   ///
562   /// This function applies a specific mangling that is used in PGO profiles,
563   /// among other things. If you're trying to get a symbol name for an
564   /// arbitrary GlobalValue, this is not the function you're looking for; see
565   /// Mangler.h.
dropLLVMManglingEscape(StringRef Name)566   static StringRef dropLLVMManglingEscape(StringRef Name) {
567     Name.consume_front("\1");
568     return Name;
569   }
570 
571   /// Return the modified name for a global value suitable to be
572   /// used as the key for a global lookup (e.g. profile or ThinLTO).
573   /// The value's original name is \c Name and has linkage of type
574   /// \c Linkage. The value is defined in module \c FileName.
575   static std::string getGlobalIdentifier(StringRef Name,
576                                          GlobalValue::LinkageTypes Linkage,
577                                          StringRef FileName);
578 
579   /// Return the modified name for this global value suitable to be
580   /// used as the key for a global lookup (e.g. profile or ThinLTO).
581   std::string getGlobalIdentifier() const;
582 
583   /// Declare a type to represent a global unique identifier for a global value.
584   /// This is a 64 bits hash that is used by PGO and ThinLTO to have a compact
585   /// unique way to identify a symbol.
586   using GUID = uint64_t;
587 
588   /// Return a 64-bit global unique ID constructed from global value name
589   /// (i.e. returned by getGlobalIdentifier()).
getGUID(StringRef GlobalName)590   static GUID getGUID(StringRef GlobalName) { return MD5Hash(GlobalName); }
591 
592   /// Return a 64-bit global unique ID constructed from global value name
593   /// (i.e. returned by getGlobalIdentifier()).
getGUID()594   GUID getGUID() const { return getGUID(getGlobalIdentifier()); }
595 
596   /// @name Materialization
597   /// Materialization is used to construct functions only as they're needed.
598   /// This
599   /// is useful to reduce memory usage in LLVM or parsing work done by the
600   /// BitcodeReader to load the Module.
601   /// @{
602 
603   /// If this function's Module is being lazily streamed in functions from disk
604   /// or some other source, this method can be used to check to see if the
605   /// function has been read in yet or not.
606   bool isMaterializable() const;
607 
608   /// Make sure this GlobalValue is fully read.
609   Error materialize();
610 
611 /// @}
612 
613   /// Return true if the primary definition of this global value is outside of
614   /// the current translation unit.
615   bool isDeclaration() const;
616 
isDeclarationForLinker()617   bool isDeclarationForLinker() const {
618     if (hasAvailableExternallyLinkage())
619       return true;
620 
621     return isDeclaration();
622   }
623 
624   /// Returns true if this global's definition will be the one chosen by the
625   /// linker.
626   ///
627   /// NB! Ideally this should not be used at the IR level at all.  If you're
628   /// interested in optimization constraints implied by the linker's ability to
629   /// choose an implementation, prefer using \c hasExactDefinition.
isStrongDefinitionForLinker()630   bool isStrongDefinitionForLinker() const {
631     return !(isDeclarationForLinker() || isWeakForLinker());
632   }
633 
634   const GlobalObject *getAliaseeObject() const;
getAliaseeObject()635   GlobalObject *getAliaseeObject() {
636     return const_cast<GlobalObject *>(
637         static_cast<const GlobalValue *>(this)->getAliaseeObject());
638   }
639 
640   /// Returns whether this is a reference to an absolute symbol.
641   bool isAbsoluteSymbolRef() const;
642 
643   /// If this is an absolute symbol reference, returns the range of the symbol,
644   /// otherwise returns std::nullopt.
645   std::optional<ConstantRange> getAbsoluteSymbolRange() const;
646 
647   /// This method unlinks 'this' from the containing module, but does not delete
648   /// it.
649   void removeFromParent();
650 
651   /// This method unlinks 'this' from the containing module and deletes it.
652   void eraseFromParent();
653 
654   /// Get the module that this global value is contained inside of...
getParent()655   Module *getParent() { return Parent; }
getParent()656   const Module *getParent() const { return Parent; }
657 
658   // Methods for support type inquiry through isa, cast, and dyn_cast:
classof(const Value * V)659   static bool classof(const Value *V) {
660     return V->getValueID() == Value::FunctionVal ||
661            V->getValueID() == Value::GlobalVariableVal ||
662            V->getValueID() == Value::GlobalAliasVal ||
663            V->getValueID() == Value::GlobalIFuncVal;
664   }
665 
666   /// True if GV can be left out of the object symbol table. This is the case
667   /// for linkonce_odr values whose address is not significant. While legal, it
668   /// is not normally profitable to omit them from the .o symbol table. Using
669   /// this analysis makes sense when the information can be passed down to the
670   /// linker or we are in LTO.
671   bool canBeOmittedFromSymbolTable() const;
672 };
673 
674 } // end namespace llvm
675 
676 #endif // LLVM_IR_GLOBALVALUE_H
677