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