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
32namespace llvm {
33
34class Comdat;
35class ConstantRange;
36class Error;
37class GlobalObject;
38class Module;
39
40namespace Intrinsic {
41typedef unsigned ID;
42} // end namespace Intrinsic
43
44class GlobalValue : public Constant {
45public:
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.
59 };
60
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
66 };
67
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.
73 };
74
75protected:
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), HasPartition(false),
83 IntID((Intrinsic::ID)0U), Parent(nullptr) {
84 setLinkage(Linkage);
85 setName(Name);
86 }
87
88 Type *ValueType;
89
90 static const unsigned GlobalValueSubClassDataBits = 16;
91
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
98
99 unsigned ThreadLocal : 3; // Is this symbol "Thread Local", if so, what is
100 // the desired model?
101
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;
106
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;
110
111 /// True if this symbol has a partition name assigned (see
112 /// https://lld.llvm.org/Partitions.html).
113 unsigned HasPartition : 1;
114
115private:
116 // Give subclasses access to what otherwise would be wasted padding.
117 // (16 + 4 + 2 + 2 + 2 + 3 + 1 + 1 + 1) == 32.
118 unsigned SubClassData : GlobalValueSubClassDataBits;
119
120 friend class Constant;
121
122 void destroyConstantImpl();
123 Value *handleOperandChangeImpl(Value *From, Value *To);
124
125 /// Returns true if the definition of this global may be replaced by a
126 /// differently optimized variant of the same source level function at link
127 /// time.
128 bool mayBeDerefined() const {
129 switch (getLinkage()) {
130 case WeakODRLinkage:
131 case LinkOnceODRLinkage:
132 case AvailableExternallyLinkage:
133 return true;
134
135 case WeakAnyLinkage:
136 case LinkOnceAnyLinkage:
137 case CommonLinkage:
138 case ExternalWeakLinkage:
139 case ExternalLinkage:
140 case AppendingLinkage:
141 case InternalLinkage:
142 case PrivateLinkage:
143 return isInterposable();
144 }
145
146 llvm_unreachable("Fully covered switch above!");
147 }
148
149protected:
150 /// The intrinsic ID for this subclass (which must be a Function).
151 ///
152 /// This member is defined by this class, but not used for anything.
153 /// Subclasses can use it to store their intrinsic ID, if they have one.
154 ///
155 /// This is stored here to save space in Function on 64-bit hosts.
156 Intrinsic::ID IntID;
157
158 unsigned getGlobalValueSubClassData() const {
159 return SubClassData;
160 }
161 void setGlobalValueSubClassData(unsigned V) {
162 assert(V < (1 << GlobalValueSubClassDataBits) && "It will not fit");
163 SubClassData = V;
164 }
165
166 Module *Parent; // The containing module.
167
168 // Used by SymbolTableListTraits.
169 void setParent(Module *parent) {
170 Parent = parent;
171 }
172
173 ~GlobalValue() {
174 removeDeadConstantUsers(); // remove any dead constants using this.
175 }
176
177public:
178 enum ThreadLocalMode {
179 NotThreadLocal = 0,
180 GeneralDynamicTLSModel,
181 LocalDynamicTLSModel,
182 InitialExecTLSModel,
183 LocalExecTLSModel
184 };
185
186 GlobalValue(const GlobalValue &) = delete;
187
188 unsigned getAddressSpace() const;
189
190 enum class UnnamedAddr {
191 None,
192 Local,
193 Global,
194 };
195
196 bool hasGlobalUnnamedAddr() const {
197 return getUnnamedAddr() == UnnamedAddr::Global;
198 }
199
200 /// Returns true if this value's address is not significant in this module.
201 /// This attribute is intended to be used only by the code generator and LTO
202 /// to allow the linker to decide whether the global needs to be in the symbol
203 /// table. It should probably not be used in optimizations, as the value may
204 /// have uses outside the module; use hasGlobalUnnamedAddr() instead.
205 bool hasAtLeastLocalUnnamedAddr() const {
206 return getUnnamedAddr() != UnnamedAddr::None;
207 }
208
209 UnnamedAddr getUnnamedAddr() const {
210 return UnnamedAddr(UnnamedAddrVal);
211 }
212 void setUnnamedAddr(UnnamedAddr Val) { UnnamedAddrVal = unsigned(Val); }
213
214 static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B) {
215 if (A == UnnamedAddr::None || B == UnnamedAddr::None)
216 return UnnamedAddr::None;
217 if (A == UnnamedAddr::Local || B == UnnamedAddr::Local)
218 return UnnamedAddr::Local;
219 return UnnamedAddr::Global;
220 }
221
222 bool hasComdat() const { return getComdat() != nullptr; }
223 const Comdat *getComdat() const;
224 Comdat *getComdat() {
225 return const_cast<Comdat *>(
226 static_cast<const GlobalValue *>(this)->getComdat());
227 }
228
229 VisibilityTypes getVisibility() const { return VisibilityTypes(Visibility); }
230 bool hasDefaultVisibility() const { return Visibility == DefaultVisibility; }
231 bool hasHiddenVisibility() const { return Visibility == HiddenVisibility; }
232 bool hasProtectedVisibility() const {
233 return Visibility == ProtectedVisibility;
234 }
235 void setVisibility(VisibilityTypes V) {
236 assert((!hasLocalLinkage() || V == DefaultVisibility) &&
237 "local linkage requires default visibility");
238 Visibility = V;
239 if (isImplicitDSOLocal())
240 setDSOLocal(true);
241 }
242
243 /// If the value is "Thread Local", its value isn't shared by the threads.
244 bool isThreadLocal() const { return getThreadLocalMode() != NotThreadLocal; }
245 void setThreadLocal(bool Val) {
246 setThreadLocalMode(Val ? GeneralDynamicTLSModel : NotThreadLocal);
247 }
248 void setThreadLocalMode(ThreadLocalMode Val) {
249 assert(Val == NotThreadLocal || getValueID() != Value::FunctionVal);
250 ThreadLocal = Val;
251 }
252 ThreadLocalMode getThreadLocalMode() const {
253 return static_cast<ThreadLocalMode>(ThreadLocal);
254 }
255
256 DLLStorageClassTypes getDLLStorageClass() const {
257 return DLLStorageClassTypes(DllStorageClass);
258 }
259 bool hasDLLImportStorageClass() const {
260 return DllStorageClass == DLLImportStorageClass;
261 }
262 bool hasDLLExportStorageClass() const {
263 return DllStorageClass == DLLExportStorageClass;
264 }
265 void setDLLStorageClass(DLLStorageClassTypes C) { DllStorageClass = C; }
266
267 bool hasSection() const { return !getSection().empty(); }
268 StringRef getSection() const;
269
270 /// Global values are always pointers.
271 PointerType *getType() const { return cast<PointerType>(User::getType()); }
272
273 Type *getValueType() const { return ValueType; }
274
275 bool isImplicitDSOLocal() const {
276 return hasLocalLinkage() ||
277 (!hasDefaultVisibility() && !hasExternalWeakLinkage());
278 }
279
280 void setDSOLocal(bool Local) { IsDSOLocal = Local; }
281
282 bool isDSOLocal() const {
283 return IsDSOLocal;
284 }
285
286 bool hasPartition() const {
287 return HasPartition;
288 }
289 StringRef getPartition() const;
290 void setPartition(StringRef Part);
291
292 static LinkageTypes getLinkOnceLinkage(bool ODR) {
293 return ODR ? LinkOnceODRLinkage : LinkOnceAnyLinkage;
294 }
295 static LinkageTypes getWeakLinkage(bool ODR) {
296 return ODR ? WeakODRLinkage : WeakAnyLinkage;
297 }
298
299 static bool isExternalLinkage(LinkageTypes Linkage) {
300 return Linkage == ExternalLinkage;
301 }
302 static bool isAvailableExternallyLinkage(LinkageTypes Linkage) {
303 return Linkage == AvailableExternallyLinkage;
304 }
305 static bool isLinkOnceODRLinkage(LinkageTypes Linkage) {
306 return Linkage == LinkOnceODRLinkage;
307 }
308 static bool isLinkOnceLinkage(LinkageTypes Linkage) {
309 return Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage;
310 }
311 static bool isWeakAnyLinkage(LinkageTypes Linkage) {
312 return Linkage == WeakAnyLinkage;
313 }
314 static bool isWeakODRLinkage(LinkageTypes Linkage) {
315 return Linkage == WeakODRLinkage;
316 }
317 static bool isWeakLinkage(LinkageTypes Linkage) {
318 return isWeakAnyLinkage(Linkage) || isWeakODRLinkage(Linkage);
319 }
320 static bool isAppendingLinkage(LinkageTypes Linkage) {
321 return Linkage == AppendingLinkage;
322 }
323 static bool isInternalLinkage(LinkageTypes Linkage) {
324 return Linkage == InternalLinkage;
325 }
326 static bool isPrivateLinkage(LinkageTypes Linkage) {
327 return Linkage == PrivateLinkage;
328 }
329 static bool isLocalLinkage(LinkageTypes Linkage) {
330 return isInternalLinkage(Linkage) || isPrivateLinkage(Linkage);
331 }
332 static bool isExternalWeakLinkage(LinkageTypes Linkage) {
333 return Linkage == ExternalWeakLinkage;
334 }
335 static bool isCommonLinkage(LinkageTypes Linkage) {
336 return Linkage == CommonLinkage;
337 }
338 static bool isValidDeclarationLinkage(LinkageTypes Linkage) {
339 return isExternalWeakLinkage(Linkage) || isExternalLinkage(Linkage);
340 }
341
342 /// Whether the definition of this global may be replaced by something
343 /// non-equivalent at link time. For example, if a function has weak linkage
344 /// then the code defining it may be replaced by different code.
345 static bool isInterposableLinkage(LinkageTypes Linkage) {
346 switch (Linkage) {
347 case WeakAnyLinkage:
348 case LinkOnceAnyLinkage:
349 case CommonLinkage:
350 case ExternalWeakLinkage:
351 return true;
352
353 case AvailableExternallyLinkage:
354 case LinkOnceODRLinkage:
355 case WeakODRLinkage:
356 // The above three cannot be overridden but can be de-refined.
357
358 case ExternalLinkage:
359 case AppendingLinkage:
360 case InternalLinkage:
361 case PrivateLinkage:
362 return false;
363 }
364 llvm_unreachable("Fully covered switch above!");
365 }
366
367 /// Whether the definition of this global may be discarded if it is not used
368 /// in its compilation unit.
369 static bool isDiscardableIfUnused(LinkageTypes Linkage) {
370 return isLinkOnceLinkage(Linkage) || isLocalLinkage(Linkage) ||
371 isAvailableExternallyLinkage(Linkage);
372 }
373
374 /// Whether the definition of this global may be replaced at link time. NB:
375 /// Using this method outside of the code generators is almost always a
376 /// mistake: when working at the IR level use isInterposable instead as it
377 /// knows about ODR semantics.
378 static bool isWeakForLinker(LinkageTypes Linkage) {
379 return Linkage == WeakAnyLinkage || Linkage == WeakODRLinkage ||
380 Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage ||
381 Linkage == CommonLinkage || Linkage == ExternalWeakLinkage;
382 }
383
384 /// Return true if the currently visible definition of this global (if any) is
385 /// exactly the definition we will see at runtime.
386 ///
387 /// Non-exact linkage types inhibits most non-inlining IPO, since a
388 /// differently optimized variant of the same function can have different
389 /// observable or undefined behavior than in the variant currently visible.
390 /// For instance, we could have started with
391 ///
392 /// void foo(int *v) {
393 /// int t = 5 / v[0];
394 /// (void) t;
395 /// }
396 ///
397 /// and "refined" it to
398 ///
399 /// void foo(int *v) { }
400 ///
401 /// However, we cannot infer readnone for `foo`, since that would justify
402 /// DSE'ing a store to `v[0]` across a call to `foo`, which can cause
403 /// undefined behavior if the linker replaces the actual call destination with
404 /// the unoptimized `foo`.
405 ///
406 /// Inlining is okay across non-exact linkage types as long as they're not
407 /// interposable (see \c isInterposable), since in such cases the currently
408 /// visible variant is *a* correct implementation of the original source
409 /// function; it just isn't the *only* correct implementation.
410 bool isDefinitionExact() const {
411 return !mayBeDerefined();
412 }
413
414 /// Return true if this global has an exact defintion.
415 bool hasExactDefinition() const {
416 // While this computes exactly the same thing as
417 // isStrongDefinitionForLinker, the intended uses are different. This
418 // function is intended to help decide if specific inter-procedural
419 // transforms are correct, while isStrongDefinitionForLinker's intended use
420 // is in low level code generation.
421 return !isDeclaration() && isDefinitionExact();
422 }
423
424 /// Return true if this global's definition can be substituted with an
425 /// *arbitrary* definition at link time or load time. We cannot do any IPO or
426 /// inlining across interposable call edges, since the callee can be
427 /// replaced with something arbitrary.
428 bool isInterposable() const;
429 bool canBenefitFromLocalAlias() const;
430
431 bool hasExternalLinkage() const { return isExternalLinkage(getLinkage()); }
432 bool hasAvailableExternallyLinkage() const {
433 return isAvailableExternallyLinkage(getLinkage());
434 }
435 bool hasLinkOnceLinkage() const { return isLinkOnceLinkage(getLinkage()); }
436 bool hasLinkOnceODRLinkage() const {
437 return isLinkOnceODRLinkage(getLinkage());
438 }
439 bool hasWeakLinkage() const { return isWeakLinkage(getLinkage()); }
440 bool hasWeakAnyLinkage() const { return isWeakAnyLinkage(getLinkage()); }
441 bool hasWeakODRLinkage() const { return isWeakODRLinkage(getLinkage()); }
442 bool hasAppendingLinkage() const { return isAppendingLinkage(getLinkage()); }
443 bool hasInternalLinkage() const { return isInternalLinkage(getLinkage()); }
444 bool hasPrivateLinkage() const { return isPrivateLinkage(getLinkage()); }
445 bool hasLocalLinkage() const { return isLocalLinkage(getLinkage()); }
446 bool hasExternalWeakLinkage() const {
447 return isExternalWeakLinkage(getLinkage());
448 }
449 bool hasCommonLinkage() const { return isCommonLinkage(getLinkage()); }
450 bool hasValidDeclarationLinkage() const {
451 return isValidDeclarationLinkage(getLinkage());
452 }
453
454 void setLinkage(LinkageTypes LT) {
455 if (isLocalLinkage(LT))
456 Visibility = DefaultVisibility;
457 Linkage = LT;
458 if (isImplicitDSOLocal())
459 setDSOLocal(true);
460 }
461 LinkageTypes getLinkage() const { return LinkageTypes(Linkage); }
462
463 bool isDiscardableIfUnused() const {
464 return isDiscardableIfUnused(getLinkage());
465 }
466
467 bool isWeakForLinker() const { return isWeakForLinker(getLinkage()); }
468
469protected:
470 /// Copy all additional attributes (those not needed to create a GlobalValue)
471 /// from the GlobalValue Src to this one.
472 void copyAttributesFrom(const GlobalValue *Src);
473
474public:
475 /// If the given string begins with the GlobalValue name mangling escape
476 /// character '\1', drop it.
477 ///
478 /// This function applies a specific mangling that is used in PGO profiles,
479 /// among other things. If you're trying to get a symbol name for an
480 /// arbitrary GlobalValue, this is not the function you're looking for; see
481 /// Mangler.h.
482 static StringRef dropLLVMManglingEscape(StringRef Name) {
483 if (!Name.empty() && Name[0] == '\1')
484 return Name.substr(1);
485 return Name;
486 }
487
488 /// Return the modified name for a global value suitable to be
489 /// used as the key for a global lookup (e.g. profile or ThinLTO).
490 /// The value's original name is \c Name and has linkage of type
491 /// \c Linkage. The value is defined in module \c FileName.
492 static std::string getGlobalIdentifier(StringRef Name,
493 GlobalValue::LinkageTypes Linkage,
494 StringRef FileName);
495
496 /// Return the modified name for this global value suitable to be
497 /// used as the key for a global lookup (e.g. profile or ThinLTO).
498 std::string getGlobalIdentifier() const;
499
500 /// Declare a type to represent a global unique identifier for a global value.
501 /// This is a 64 bits hash that is used by PGO and ThinLTO to have a compact
502 /// unique way to identify a symbol.
503 using GUID = uint64_t;
504
505 /// Return a 64-bit global unique ID constructed from global value name
506 /// (i.e. returned by getGlobalIdentifier()).
507 static GUID getGUID(StringRef GlobalName) { return MD5Hash(GlobalName); }
508
509 /// Return a 64-bit global unique ID constructed from global value name
510 /// (i.e. returned by getGlobalIdentifier()).
511 GUID getGUID() const { return getGUID(getGlobalIdentifier()); }
512
513 /// @name Materialization
514 /// Materialization is used to construct functions only as they're needed.
515 /// This
516 /// is useful to reduce memory usage in LLVM or parsing work done by the
517 /// BitcodeReader to load the Module.
518 /// @{
519
520 /// If this function's Module is being lazily streamed in functions from disk
521 /// or some other source, this method can be used to check to see if the
522 /// function has been read in yet or not.
523 bool isMaterializable() const;
524
525 /// Make sure this GlobalValue is fully read.
526 Error materialize();
527
528/// @}
529
530 /// Return true if the primary definition of this global value is outside of
531 /// the current translation unit.
532 bool isDeclaration() const;
533
534 bool isDeclarationForLinker() const {
535 if (hasAvailableExternallyLinkage())
536 return true;
537
538 return isDeclaration();
539 }
540
541 /// Returns true if this global's definition will be the one chosen by the
542 /// linker.
543 ///
544 /// NB! Ideally this should not be used at the IR level at all. If you're
545 /// interested in optimization constraints implied by the linker's ability to
546 /// choose an implementation, prefer using \c hasExactDefinition.
547 bool isStrongDefinitionForLinker() const {
548 return !(isDeclarationForLinker() || isWeakForLinker());
549 }
550
551 const GlobalObject *getBaseObject() const;
552 GlobalObject *getBaseObject() {
553 return const_cast<GlobalObject *>(
554 static_cast<const GlobalValue *>(this)->getBaseObject());
555 }
556
557 /// Returns whether this is a reference to an absolute symbol.
558 bool isAbsoluteSymbolRef() const;
559
560 /// If this is an absolute symbol reference, returns the range of the symbol,
561 /// otherwise returns None.
562 Optional<ConstantRange> getAbsoluteSymbolRange() const;
563
564 /// This method unlinks 'this' from the containing module, but does not delete
565 /// it.
566 void removeFromParent();
567
568 /// This method unlinks 'this' from the containing module and deletes it.
569 void eraseFromParent();
570
571 /// Get the module that this global value is contained inside of...
572 Module *getParent() { return Parent; }
573 const Module *getParent() const { return Parent; }
574
575 // Methods for support type inquiry through isa, cast, and dyn_cast:
576 static bool classof(const Value *V) {
577 return V->getValueID() == Value::FunctionVal ||
578 V->getValueID() == Value::GlobalVariableVal ||
579 V->getValueID() == Value::GlobalAliasVal ||
580 V->getValueID() == Value::GlobalIFuncVal;
581 }
582
583 /// True if GV can be left out of the object symbol table. This is the case
584 /// for linkonce_odr values whose address is not significant. While legal, it
585 /// is not normally profitable to omit them from the .o symbol table. Using
586 /// this analysis makes sense when the information can be passed down to the
587 /// linker or we are in LTO.
588 bool canBeOmittedFromSymbolTable() const;
589};
590
591} // end namespace llvm
592
593#endif // LLVM_IR_GLOBALVALUE_H
594