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 <cassert> 28 #include <cstdint> 29 #include <string> 30 31 namespace llvm { 32 33 class Comdat; 34 class ConstantRange; 35 class DataLayout; 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 GlobalIdentifierDelimiter = ';'; 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 void setNoSanitizeMetadata(); 364 isTagged()365 bool isTagged() const { 366 return hasSanitizerMetadata() && getSanitizerMetadata().Memtag; 367 } 368 getLinkOnceLinkage(bool ODR)369 static LinkageTypes getLinkOnceLinkage(bool ODR) { 370 return ODR ? LinkOnceODRLinkage : LinkOnceAnyLinkage; 371 } getWeakLinkage(bool ODR)372 static LinkageTypes getWeakLinkage(bool ODR) { 373 return ODR ? WeakODRLinkage : WeakAnyLinkage; 374 } 375 isExternalLinkage(LinkageTypes Linkage)376 static bool isExternalLinkage(LinkageTypes Linkage) { 377 return Linkage == ExternalLinkage; 378 } isAvailableExternallyLinkage(LinkageTypes Linkage)379 static bool isAvailableExternallyLinkage(LinkageTypes Linkage) { 380 return Linkage == AvailableExternallyLinkage; 381 } isLinkOnceAnyLinkage(LinkageTypes Linkage)382 static bool isLinkOnceAnyLinkage(LinkageTypes Linkage) { 383 return Linkage == LinkOnceAnyLinkage; 384 } isLinkOnceODRLinkage(LinkageTypes Linkage)385 static bool isLinkOnceODRLinkage(LinkageTypes Linkage) { 386 return Linkage == LinkOnceODRLinkage; 387 } isLinkOnceLinkage(LinkageTypes Linkage)388 static bool isLinkOnceLinkage(LinkageTypes Linkage) { 389 return isLinkOnceAnyLinkage(Linkage) || isLinkOnceODRLinkage(Linkage); 390 } isWeakAnyLinkage(LinkageTypes Linkage)391 static bool isWeakAnyLinkage(LinkageTypes Linkage) { 392 return Linkage == WeakAnyLinkage; 393 } isWeakODRLinkage(LinkageTypes Linkage)394 static bool isWeakODRLinkage(LinkageTypes Linkage) { 395 return Linkage == WeakODRLinkage; 396 } isWeakLinkage(LinkageTypes Linkage)397 static bool isWeakLinkage(LinkageTypes Linkage) { 398 return isWeakAnyLinkage(Linkage) || isWeakODRLinkage(Linkage); 399 } isAppendingLinkage(LinkageTypes Linkage)400 static bool isAppendingLinkage(LinkageTypes Linkage) { 401 return Linkage == AppendingLinkage; 402 } isInternalLinkage(LinkageTypes Linkage)403 static bool isInternalLinkage(LinkageTypes Linkage) { 404 return Linkage == InternalLinkage; 405 } isPrivateLinkage(LinkageTypes Linkage)406 static bool isPrivateLinkage(LinkageTypes Linkage) { 407 return Linkage == PrivateLinkage; 408 } isLocalLinkage(LinkageTypes Linkage)409 static bool isLocalLinkage(LinkageTypes Linkage) { 410 return isInternalLinkage(Linkage) || isPrivateLinkage(Linkage); 411 } isExternalWeakLinkage(LinkageTypes Linkage)412 static bool isExternalWeakLinkage(LinkageTypes Linkage) { 413 return Linkage == ExternalWeakLinkage; 414 } isCommonLinkage(LinkageTypes Linkage)415 static bool isCommonLinkage(LinkageTypes Linkage) { 416 return Linkage == CommonLinkage; 417 } isValidDeclarationLinkage(LinkageTypes Linkage)418 static bool isValidDeclarationLinkage(LinkageTypes Linkage) { 419 return isExternalWeakLinkage(Linkage) || isExternalLinkage(Linkage); 420 } 421 422 /// Whether the definition of this global may be replaced by something 423 /// non-equivalent at link time. For example, if a function has weak linkage 424 /// then the code defining it may be replaced by different code. isInterposableLinkage(LinkageTypes Linkage)425 static bool isInterposableLinkage(LinkageTypes Linkage) { 426 switch (Linkage) { 427 case WeakAnyLinkage: 428 case LinkOnceAnyLinkage: 429 case CommonLinkage: 430 case ExternalWeakLinkage: 431 return true; 432 433 case AvailableExternallyLinkage: 434 case LinkOnceODRLinkage: 435 case WeakODRLinkage: 436 // The above three cannot be overridden but can be de-refined. 437 438 case ExternalLinkage: 439 case AppendingLinkage: 440 case InternalLinkage: 441 case PrivateLinkage: 442 return false; 443 } 444 llvm_unreachable("Fully covered switch above!"); 445 } 446 447 /// Whether the definition of this global may be discarded if it is not used 448 /// in its compilation unit. isDiscardableIfUnused(LinkageTypes Linkage)449 static bool isDiscardableIfUnused(LinkageTypes Linkage) { 450 return isLinkOnceLinkage(Linkage) || isLocalLinkage(Linkage) || 451 isAvailableExternallyLinkage(Linkage); 452 } 453 454 /// Whether the definition of this global may be replaced at link time. NB: 455 /// Using this method outside of the code generators is almost always a 456 /// mistake: when working at the IR level use isInterposable instead as it 457 /// knows about ODR semantics. isWeakForLinker(LinkageTypes Linkage)458 static bool isWeakForLinker(LinkageTypes Linkage) { 459 return Linkage == WeakAnyLinkage || Linkage == WeakODRLinkage || 460 Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage || 461 Linkage == CommonLinkage || Linkage == ExternalWeakLinkage; 462 } 463 464 /// Return true if the currently visible definition of this global (if any) is 465 /// exactly the definition we will see at runtime. 466 /// 467 /// Non-exact linkage types inhibits most non-inlining IPO, since a 468 /// differently optimized variant of the same function can have different 469 /// observable or undefined behavior than in the variant currently visible. 470 /// For instance, we could have started with 471 /// 472 /// void foo(int *v) { 473 /// int t = 5 / v[0]; 474 /// (void) t; 475 /// } 476 /// 477 /// and "refined" it to 478 /// 479 /// void foo(int *v) { } 480 /// 481 /// However, we cannot infer readnone for `foo`, since that would justify 482 /// DSE'ing a store to `v[0]` across a call to `foo`, which can cause 483 /// undefined behavior if the linker replaces the actual call destination with 484 /// the unoptimized `foo`. 485 /// 486 /// Inlining is okay across non-exact linkage types as long as they're not 487 /// interposable (see \c isInterposable), since in such cases the currently 488 /// visible variant is *a* correct implementation of the original source 489 /// function; it just isn't the *only* correct implementation. isDefinitionExact()490 bool isDefinitionExact() const { 491 return !mayBeDerefined(); 492 } 493 494 /// Return true if this global has an exact defintion. hasExactDefinition()495 bool hasExactDefinition() const { 496 // While this computes exactly the same thing as 497 // isStrongDefinitionForLinker, the intended uses are different. This 498 // function is intended to help decide if specific inter-procedural 499 // transforms are correct, while isStrongDefinitionForLinker's intended use 500 // is in low level code generation. 501 return !isDeclaration() && isDefinitionExact(); 502 } 503 504 /// Return true if this global's definition can be substituted with an 505 /// *arbitrary* definition at link time or load time. We cannot do any IPO or 506 /// inlining across interposable call edges, since the callee can be 507 /// replaced with something arbitrary. 508 bool isInterposable() const; 509 bool canBenefitFromLocalAlias() const; 510 hasExternalLinkage()511 bool hasExternalLinkage() const { return isExternalLinkage(getLinkage()); } hasAvailableExternallyLinkage()512 bool hasAvailableExternallyLinkage() const { 513 return isAvailableExternallyLinkage(getLinkage()); 514 } hasLinkOnceLinkage()515 bool hasLinkOnceLinkage() const { return isLinkOnceLinkage(getLinkage()); } hasLinkOnceAnyLinkage()516 bool hasLinkOnceAnyLinkage() const { 517 return isLinkOnceAnyLinkage(getLinkage()); 518 } hasLinkOnceODRLinkage()519 bool hasLinkOnceODRLinkage() const { 520 return isLinkOnceODRLinkage(getLinkage()); 521 } hasWeakLinkage()522 bool hasWeakLinkage() const { return isWeakLinkage(getLinkage()); } hasWeakAnyLinkage()523 bool hasWeakAnyLinkage() const { return isWeakAnyLinkage(getLinkage()); } hasWeakODRLinkage()524 bool hasWeakODRLinkage() const { return isWeakODRLinkage(getLinkage()); } hasAppendingLinkage()525 bool hasAppendingLinkage() const { return isAppendingLinkage(getLinkage()); } hasInternalLinkage()526 bool hasInternalLinkage() const { return isInternalLinkage(getLinkage()); } hasPrivateLinkage()527 bool hasPrivateLinkage() const { return isPrivateLinkage(getLinkage()); } hasLocalLinkage()528 bool hasLocalLinkage() const { return isLocalLinkage(getLinkage()); } hasExternalWeakLinkage()529 bool hasExternalWeakLinkage() const { 530 return isExternalWeakLinkage(getLinkage()); 531 } hasCommonLinkage()532 bool hasCommonLinkage() const { return isCommonLinkage(getLinkage()); } hasValidDeclarationLinkage()533 bool hasValidDeclarationLinkage() const { 534 return isValidDeclarationLinkage(getLinkage()); 535 } 536 setLinkage(LinkageTypes LT)537 void setLinkage(LinkageTypes LT) { 538 if (isLocalLinkage(LT)) { 539 Visibility = DefaultVisibility; 540 DllStorageClass = DefaultStorageClass; 541 } 542 Linkage = LT; 543 if (isImplicitDSOLocal()) 544 setDSOLocal(true); 545 } getLinkage()546 LinkageTypes getLinkage() const { return LinkageTypes(Linkage); } 547 isDiscardableIfUnused()548 bool isDiscardableIfUnused() const { 549 return isDiscardableIfUnused(getLinkage()); 550 } 551 isWeakForLinker()552 bool isWeakForLinker() const { return isWeakForLinker(getLinkage()); } 553 554 protected: 555 /// Copy all additional attributes (those not needed to create a GlobalValue) 556 /// from the GlobalValue Src to this one. 557 void copyAttributesFrom(const GlobalValue *Src); 558 559 public: 560 /// If the given string begins with the GlobalValue name mangling escape 561 /// character '\1', drop it. 562 /// 563 /// This function applies a specific mangling that is used in PGO profiles, 564 /// among other things. If you're trying to get a symbol name for an 565 /// arbitrary GlobalValue, this is not the function you're looking for; see 566 /// Mangler.h. dropLLVMManglingEscape(StringRef Name)567 static StringRef dropLLVMManglingEscape(StringRef Name) { 568 Name.consume_front("\1"); 569 return Name; 570 } 571 572 /// Return the modified name for a global value suitable to be 573 /// used as the key for a global lookup (e.g. profile or ThinLTO). 574 /// The value's original name is \c Name and has linkage of type 575 /// \c Linkage. The value is defined in module \c FileName. 576 static std::string getGlobalIdentifier(StringRef Name, 577 GlobalValue::LinkageTypes Linkage, 578 StringRef FileName); 579 580 /// Return the modified name for this global value suitable to be 581 /// used as the key for a global lookup (e.g. profile or ThinLTO). 582 std::string getGlobalIdentifier() const; 583 584 /// Declare a type to represent a global unique identifier for a global value. 585 /// This is a 64 bits hash that is used by PGO and ThinLTO to have a compact 586 /// unique way to identify a symbol. 587 using GUID = uint64_t; 588 589 /// Return a 64-bit global unique ID constructed from global value name 590 /// (i.e. returned by getGlobalIdentifier()). 591 static GUID getGUID(StringRef GlobalName); 592 593 /// Return a 64-bit global unique ID constructed from global value name 594 /// (i.e. returned by getGlobalIdentifier()). getGUID()595 GUID getGUID() const { return getGUID(getGlobalIdentifier()); } 596 597 /// @name Materialization 598 /// Materialization is used to construct functions only as they're needed. 599 /// This 600 /// is useful to reduce memory usage in LLVM or parsing work done by the 601 /// BitcodeReader to load the Module. 602 /// @{ 603 604 /// If this function's Module is being lazily streamed in functions from disk 605 /// or some other source, this method can be used to check to see if the 606 /// function has been read in yet or not. 607 bool isMaterializable() const; 608 609 /// Make sure this GlobalValue is fully read. 610 Error materialize(); 611 612 /// @} 613 614 /// Return true if the primary definition of this global value is outside of 615 /// the current translation unit. 616 bool isDeclaration() const; 617 isDeclarationForLinker()618 bool isDeclarationForLinker() const { 619 if (hasAvailableExternallyLinkage()) 620 return true; 621 622 return isDeclaration(); 623 } 624 625 /// Returns true if this global's definition will be the one chosen by the 626 /// linker. 627 /// 628 /// NB! Ideally this should not be used at the IR level at all. If you're 629 /// interested in optimization constraints implied by the linker's ability to 630 /// choose an implementation, prefer using \c hasExactDefinition. isStrongDefinitionForLinker()631 bool isStrongDefinitionForLinker() const { 632 return !(isDeclarationForLinker() || isWeakForLinker()); 633 } 634 635 const GlobalObject *getAliaseeObject() const; getAliaseeObject()636 GlobalObject *getAliaseeObject() { 637 return const_cast<GlobalObject *>( 638 static_cast<const GlobalValue *>(this)->getAliaseeObject()); 639 } 640 641 /// Returns whether this is a reference to an absolute symbol. 642 bool isAbsoluteSymbolRef() const; 643 644 /// If this is an absolute symbol reference, returns the range of the symbol, 645 /// otherwise returns std::nullopt. 646 std::optional<ConstantRange> getAbsoluteSymbolRange() const; 647 648 /// This method unlinks 'this' from the containing module, but does not delete 649 /// it. 650 void removeFromParent(); 651 652 /// This method unlinks 'this' from the containing module and deletes it. 653 void eraseFromParent(); 654 655 /// Get the module that this global value is contained inside of... getParent()656 Module *getParent() { return Parent; } getParent()657 const Module *getParent() const { return Parent; } 658 659 /// Get the data layout of the module this global belongs to. 660 /// 661 /// Requires the global to have a parent module. 662 const DataLayout &getDataLayout() const; 663 664 // Methods for support type inquiry through isa, cast, and dyn_cast: classof(const Value * V)665 static bool classof(const Value *V) { 666 return V->getValueID() == Value::FunctionVal || 667 V->getValueID() == Value::GlobalVariableVal || 668 V->getValueID() == Value::GlobalAliasVal || 669 V->getValueID() == Value::GlobalIFuncVal; 670 } 671 672 /// True if GV can be left out of the object symbol table. This is the case 673 /// for linkonce_odr values whose address is not significant. While legal, it 674 /// is not normally profitable to omit them from the .o symbol table. Using 675 /// this analysis makes sense when the information can be passed down to the 676 /// linker or we are in LTO. 677 bool canBeOmittedFromSymbolTable() const; 678 }; 679 680 } // end namespace llvm 681 682 #endif // LLVM_IR_GLOBALVALUE_H 683