1 //===-- llvm/GlobalValue.h - Class to represent a global value --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is a common base class of all globally definable objects. As such,
11 // it is subclassed by GlobalVariable, GlobalAlias and by Function. This is
12 // used because you can do certain things with these global objects that you
13 // can't do to anything else. For example, use the address of one as a
16 //===----------------------------------------------------------------------===//
18 #ifndef LLVM_IR_GLOBALVALUE_H
19 #define LLVM_IR_GLOBALVALUE_H
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MD5.h"
43 } // end namespace Intrinsic
45 class GlobalValue : public Constant {
47 /// @brief An enumeration for the kinds of linkage for global values.
49 ExternalLinkage = 0,///< Externally visible function
50 AvailableExternallyLinkage, ///< Available for inspection, not emission.
51 LinkOnceAnyLinkage, ///< Keep one copy of function when linking (inline)
52 LinkOnceODRLinkage, ///< Same, but only replaced by something equivalent.
53 WeakAnyLinkage, ///< Keep one copy of named function when linking (weak)
54 WeakODRLinkage, ///< Same, but only replaced by something equivalent.
55 AppendingLinkage, ///< Special purpose, only applies to global arrays
56 InternalLinkage, ///< Rename collisions when linking (static functions).
57 PrivateLinkage, ///< Like Internal, but omit from symbol table.
58 ExternalWeakLinkage,///< ExternalWeak linkage description.
59 CommonLinkage ///< Tentative definitions.
62 /// @brief An enumeration for the kinds of visibility of global values.
63 enum VisibilityTypes {
64 DefaultVisibility = 0, ///< The GV is visible
65 HiddenVisibility, ///< The GV is hidden
66 ProtectedVisibility ///< The GV is protected
69 /// @brief Storage classes of global values for PE targets.
70 enum DLLStorageClassTypes {
71 DefaultStorageClass = 0,
72 DLLImportStorageClass = 1, ///< Function to be imported from DLL
73 DLLExportStorageClass = 2 ///< Function to be accessible from DLL.
77 GlobalValue(Type *Ty, ValueTy VTy, Use *Ops, unsigned NumOps,
78 LinkageTypes Linkage, const Twine &Name, unsigned AddressSpace)
79 : Constant(PointerType::get(Ty, AddressSpace), VTy, Ops, NumOps),
80 ValueType(Ty), Linkage(Linkage), Visibility(DefaultVisibility),
81 UnnamedAddrVal(unsigned(UnnamedAddr::None)),
82 DllStorageClass(DefaultStorageClass), ThreadLocal(NotThreadLocal),
83 HasLLVMReservedName(false), IsDSOLocal(false),
84 IntID((Intrinsic::ID)0U), Parent(nullptr) {
90 static const unsigned GlobalValueSubClassDataBits = 17;
92 // All bitfields use unsigned as the underlying type so that MSVC will pack
94 unsigned Linkage : 4; // The linkage of this global
95 unsigned Visibility : 2; // The visibility style of this global
96 unsigned UnnamedAddrVal : 2; // This value's address is not significant
97 unsigned DllStorageClass : 2; // DLL storage class
99 unsigned ThreadLocal : 3; // Is this symbol "Thread Local", if so, what is
100 // the desired model?
102 /// True if the function's name starts with "llvm.". This corresponds to the
103 /// value of Function::isIntrinsic(), which may be true even if
104 /// Function::intrinsicID() returns Intrinsic::not_intrinsic.
105 unsigned HasLLVMReservedName : 1;
107 /// If true then there is a definition within the same linkage unit and that
108 /// definition cannot be runtime preempted.
109 unsigned IsDSOLocal : 1;
112 friend class Constant;
114 // Give subclasses access to what otherwise would be wasted padding.
115 // (17 + 4 + 2 + 2 + 2 + 3 + 1 + 1) == 32.
116 unsigned SubClassData : GlobalValueSubClassDataBits;
118 void destroyConstantImpl();
119 Value *handleOperandChangeImpl(Value *From, Value *To);
121 /// Returns true if the definition of this global may be replaced by a
122 /// differently optimized variant of the same source level function at link
124 bool mayBeDerefined() const {
125 switch (getLinkage()) {
127 case LinkOnceODRLinkage:
128 case AvailableExternallyLinkage:
132 case LinkOnceAnyLinkage:
134 case ExternalWeakLinkage:
135 case ExternalLinkage:
136 case AppendingLinkage:
137 case InternalLinkage:
139 return isInterposable();
142 llvm_unreachable("Fully covered switch above!");
146 /// \brief The intrinsic ID for this subclass (which must be a Function).
148 /// This member is defined by this class, but not used for anything.
149 /// Subclasses can use it to store their intrinsic ID, if they have one.
151 /// This is stored here to save space in Function on 64-bit hosts.
154 unsigned getGlobalValueSubClassData() const {
157 void setGlobalValueSubClassData(unsigned V) {
158 assert(V < (1 << GlobalValueSubClassDataBits) && "It will not fit");
162 Module *Parent; // The containing module.
164 // Used by SymbolTableListTraits.
165 void setParent(Module *parent) {
170 removeDeadConstantUsers(); // remove any dead constants using this.
174 enum ThreadLocalMode {
176 GeneralDynamicTLSModel,
177 LocalDynamicTLSModel,
182 GlobalValue(const GlobalValue &) = delete;
184 unsigned getAlignment() const;
186 enum class UnnamedAddr {
192 bool hasGlobalUnnamedAddr() const {
193 return getUnnamedAddr() == UnnamedAddr::Global;
196 /// Returns true if this value's address is not significant in this module.
197 /// This attribute is intended to be used only by the code generator and LTO
198 /// to allow the linker to decide whether the global needs to be in the symbol
199 /// table. It should probably not be used in optimizations, as the value may
200 /// have uses outside the module; use hasGlobalUnnamedAddr() instead.
201 bool hasAtLeastLocalUnnamedAddr() const {
202 return getUnnamedAddr() != UnnamedAddr::None;
205 UnnamedAddr getUnnamedAddr() const {
206 return UnnamedAddr(UnnamedAddrVal);
208 void setUnnamedAddr(UnnamedAddr Val) { UnnamedAddrVal = unsigned(Val); }
210 static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B) {
211 if (A == UnnamedAddr::None || B == UnnamedAddr::None)
212 return UnnamedAddr::None;
213 if (A == UnnamedAddr::Local || B == UnnamedAddr::Local)
214 return UnnamedAddr::Local;
215 return UnnamedAddr::Global;
218 bool hasComdat() const { return getComdat() != nullptr; }
219 const Comdat *getComdat() const;
220 Comdat *getComdat() {
221 return const_cast<Comdat *>(
222 static_cast<const GlobalValue *>(this)->getComdat());
225 VisibilityTypes getVisibility() const { return VisibilityTypes(Visibility); }
226 bool hasDefaultVisibility() const { return Visibility == DefaultVisibility; }
227 bool hasHiddenVisibility() const { return Visibility == HiddenVisibility; }
228 bool hasProtectedVisibility() const {
229 return Visibility == ProtectedVisibility;
231 void setVisibility(VisibilityTypes V) {
232 assert((!hasLocalLinkage() || V == DefaultVisibility) &&
233 "local linkage requires default visibility");
237 /// If the value is "Thread Local", its value isn't shared by the threads.
238 bool isThreadLocal() const { return getThreadLocalMode() != NotThreadLocal; }
239 void setThreadLocal(bool Val) {
240 setThreadLocalMode(Val ? GeneralDynamicTLSModel : NotThreadLocal);
242 void setThreadLocalMode(ThreadLocalMode Val) {
243 assert(Val == NotThreadLocal || getValueID() != Value::FunctionVal);
246 ThreadLocalMode getThreadLocalMode() const {
247 return static_cast<ThreadLocalMode>(ThreadLocal);
250 DLLStorageClassTypes getDLLStorageClass() const {
251 return DLLStorageClassTypes(DllStorageClass);
253 bool hasDLLImportStorageClass() const {
254 return DllStorageClass == DLLImportStorageClass;
256 bool hasDLLExportStorageClass() const {
257 return DllStorageClass == DLLExportStorageClass;
259 void setDLLStorageClass(DLLStorageClassTypes C) { DllStorageClass = C; }
261 bool hasSection() const { return !getSection().empty(); }
262 StringRef getSection() const;
264 /// Global values are always pointers.
265 PointerType *getType() const { return cast<PointerType>(User::getType()); }
267 Type *getValueType() const { return ValueType; }
269 void setDSOLocal(bool Local) { IsDSOLocal = Local; }
271 bool isDSOLocal() const {
275 static LinkageTypes getLinkOnceLinkage(bool ODR) {
276 return ODR ? LinkOnceODRLinkage : LinkOnceAnyLinkage;
278 static LinkageTypes getWeakLinkage(bool ODR) {
279 return ODR ? WeakODRLinkage : WeakAnyLinkage;
282 static bool isExternalLinkage(LinkageTypes Linkage) {
283 return Linkage == ExternalLinkage;
285 static bool isAvailableExternallyLinkage(LinkageTypes Linkage) {
286 return Linkage == AvailableExternallyLinkage;
288 static bool isLinkOnceODRLinkage(LinkageTypes Linkage) {
289 return Linkage == LinkOnceODRLinkage;
291 static bool isLinkOnceLinkage(LinkageTypes Linkage) {
292 return Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage;
294 static bool isWeakAnyLinkage(LinkageTypes Linkage) {
295 return Linkage == WeakAnyLinkage;
297 static bool isWeakODRLinkage(LinkageTypes Linkage) {
298 return Linkage == WeakODRLinkage;
300 static bool isWeakLinkage(LinkageTypes Linkage) {
301 return isWeakAnyLinkage(Linkage) || isWeakODRLinkage(Linkage);
303 static bool isAppendingLinkage(LinkageTypes Linkage) {
304 return Linkage == AppendingLinkage;
306 static bool isInternalLinkage(LinkageTypes Linkage) {
307 return Linkage == InternalLinkage;
309 static bool isPrivateLinkage(LinkageTypes Linkage) {
310 return Linkage == PrivateLinkage;
312 static bool isLocalLinkage(LinkageTypes Linkage) {
313 return isInternalLinkage(Linkage) || isPrivateLinkage(Linkage);
315 static bool isExternalWeakLinkage(LinkageTypes Linkage) {
316 return Linkage == ExternalWeakLinkage;
318 static bool isCommonLinkage(LinkageTypes Linkage) {
319 return Linkage == CommonLinkage;
321 static bool isValidDeclarationLinkage(LinkageTypes Linkage) {
322 return isExternalWeakLinkage(Linkage) || isExternalLinkage(Linkage);
325 /// Whether the definition of this global may be replaced by something
326 /// non-equivalent at link time. For example, if a function has weak linkage
327 /// then the code defining it may be replaced by different code.
328 static bool isInterposableLinkage(LinkageTypes Linkage) {
331 case LinkOnceAnyLinkage:
333 case ExternalWeakLinkage:
336 case AvailableExternallyLinkage:
337 case LinkOnceODRLinkage:
339 // The above three cannot be overridden but can be de-refined.
341 case ExternalLinkage:
342 case AppendingLinkage:
343 case InternalLinkage:
347 llvm_unreachable("Fully covered switch above!");
350 /// Whether the definition of this global may be discarded if it is not used
351 /// in its compilation unit.
352 static bool isDiscardableIfUnused(LinkageTypes Linkage) {
353 return isLinkOnceLinkage(Linkage) || isLocalLinkage(Linkage) ||
354 isAvailableExternallyLinkage(Linkage);
357 /// Whether the definition of this global may be replaced at link time. NB:
358 /// Using this method outside of the code generators is almost always a
359 /// mistake: when working at the IR level use isInterposable instead as it
360 /// knows about ODR semantics.
361 static bool isWeakForLinker(LinkageTypes Linkage) {
362 return Linkage == WeakAnyLinkage || Linkage == WeakODRLinkage ||
363 Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage ||
364 Linkage == CommonLinkage || Linkage == ExternalWeakLinkage;
367 /// Return true if the currently visible definition of this global (if any) is
368 /// exactly the definition we will see at runtime.
370 /// Non-exact linkage types inhibits most non-inlining IPO, since a
371 /// differently optimized variant of the same function can have different
372 /// observable or undefined behavior than in the variant currently visible.
373 /// For instance, we could have started with
375 /// void foo(int *v) {
376 /// int t = 5 / v[0];
380 /// and "refined" it to
382 /// void foo(int *v) { }
384 /// However, we cannot infer readnone for `foo`, since that would justify
385 /// DSE'ing a store to `v[0]` across a call to `foo`, which can cause
386 /// undefined behavior if the linker replaces the actual call destination with
387 /// the unoptimized `foo`.
389 /// Inlining is okay across non-exact linkage types as long as they're not
390 /// interposable (see \c isInterposable), since in such cases the currently
391 /// visible variant is *a* correct implementation of the original source
392 /// function; it just isn't the *only* correct implementation.
393 bool isDefinitionExact() const {
394 return !mayBeDerefined();
397 /// Return true if this global has an exact defintion.
398 bool hasExactDefinition() const {
399 // While this computes exactly the same thing as
400 // isStrongDefinitionForLinker, the intended uses are different. This
401 // function is intended to help decide if specific inter-procedural
402 // transforms are correct, while isStrongDefinitionForLinker's intended use
403 // is in low level code generation.
404 return !isDeclaration() && isDefinitionExact();
407 /// Return true if this global's definition can be substituted with an
408 /// *arbitrary* definition at link time. We cannot do any IPO or inlinining
409 /// across interposable call edges, since the callee can be replaced with
410 /// something arbitrary at link time.
411 bool isInterposable() const { return isInterposableLinkage(getLinkage()); }
413 bool hasExternalLinkage() const { return isExternalLinkage(getLinkage()); }
414 bool hasAvailableExternallyLinkage() const {
415 return isAvailableExternallyLinkage(getLinkage());
417 bool hasLinkOnceLinkage() const { return isLinkOnceLinkage(getLinkage()); }
418 bool hasLinkOnceODRLinkage() const {
419 return isLinkOnceODRLinkage(getLinkage());
421 bool hasWeakLinkage() const { return isWeakLinkage(getLinkage()); }
422 bool hasWeakAnyLinkage() const { return isWeakAnyLinkage(getLinkage()); }
423 bool hasWeakODRLinkage() const { return isWeakODRLinkage(getLinkage()); }
424 bool hasAppendingLinkage() const { return isAppendingLinkage(getLinkage()); }
425 bool hasInternalLinkage() const { return isInternalLinkage(getLinkage()); }
426 bool hasPrivateLinkage() const { return isPrivateLinkage(getLinkage()); }
427 bool hasLocalLinkage() const { return isLocalLinkage(getLinkage()); }
428 bool hasExternalWeakLinkage() const {
429 return isExternalWeakLinkage(getLinkage());
431 bool hasCommonLinkage() const { return isCommonLinkage(getLinkage()); }
432 bool hasValidDeclarationLinkage() const {
433 return isValidDeclarationLinkage(getLinkage());
436 void setLinkage(LinkageTypes LT) {
437 if (isLocalLinkage(LT))
438 Visibility = DefaultVisibility;
441 LinkageTypes getLinkage() const { return LinkageTypes(Linkage); }
443 bool isDiscardableIfUnused() const {
444 return isDiscardableIfUnused(getLinkage());
447 bool isWeakForLinker() const { return isWeakForLinker(getLinkage()); }
450 /// Copy all additional attributes (those not needed to create a GlobalValue)
451 /// from the GlobalValue Src to this one.
452 void copyAttributesFrom(const GlobalValue *Src);
455 /// If the given string begins with the GlobalValue name mangling escape
456 /// character '\1', drop it.
458 /// This function applies a specific mangling that is used in PGO profiles,
459 /// among other things. If you're trying to get a symbol name for an
460 /// arbitrary GlobalValue, this is not the function you're looking for; see
462 static StringRef dropLLVMManglingEscape(StringRef Name) {
463 if (!Name.empty() && Name[0] == '\1')
464 return Name.substr(1);
468 /// Return the modified name for a global value suitable to be
469 /// used as the key for a global lookup (e.g. profile or ThinLTO).
470 /// The value's original name is \c Name and has linkage of type
471 /// \c Linkage. The value is defined in module \c FileName.
472 static std::string getGlobalIdentifier(StringRef Name,
473 GlobalValue::LinkageTypes Linkage,
476 /// Return the modified name for this global value suitable to be
477 /// used as the key for a global lookup (e.g. profile or ThinLTO).
478 std::string getGlobalIdentifier() const;
480 /// Declare a type to represent a global unique identifier for a global value.
481 /// This is a 64 bits hash that is used by PGO and ThinLTO to have a compact
482 /// unique way to identify a symbol.
483 using GUID = uint64_t;
485 /// Return a 64-bit global unique ID constructed from global value name
486 /// (i.e. returned by getGlobalIdentifier()).
487 static GUID getGUID(StringRef GlobalName) { return MD5Hash(GlobalName); }
489 /// Return a 64-bit global unique ID constructed from global value name
490 /// (i.e. returned by getGlobalIdentifier()).
491 GUID getGUID() const { return getGUID(getGlobalIdentifier()); }
493 /// @name Materialization
494 /// Materialization is used to construct functions only as they're needed.
496 /// is useful to reduce memory usage in LLVM or parsing work done by the
497 /// BitcodeReader to load the Module.
500 /// If this function's Module is being lazily streamed in functions from disk
501 /// or some other source, this method can be used to check to see if the
502 /// function has been read in yet or not.
503 bool isMaterializable() const;
505 /// Make sure this GlobalValue is fully read.
510 /// Return true if the primary definition of this global value is outside of
511 /// the current translation unit.
512 bool isDeclaration() const;
514 bool isDeclarationForLinker() const {
515 if (hasAvailableExternallyLinkage())
518 return isDeclaration();
521 /// Returns true if this global's definition will be the one chosen by the
524 /// NB! Ideally this should not be used at the IR level at all. If you're
525 /// interested in optimization constraints implied by the linker's ability to
526 /// choose an implementation, prefer using \c hasExactDefinition.
527 bool isStrongDefinitionForLinker() const {
528 return !(isDeclarationForLinker() || isWeakForLinker());
531 // Returns true if the alignment of the value can be unilaterally
533 bool canIncreaseAlignment() const;
535 const GlobalObject *getBaseObject() const;
536 GlobalObject *getBaseObject() {
537 return const_cast<GlobalObject *>(
538 static_cast<const GlobalValue *>(this)->getBaseObject());
541 /// Returns whether this is a reference to an absolute symbol.
542 bool isAbsoluteSymbolRef() const;
544 /// If this is an absolute symbol reference, returns the range of the symbol,
545 /// otherwise returns None.
546 Optional<ConstantRange> getAbsoluteSymbolRange() const;
548 /// This method unlinks 'this' from the containing module, but does not delete
550 void removeFromParent();
552 /// This method unlinks 'this' from the containing module and deletes it.
553 void eraseFromParent();
555 /// Get the module that this global value is contained inside of...
556 Module *getParent() { return Parent; }
557 const Module *getParent() const { return Parent; }
559 // Methods for support type inquiry through isa, cast, and dyn_cast:
560 static bool classof(const Value *V) {
561 return V->getValueID() == Value::FunctionVal ||
562 V->getValueID() == Value::GlobalVariableVal ||
563 V->getValueID() == Value::GlobalAliasVal ||
564 V->getValueID() == Value::GlobalIFuncVal;
568 } // end namespace llvm
570 #endif // LLVM_IR_GLOBALVALUE_H