Recommit [NFC] Better encapsulation of llvm::Optional Storage
[llvm-complete.git] / include / llvm / IR / GlobalValue.h
blobd78ce622bc5dd099a4b6e91d29b1759b7ac0c1f0
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.
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_IR_GLOBALVALUE_H
18 #define LLVM_IR_GLOBALVALUE_H
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>
32 namespace llvm {
34 class Comdat;
35 class ConstantRange;
36 class Error;
37 class GlobalObject;
38 class Module;
40 namespace Intrinsic {
41 enum ID : unsigned;
42 } // end namespace Intrinsic
44 class GlobalValue : public Constant {
45 public:
46 /// An enumeration for the kinds of linkage for global values.
47 enum LinkageTypes {
48 ExternalLinkage = 0,///< Externally visible function
49 AvailableExternallyLinkage, ///< Available for inspection, not emission.
50 LinkOnceAnyLinkage, ///< Keep one copy of function when linking (inline)
51 LinkOnceODRLinkage, ///< Same, but only replaced by something equivalent.
52 WeakAnyLinkage, ///< Keep one copy of named function when linking (weak)
53 WeakODRLinkage, ///< Same, but only replaced by something equivalent.
54 AppendingLinkage, ///< Special purpose, only applies to global arrays
55 InternalLinkage, ///< Rename collisions when linking (static functions).
56 PrivateLinkage, ///< Like Internal, but omit from symbol table.
57 ExternalWeakLinkage,///< ExternalWeak linkage description.
58 CommonLinkage ///< Tentative definitions.
61 /// An enumeration for the kinds of visibility of global values.
62 enum VisibilityTypes {
63 DefaultVisibility = 0, ///< The GV is visible
64 HiddenVisibility, ///< The GV is hidden
65 ProtectedVisibility ///< The GV is protected
68 /// Storage classes of global values for PE targets.
69 enum DLLStorageClassTypes {
70 DefaultStorageClass = 0,
71 DLLImportStorageClass = 1, ///< Function to be imported from DLL
72 DLLExportStorageClass = 2 ///< Function to be accessible from DLL.
75 protected:
76 GlobalValue(Type *Ty, ValueTy VTy, Use *Ops, unsigned NumOps,
77 LinkageTypes Linkage, const Twine &Name, unsigned AddressSpace)
78 : Constant(PointerType::get(Ty, AddressSpace), VTy, Ops, NumOps),
79 ValueType(Ty), Visibility(DefaultVisibility),
80 UnnamedAddrVal(unsigned(UnnamedAddr::None)),
81 DllStorageClass(DefaultStorageClass), ThreadLocal(NotThreadLocal),
82 HasLLVMReservedName(false), IsDSOLocal(false), IntID((Intrinsic::ID)0U),
83 Parent(nullptr) {
84 setLinkage(Linkage);
85 setName(Name);
88 Type *ValueType;
90 static const unsigned GlobalValueSubClassDataBits = 17;
92 // All bitfields use unsigned as the underlying type so that MSVC will pack
93 // them.
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;
111 private:
112 // Give subclasses access to what otherwise would be wasted padding.
113 // (17 + 4 + 2 + 2 + 2 + 3 + 1 + 1) == 32.
114 unsigned SubClassData : GlobalValueSubClassDataBits;
116 friend class Constant;
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
123 /// time.
124 bool mayBeDerefined() const {
125 switch (getLinkage()) {
126 case WeakODRLinkage:
127 case LinkOnceODRLinkage:
128 case AvailableExternallyLinkage:
129 return true;
131 case WeakAnyLinkage:
132 case LinkOnceAnyLinkage:
133 case CommonLinkage:
134 case ExternalWeakLinkage:
135 case ExternalLinkage:
136 case AppendingLinkage:
137 case InternalLinkage:
138 case PrivateLinkage:
139 return isInterposable();
142 llvm_unreachable("Fully covered switch above!");
145 void maybeSetDsoLocal() {
146 if (hasLocalLinkage() ||
147 (!hasDefaultVisibility() && !hasExternalWeakLinkage()))
148 setDSOLocal(true);
151 protected:
152 /// The intrinsic ID for this subclass (which must be a Function).
154 /// This member is defined by this class, but not used for anything.
155 /// Subclasses can use it to store their intrinsic ID, if they have one.
157 /// This is stored here to save space in Function on 64-bit hosts.
158 Intrinsic::ID IntID;
160 unsigned getGlobalValueSubClassData() const {
161 return SubClassData;
163 void setGlobalValueSubClassData(unsigned V) {
164 assert(V < (1 << GlobalValueSubClassDataBits) && "It will not fit");
165 SubClassData = V;
168 Module *Parent; // The containing module.
170 // Used by SymbolTableListTraits.
171 void setParent(Module *parent) {
172 Parent = parent;
175 ~GlobalValue() {
176 removeDeadConstantUsers(); // remove any dead constants using this.
179 public:
180 enum ThreadLocalMode {
181 NotThreadLocal = 0,
182 GeneralDynamicTLSModel,
183 LocalDynamicTLSModel,
184 InitialExecTLSModel,
185 LocalExecTLSModel
188 GlobalValue(const GlobalValue &) = delete;
190 unsigned getAlignment() const;
191 unsigned getAddressSpace() const;
193 enum class UnnamedAddr {
194 None,
195 Local,
196 Global,
199 bool hasGlobalUnnamedAddr() const {
200 return getUnnamedAddr() == UnnamedAddr::Global;
203 /// Returns true if this value's address is not significant in this module.
204 /// This attribute is intended to be used only by the code generator and LTO
205 /// to allow the linker to decide whether the global needs to be in the symbol
206 /// table. It should probably not be used in optimizations, as the value may
207 /// have uses outside the module; use hasGlobalUnnamedAddr() instead.
208 bool hasAtLeastLocalUnnamedAddr() const {
209 return getUnnamedAddr() != UnnamedAddr::None;
212 UnnamedAddr getUnnamedAddr() const {
213 return UnnamedAddr(UnnamedAddrVal);
215 void setUnnamedAddr(UnnamedAddr Val) { UnnamedAddrVal = unsigned(Val); }
217 static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B) {
218 if (A == UnnamedAddr::None || B == UnnamedAddr::None)
219 return UnnamedAddr::None;
220 if (A == UnnamedAddr::Local || B == UnnamedAddr::Local)
221 return UnnamedAddr::Local;
222 return UnnamedAddr::Global;
225 bool hasComdat() const { return getComdat() != nullptr; }
226 const Comdat *getComdat() const;
227 Comdat *getComdat() {
228 return const_cast<Comdat *>(
229 static_cast<const GlobalValue *>(this)->getComdat());
232 VisibilityTypes getVisibility() const { return VisibilityTypes(Visibility); }
233 bool hasDefaultVisibility() const { return Visibility == DefaultVisibility; }
234 bool hasHiddenVisibility() const { return Visibility == HiddenVisibility; }
235 bool hasProtectedVisibility() const {
236 return Visibility == ProtectedVisibility;
238 void setVisibility(VisibilityTypes V) {
239 assert((!hasLocalLinkage() || V == DefaultVisibility) &&
240 "local linkage requires default visibility");
241 Visibility = V;
242 maybeSetDsoLocal();
245 /// If the value is "Thread Local", its value isn't shared by the threads.
246 bool isThreadLocal() const { return getThreadLocalMode() != NotThreadLocal; }
247 void setThreadLocal(bool Val) {
248 setThreadLocalMode(Val ? GeneralDynamicTLSModel : NotThreadLocal);
250 void setThreadLocalMode(ThreadLocalMode Val) {
251 assert(Val == NotThreadLocal || getValueID() != Value::FunctionVal);
252 ThreadLocal = Val;
254 ThreadLocalMode getThreadLocalMode() const {
255 return static_cast<ThreadLocalMode>(ThreadLocal);
258 DLLStorageClassTypes getDLLStorageClass() const {
259 return DLLStorageClassTypes(DllStorageClass);
261 bool hasDLLImportStorageClass() const {
262 return DllStorageClass == DLLImportStorageClass;
264 bool hasDLLExportStorageClass() const {
265 return DllStorageClass == DLLExportStorageClass;
267 void setDLLStorageClass(DLLStorageClassTypes C) { DllStorageClass = C; }
269 bool hasSection() const { return !getSection().empty(); }
270 StringRef getSection() const;
272 /// Global values are always pointers.
273 PointerType *getType() const { return cast<PointerType>(User::getType()); }
275 Type *getValueType() const { return ValueType; }
277 void setDSOLocal(bool Local) { IsDSOLocal = Local; }
279 bool isDSOLocal() const {
280 return IsDSOLocal;
283 static LinkageTypes getLinkOnceLinkage(bool ODR) {
284 return ODR ? LinkOnceODRLinkage : LinkOnceAnyLinkage;
286 static LinkageTypes getWeakLinkage(bool ODR) {
287 return ODR ? WeakODRLinkage : WeakAnyLinkage;
290 static bool isExternalLinkage(LinkageTypes Linkage) {
291 return Linkage == ExternalLinkage;
293 static bool isAvailableExternallyLinkage(LinkageTypes Linkage) {
294 return Linkage == AvailableExternallyLinkage;
296 static bool isLinkOnceODRLinkage(LinkageTypes Linkage) {
297 return Linkage == LinkOnceODRLinkage;
299 static bool isLinkOnceLinkage(LinkageTypes Linkage) {
300 return Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage;
302 static bool isWeakAnyLinkage(LinkageTypes Linkage) {
303 return Linkage == WeakAnyLinkage;
305 static bool isWeakODRLinkage(LinkageTypes Linkage) {
306 return Linkage == WeakODRLinkage;
308 static bool isWeakLinkage(LinkageTypes Linkage) {
309 return isWeakAnyLinkage(Linkage) || isWeakODRLinkage(Linkage);
311 static bool isAppendingLinkage(LinkageTypes Linkage) {
312 return Linkage == AppendingLinkage;
314 static bool isInternalLinkage(LinkageTypes Linkage) {
315 return Linkage == InternalLinkage;
317 static bool isPrivateLinkage(LinkageTypes Linkage) {
318 return Linkage == PrivateLinkage;
320 static bool isLocalLinkage(LinkageTypes Linkage) {
321 return isInternalLinkage(Linkage) || isPrivateLinkage(Linkage);
323 static bool isExternalWeakLinkage(LinkageTypes Linkage) {
324 return Linkage == ExternalWeakLinkage;
326 static bool isCommonLinkage(LinkageTypes Linkage) {
327 return Linkage == CommonLinkage;
329 static bool isValidDeclarationLinkage(LinkageTypes Linkage) {
330 return isExternalWeakLinkage(Linkage) || isExternalLinkage(Linkage);
333 /// Whether the definition of this global may be replaced by something
334 /// non-equivalent at link time. For example, if a function has weak linkage
335 /// then the code defining it may be replaced by different code.
336 static bool isInterposableLinkage(LinkageTypes Linkage) {
337 switch (Linkage) {
338 case WeakAnyLinkage:
339 case LinkOnceAnyLinkage:
340 case CommonLinkage:
341 case ExternalWeakLinkage:
342 return true;
344 case AvailableExternallyLinkage:
345 case LinkOnceODRLinkage:
346 case WeakODRLinkage:
347 // The above three cannot be overridden but can be de-refined.
349 case ExternalLinkage:
350 case AppendingLinkage:
351 case InternalLinkage:
352 case PrivateLinkage:
353 return false;
355 llvm_unreachable("Fully covered switch above!");
358 /// Whether the definition of this global may be discarded if it is not used
359 /// in its compilation unit.
360 static bool isDiscardableIfUnused(LinkageTypes Linkage) {
361 return isLinkOnceLinkage(Linkage) || isLocalLinkage(Linkage) ||
362 isAvailableExternallyLinkage(Linkage);
365 /// Whether the definition of this global may be replaced at link time. NB:
366 /// Using this method outside of the code generators is almost always a
367 /// mistake: when working at the IR level use isInterposable instead as it
368 /// knows about ODR semantics.
369 static bool isWeakForLinker(LinkageTypes Linkage) {
370 return Linkage == WeakAnyLinkage || Linkage == WeakODRLinkage ||
371 Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage ||
372 Linkage == CommonLinkage || Linkage == ExternalWeakLinkage;
375 /// Return true if the currently visible definition of this global (if any) is
376 /// exactly the definition we will see at runtime.
378 /// Non-exact linkage types inhibits most non-inlining IPO, since a
379 /// differently optimized variant of the same function can have different
380 /// observable or undefined behavior than in the variant currently visible.
381 /// For instance, we could have started with
383 /// void foo(int *v) {
384 /// int t = 5 / v[0];
385 /// (void) t;
386 /// }
388 /// and "refined" it to
390 /// void foo(int *v) { }
392 /// However, we cannot infer readnone for `foo`, since that would justify
393 /// DSE'ing a store to `v[0]` across a call to `foo`, which can cause
394 /// undefined behavior if the linker replaces the actual call destination with
395 /// the unoptimized `foo`.
397 /// Inlining is okay across non-exact linkage types as long as they're not
398 /// interposable (see \c isInterposable), since in such cases the currently
399 /// visible variant is *a* correct implementation of the original source
400 /// function; it just isn't the *only* correct implementation.
401 bool isDefinitionExact() const {
402 return !mayBeDerefined();
405 /// Return true if this global has an exact defintion.
406 bool hasExactDefinition() const {
407 // While this computes exactly the same thing as
408 // isStrongDefinitionForLinker, the intended uses are different. This
409 // function is intended to help decide if specific inter-procedural
410 // transforms are correct, while isStrongDefinitionForLinker's intended use
411 // is in low level code generation.
412 return !isDeclaration() && isDefinitionExact();
415 /// Return true if this global's definition can be substituted with an
416 /// *arbitrary* definition at link time. We cannot do any IPO or inlinining
417 /// across interposable call edges, since the callee can be replaced with
418 /// something arbitrary at link time.
419 bool isInterposable() const { return isInterposableLinkage(getLinkage()); }
421 bool hasExternalLinkage() const { return isExternalLinkage(getLinkage()); }
422 bool hasAvailableExternallyLinkage() const {
423 return isAvailableExternallyLinkage(getLinkage());
425 bool hasLinkOnceLinkage() const { return isLinkOnceLinkage(getLinkage()); }
426 bool hasLinkOnceODRLinkage() const {
427 return isLinkOnceODRLinkage(getLinkage());
429 bool hasWeakLinkage() const { return isWeakLinkage(getLinkage()); }
430 bool hasWeakAnyLinkage() const { return isWeakAnyLinkage(getLinkage()); }
431 bool hasWeakODRLinkage() const { return isWeakODRLinkage(getLinkage()); }
432 bool hasAppendingLinkage() const { return isAppendingLinkage(getLinkage()); }
433 bool hasInternalLinkage() const { return isInternalLinkage(getLinkage()); }
434 bool hasPrivateLinkage() const { return isPrivateLinkage(getLinkage()); }
435 bool hasLocalLinkage() const { return isLocalLinkage(getLinkage()); }
436 bool hasExternalWeakLinkage() const {
437 return isExternalWeakLinkage(getLinkage());
439 bool hasCommonLinkage() const { return isCommonLinkage(getLinkage()); }
440 bool hasValidDeclarationLinkage() const {
441 return isValidDeclarationLinkage(getLinkage());
444 void setLinkage(LinkageTypes LT) {
445 if (isLocalLinkage(LT))
446 Visibility = DefaultVisibility;
447 Linkage = LT;
448 maybeSetDsoLocal();
450 LinkageTypes getLinkage() const { return LinkageTypes(Linkage); }
452 bool isDiscardableIfUnused() const {
453 return isDiscardableIfUnused(getLinkage());
456 bool isWeakForLinker() const { return isWeakForLinker(getLinkage()); }
458 protected:
459 /// Copy all additional attributes (those not needed to create a GlobalValue)
460 /// from the GlobalValue Src to this one.
461 void copyAttributesFrom(const GlobalValue *Src);
463 public:
464 /// If the given string begins with the GlobalValue name mangling escape
465 /// character '\1', drop it.
467 /// This function applies a specific mangling that is used in PGO profiles,
468 /// among other things. If you're trying to get a symbol name for an
469 /// arbitrary GlobalValue, this is not the function you're looking for; see
470 /// Mangler.h.
471 static StringRef dropLLVMManglingEscape(StringRef Name) {
472 if (!Name.empty() && Name[0] == '\1')
473 return Name.substr(1);
474 return Name;
477 /// Return the modified name for a global value suitable to be
478 /// used as the key for a global lookup (e.g. profile or ThinLTO).
479 /// The value's original name is \c Name and has linkage of type
480 /// \c Linkage. The value is defined in module \c FileName.
481 static std::string getGlobalIdentifier(StringRef Name,
482 GlobalValue::LinkageTypes Linkage,
483 StringRef FileName);
485 /// Return the modified name for this global value suitable to be
486 /// used as the key for a global lookup (e.g. profile or ThinLTO).
487 std::string getGlobalIdentifier() const;
489 /// Declare a type to represent a global unique identifier for a global value.
490 /// This is a 64 bits hash that is used by PGO and ThinLTO to have a compact
491 /// unique way to identify a symbol.
492 using GUID = uint64_t;
494 /// Return a 64-bit global unique ID constructed from global value name
495 /// (i.e. returned by getGlobalIdentifier()).
496 static GUID getGUID(StringRef GlobalName) { return MD5Hash(GlobalName); }
498 /// Return a 64-bit global unique ID constructed from global value name
499 /// (i.e. returned by getGlobalIdentifier()).
500 GUID getGUID() const { return getGUID(getGlobalIdentifier()); }
502 /// @name Materialization
503 /// Materialization is used to construct functions only as they're needed.
504 /// This
505 /// is useful to reduce memory usage in LLVM or parsing work done by the
506 /// BitcodeReader to load the Module.
507 /// @{
509 /// If this function's Module is being lazily streamed in functions from disk
510 /// or some other source, this method can be used to check to see if the
511 /// function has been read in yet or not.
512 bool isMaterializable() const;
514 /// Make sure this GlobalValue is fully read.
515 Error materialize();
517 /// @}
519 /// Return true if the primary definition of this global value is outside of
520 /// the current translation unit.
521 bool isDeclaration() const;
523 bool isDeclarationForLinker() const {
524 if (hasAvailableExternallyLinkage())
525 return true;
527 return isDeclaration();
530 /// Returns true if this global's definition will be the one chosen by the
531 /// linker.
533 /// NB! Ideally this should not be used at the IR level at all. If you're
534 /// interested in optimization constraints implied by the linker's ability to
535 /// choose an implementation, prefer using \c hasExactDefinition.
536 bool isStrongDefinitionForLinker() const {
537 return !(isDeclarationForLinker() || isWeakForLinker());
540 // Returns true if the alignment of the value can be unilaterally
541 // increased.
542 bool canIncreaseAlignment() const;
544 const GlobalObject *getBaseObject() const;
545 GlobalObject *getBaseObject() {
546 return const_cast<GlobalObject *>(
547 static_cast<const GlobalValue *>(this)->getBaseObject());
550 /// Returns whether this is a reference to an absolute symbol.
551 bool isAbsoluteSymbolRef() const;
553 /// If this is an absolute symbol reference, returns the range of the symbol,
554 /// otherwise returns None.
555 Optional<ConstantRange> getAbsoluteSymbolRange() const;
557 /// This method unlinks 'this' from the containing module, but does not delete
558 /// it.
559 void removeFromParent();
561 /// This method unlinks 'this' from the containing module and deletes it.
562 void eraseFromParent();
564 /// Get the module that this global value is contained inside of...
565 Module *getParent() { return Parent; }
566 const Module *getParent() const { return Parent; }
568 // Methods for support type inquiry through isa, cast, and dyn_cast:
569 static bool classof(const Value *V) {
570 return V->getValueID() == Value::FunctionVal ||
571 V->getValueID() == Value::GlobalVariableVal ||
572 V->getValueID() == Value::GlobalAliasVal ||
573 V->getValueID() == Value::GlobalIFuncVal;
576 /// True if GV can be left out of the object symbol table. This is the case
577 /// for linkonce_odr values whose address is not significant. While legal, it
578 /// is not normally profitable to omit them from the .o symbol table. Using
579 /// this analysis makes sense when the information can be passed down to the
580 /// linker or we are in LTO.
581 bool canBeOmittedFromSymbolTable() const;
584 } // end namespace llvm
586 #endif // LLVM_IR_GLOBALVALUE_H