1 //===-- Globals.cpp - Implement the GlobalValue & GlobalVariable class ----===// 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 implements the GlobalValue & GlobalVariable classes for the IR 10 // library. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "LLVMContextImpl.h" 15 #include "llvm/ADT/Triple.h" 16 #include "llvm/IR/ConstantRange.h" 17 #include "llvm/IR/Constants.h" 18 #include "llvm/IR/DerivedTypes.h" 19 #include "llvm/IR/GlobalAlias.h" 20 #include "llvm/IR/GlobalValue.h" 21 #include "llvm/IR/GlobalVariable.h" 22 #include "llvm/IR/Module.h" 23 #include "llvm/Support/Error.h" 24 #include "llvm/Support/ErrorHandling.h" 25 using namespace llvm; 26 27 //===----------------------------------------------------------------------===// 28 // GlobalValue Class 29 //===----------------------------------------------------------------------===// 30 31 // GlobalValue should be a Constant, plus a type, a module, some flags, and an 32 // intrinsic ID. Add an assert to prevent people from accidentally growing 33 // GlobalValue while adding flags. 34 static_assert(sizeof(GlobalValue) == 35 sizeof(Constant) + 2 * sizeof(void *) + 2 * sizeof(unsigned), 36 "unexpected GlobalValue size growth"); 37 38 // GlobalObject adds a comdat. 39 static_assert(sizeof(GlobalObject) == sizeof(GlobalValue) + sizeof(void *), 40 "unexpected GlobalObject size growth"); 41 42 bool GlobalValue::isMaterializable() const { 43 if (const Function *F = dyn_cast<Function>(this)) 44 return F->isMaterializable(); 45 return false; 46 } 47 Error GlobalValue::materialize() { 48 return getParent()->materialize(this); 49 } 50 51 /// Override destroyConstantImpl to make sure it doesn't get called on 52 /// GlobalValue's because they shouldn't be treated like other constants. 53 void GlobalValue::destroyConstantImpl() { 54 llvm_unreachable("You can't GV->destroyConstantImpl()!"); 55 } 56 57 Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) { 58 llvm_unreachable("Unsupported class for handleOperandChange()!"); 59 } 60 61 /// copyAttributesFrom - copy all additional attributes (those not needed to 62 /// create a GlobalValue) from the GlobalValue Src to this one. 63 void GlobalValue::copyAttributesFrom(const GlobalValue *Src) { 64 setVisibility(Src->getVisibility()); 65 setUnnamedAddr(Src->getUnnamedAddr()); 66 setThreadLocalMode(Src->getThreadLocalMode()); 67 setDLLStorageClass(Src->getDLLStorageClass()); 68 setDSOLocal(Src->isDSOLocal()); 69 setPartition(Src->getPartition()); 70 if (Src->hasSanitizerMetadata()) 71 setSanitizerMetadata(Src->getSanitizerMetadata()); 72 else 73 removeSanitizerMetadata(); 74 } 75 76 void GlobalValue::removeFromParent() { 77 switch (getValueID()) { 78 #define HANDLE_GLOBAL_VALUE(NAME) \ 79 case Value::NAME##Val: \ 80 return static_cast<NAME *>(this)->removeFromParent(); 81 #include "llvm/IR/Value.def" 82 default: 83 break; 84 } 85 llvm_unreachable("not a global"); 86 } 87 88 void GlobalValue::eraseFromParent() { 89 switch (getValueID()) { 90 #define HANDLE_GLOBAL_VALUE(NAME) \ 91 case Value::NAME##Val: \ 92 return static_cast<NAME *>(this)->eraseFromParent(); 93 #include "llvm/IR/Value.def" 94 default: 95 break; 96 } 97 llvm_unreachable("not a global"); 98 } 99 100 GlobalObject::~GlobalObject() { setComdat(nullptr); } 101 102 bool GlobalValue::isInterposable() const { 103 if (isInterposableLinkage(getLinkage())) 104 return true; 105 return getParent() && getParent()->getSemanticInterposition() && 106 !isDSOLocal(); 107 } 108 109 bool GlobalValue::canBenefitFromLocalAlias() const { 110 // See AsmPrinter::getSymbolPreferLocal(). For a deduplicate comdat kind, 111 // references to a discarded local symbol from outside the group are not 112 // allowed, so avoid the local alias. 113 auto isDeduplicateComdat = [](const Comdat *C) { 114 return C && C->getSelectionKind() != Comdat::NoDeduplicate; 115 }; 116 return hasDefaultVisibility() && 117 GlobalObject::isExternalLinkage(getLinkage()) && !isDeclaration() && 118 !isa<GlobalIFunc>(this) && !isDeduplicateComdat(getComdat()); 119 } 120 121 unsigned GlobalValue::getAddressSpace() const { 122 PointerType *PtrTy = getType(); 123 return PtrTy->getAddressSpace(); 124 } 125 126 void GlobalObject::setAlignment(MaybeAlign Align) { 127 assert((!Align || *Align <= MaximumAlignment) && 128 "Alignment is greater than MaximumAlignment!"); 129 unsigned AlignmentData = encode(Align); 130 unsigned OldData = getGlobalValueSubClassData(); 131 setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData); 132 assert(MaybeAlign(getAlignment()) == Align && 133 "Alignment representation error!"); 134 } 135 136 void GlobalObject::copyAttributesFrom(const GlobalObject *Src) { 137 GlobalValue::copyAttributesFrom(Src); 138 setAlignment(Src->getAlign()); 139 setSection(Src->getSection()); 140 } 141 142 std::string GlobalValue::getGlobalIdentifier(StringRef Name, 143 GlobalValue::LinkageTypes Linkage, 144 StringRef FileName) { 145 146 // Value names may be prefixed with a binary '1' to indicate 147 // that the backend should not modify the symbols due to any platform 148 // naming convention. Do not include that '1' in the PGO profile name. 149 if (Name[0] == '\1') 150 Name = Name.substr(1); 151 152 std::string NewName = std::string(Name); 153 if (llvm::GlobalValue::isLocalLinkage(Linkage)) { 154 // For local symbols, prepend the main file name to distinguish them. 155 // Do not include the full path in the file name since there's no guarantee 156 // that it will stay the same, e.g., if the files are checked out from 157 // version control in different locations. 158 if (FileName.empty()) 159 NewName = NewName.insert(0, "<unknown>:"); 160 else 161 NewName = NewName.insert(0, FileName.str() + ":"); 162 } 163 return NewName; 164 } 165 166 std::string GlobalValue::getGlobalIdentifier() const { 167 return getGlobalIdentifier(getName(), getLinkage(), 168 getParent()->getSourceFileName()); 169 } 170 171 StringRef GlobalValue::getSection() const { 172 if (auto *GA = dyn_cast<GlobalAlias>(this)) { 173 // In general we cannot compute this at the IR level, but we try. 174 if (const GlobalObject *GO = GA->getAliaseeObject()) 175 return GO->getSection(); 176 return ""; 177 } 178 return cast<GlobalObject>(this)->getSection(); 179 } 180 181 const Comdat *GlobalValue::getComdat() const { 182 if (auto *GA = dyn_cast<GlobalAlias>(this)) { 183 // In general we cannot compute this at the IR level, but we try. 184 if (const GlobalObject *GO = GA->getAliaseeObject()) 185 return const_cast<GlobalObject *>(GO)->getComdat(); 186 return nullptr; 187 } 188 // ifunc and its resolver are separate things so don't use resolver comdat. 189 if (isa<GlobalIFunc>(this)) 190 return nullptr; 191 return cast<GlobalObject>(this)->getComdat(); 192 } 193 194 void GlobalObject::setComdat(Comdat *C) { 195 if (ObjComdat) 196 ObjComdat->removeUser(this); 197 ObjComdat = C; 198 if (C) 199 C->addUser(this); 200 } 201 202 StringRef GlobalValue::getPartition() const { 203 if (!hasPartition()) 204 return ""; 205 return getContext().pImpl->GlobalValuePartitions[this]; 206 } 207 208 void GlobalValue::setPartition(StringRef S) { 209 // Do nothing if we're clearing the partition and it is already empty. 210 if (!hasPartition() && S.empty()) 211 return; 212 213 // Get or create a stable partition name string and put it in the table in the 214 // context. 215 if (!S.empty()) 216 S = getContext().pImpl->Saver.save(S); 217 getContext().pImpl->GlobalValuePartitions[this] = S; 218 219 // Update the HasPartition field. Setting the partition to the empty string 220 // means this global no longer has a partition. 221 HasPartition = !S.empty(); 222 } 223 224 using SanitizerMetadata = GlobalValue::SanitizerMetadata; 225 const SanitizerMetadata &GlobalValue::getSanitizerMetadata() const { 226 assert(hasSanitizerMetadata()); 227 assert(getContext().pImpl->GlobalValueSanitizerMetadata.count(this)); 228 return getContext().pImpl->GlobalValueSanitizerMetadata[this]; 229 } 230 231 void GlobalValue::setSanitizerMetadata(SanitizerMetadata Meta) { 232 getContext().pImpl->GlobalValueSanitizerMetadata[this] = Meta; 233 HasSanitizerMetadata = true; 234 } 235 236 void GlobalValue::removeSanitizerMetadata() { 237 DenseMap<const GlobalValue *, SanitizerMetadata> &MetadataMap = 238 getContext().pImpl->GlobalValueSanitizerMetadata; 239 MetadataMap.erase(this); 240 HasSanitizerMetadata = false; 241 } 242 243 StringRef GlobalObject::getSectionImpl() const { 244 assert(hasSection()); 245 return getContext().pImpl->GlobalObjectSections[this]; 246 } 247 248 void GlobalObject::setSection(StringRef S) { 249 // Do nothing if we're clearing the section and it is already empty. 250 if (!hasSection() && S.empty()) 251 return; 252 253 // Get or create a stable section name string and put it in the table in the 254 // context. 255 if (!S.empty()) 256 S = getContext().pImpl->Saver.save(S); 257 getContext().pImpl->GlobalObjectSections[this] = S; 258 259 // Update the HasSectionHashEntryBit. Setting the section to the empty string 260 // means this global no longer has a section. 261 setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty()); 262 } 263 264 bool GlobalValue::isDeclaration() const { 265 // Globals are definitions if they have an initializer. 266 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) 267 return GV->getNumOperands() == 0; 268 269 // Functions are definitions if they have a body. 270 if (const Function *F = dyn_cast<Function>(this)) 271 return F->empty() && !F->isMaterializable(); 272 273 // Aliases and ifuncs are always definitions. 274 assert(isa<GlobalAlias>(this) || isa<GlobalIFunc>(this)); 275 return false; 276 } 277 278 bool GlobalObject::canIncreaseAlignment() const { 279 // Firstly, can only increase the alignment of a global if it 280 // is a strong definition. 281 if (!isStrongDefinitionForLinker()) 282 return false; 283 284 // It also has to either not have a section defined, or, not have 285 // alignment specified. (If it is assigned a section, the global 286 // could be densely packed with other objects in the section, and 287 // increasing the alignment could cause padding issues.) 288 if (hasSection() && getAlign()) 289 return false; 290 291 // On ELF platforms, we're further restricted in that we can't 292 // increase the alignment of any variable which might be emitted 293 // into a shared library, and which is exported. If the main 294 // executable accesses a variable found in a shared-lib, the main 295 // exe actually allocates memory for and exports the symbol ITSELF, 296 // overriding the symbol found in the library. That is, at link 297 // time, the observed alignment of the variable is copied into the 298 // executable binary. (A COPY relocation is also generated, to copy 299 // the initial data from the shadowed variable in the shared-lib 300 // into the location in the main binary, before running code.) 301 // 302 // And thus, even though you might think you are defining the 303 // global, and allocating the memory for the global in your object 304 // file, and thus should be able to set the alignment arbitrarily, 305 // that's not actually true. Doing so can cause an ABI breakage; an 306 // executable might have already been built with the previous 307 // alignment of the variable, and then assuming an increased 308 // alignment will be incorrect. 309 310 // Conservatively assume ELF if there's no parent pointer. 311 bool isELF = 312 (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF()); 313 if (isELF && !isDSOLocal()) 314 return false; 315 316 return true; 317 } 318 319 static const GlobalObject * 320 findBaseObject(const Constant *C, DenseSet<const GlobalAlias *> &Aliases) { 321 if (auto *GO = dyn_cast<GlobalObject>(C)) 322 return GO; 323 if (auto *GA = dyn_cast<GlobalAlias>(C)) 324 if (Aliases.insert(GA).second) 325 return findBaseObject(GA->getOperand(0), Aliases); 326 if (auto *CE = dyn_cast<ConstantExpr>(C)) { 327 switch (CE->getOpcode()) { 328 case Instruction::Add: { 329 auto *LHS = findBaseObject(CE->getOperand(0), Aliases); 330 auto *RHS = findBaseObject(CE->getOperand(1), Aliases); 331 if (LHS && RHS) 332 return nullptr; 333 return LHS ? LHS : RHS; 334 } 335 case Instruction::Sub: { 336 if (findBaseObject(CE->getOperand(1), Aliases)) 337 return nullptr; 338 return findBaseObject(CE->getOperand(0), Aliases); 339 } 340 case Instruction::IntToPtr: 341 case Instruction::PtrToInt: 342 case Instruction::BitCast: 343 case Instruction::GetElementPtr: 344 return findBaseObject(CE->getOperand(0), Aliases); 345 default: 346 break; 347 } 348 } 349 return nullptr; 350 } 351 352 const GlobalObject *GlobalValue::getAliaseeObject() const { 353 DenseSet<const GlobalAlias *> Aliases; 354 return findBaseObject(this, Aliases); 355 } 356 357 bool GlobalValue::isAbsoluteSymbolRef() const { 358 auto *GO = dyn_cast<GlobalObject>(this); 359 if (!GO) 360 return false; 361 362 return GO->getMetadata(LLVMContext::MD_absolute_symbol); 363 } 364 365 Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const { 366 auto *GO = dyn_cast<GlobalObject>(this); 367 if (!GO) 368 return None; 369 370 MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol); 371 if (!MD) 372 return None; 373 374 return getConstantRangeFromMetadata(*MD); 375 } 376 377 bool GlobalValue::canBeOmittedFromSymbolTable() const { 378 if (!hasLinkOnceODRLinkage()) 379 return false; 380 381 // We assume that anyone who sets global unnamed_addr on a non-constant 382 // knows what they're doing. 383 if (hasGlobalUnnamedAddr()) 384 return true; 385 386 // If it is a non constant variable, it needs to be uniqued across shared 387 // objects. 388 if (auto *Var = dyn_cast<GlobalVariable>(this)) 389 if (!Var->isConstant()) 390 return false; 391 392 return hasAtLeastLocalUnnamedAddr(); 393 } 394 395 //===----------------------------------------------------------------------===// 396 // GlobalVariable Implementation 397 //===----------------------------------------------------------------------===// 398 399 GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link, 400 Constant *InitVal, const Twine &Name, 401 ThreadLocalMode TLMode, unsigned AddressSpace, 402 bool isExternallyInitialized) 403 : GlobalObject(Ty, Value::GlobalVariableVal, 404 OperandTraits<GlobalVariable>::op_begin(this), 405 InitVal != nullptr, Link, Name, AddressSpace), 406 isConstantGlobal(constant), 407 isExternallyInitializedConstant(isExternallyInitialized) { 408 assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) && 409 "invalid type for global variable"); 410 setThreadLocalMode(TLMode); 411 if (InitVal) { 412 assert(InitVal->getType() == Ty && 413 "Initializer should be the same type as the GlobalVariable!"); 414 Op<0>() = InitVal; 415 } 416 } 417 418 GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant, 419 LinkageTypes Link, Constant *InitVal, 420 const Twine &Name, GlobalVariable *Before, 421 ThreadLocalMode TLMode, 422 Optional<unsigned> AddressSpace, 423 bool isExternallyInitialized) 424 : GlobalObject(Ty, Value::GlobalVariableVal, 425 OperandTraits<GlobalVariable>::op_begin(this), 426 InitVal != nullptr, Link, Name, 427 AddressSpace 428 ? *AddressSpace 429 : M.getDataLayout().getDefaultGlobalsAddressSpace()), 430 isConstantGlobal(constant), 431 isExternallyInitializedConstant(isExternallyInitialized) { 432 assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) && 433 "invalid type for global variable"); 434 setThreadLocalMode(TLMode); 435 if (InitVal) { 436 assert(InitVal->getType() == Ty && 437 "Initializer should be the same type as the GlobalVariable!"); 438 Op<0>() = InitVal; 439 } 440 441 if (Before) 442 Before->getParent()->getGlobalList().insert(Before->getIterator(), this); 443 else 444 M.getGlobalList().push_back(this); 445 } 446 447 void GlobalVariable::removeFromParent() { 448 getParent()->getGlobalList().remove(getIterator()); 449 } 450 451 void GlobalVariable::eraseFromParent() { 452 getParent()->getGlobalList().erase(getIterator()); 453 } 454 455 void GlobalVariable::setInitializer(Constant *InitVal) { 456 if (!InitVal) { 457 if (hasInitializer()) { 458 // Note, the num operands is used to compute the offset of the operand, so 459 // the order here matters. Clearing the operand then clearing the num 460 // operands ensures we have the correct offset to the operand. 461 Op<0>().set(nullptr); 462 setGlobalVariableNumOperands(0); 463 } 464 } else { 465 assert(InitVal->getType() == getValueType() && 466 "Initializer type must match GlobalVariable type"); 467 // Note, the num operands is used to compute the offset of the operand, so 468 // the order here matters. We need to set num operands to 1 first so that 469 // we get the correct offset to the first operand when we set it. 470 if (!hasInitializer()) 471 setGlobalVariableNumOperands(1); 472 Op<0>().set(InitVal); 473 } 474 } 475 476 /// Copy all additional attributes (those not needed to create a GlobalVariable) 477 /// from the GlobalVariable Src to this one. 478 void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) { 479 GlobalObject::copyAttributesFrom(Src); 480 setExternallyInitialized(Src->isExternallyInitialized()); 481 setAttributes(Src->getAttributes()); 482 } 483 484 void GlobalVariable::dropAllReferences() { 485 User::dropAllReferences(); 486 clearMetadata(); 487 } 488 489 //===----------------------------------------------------------------------===// 490 // GlobalAlias Implementation 491 //===----------------------------------------------------------------------===// 492 493 GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link, 494 const Twine &Name, Constant *Aliasee, 495 Module *ParentModule) 496 : GlobalValue(Ty, Value::GlobalAliasVal, &Op<0>(), 1, Link, Name, 497 AddressSpace) { 498 setAliasee(Aliasee); 499 if (ParentModule) 500 ParentModule->getAliasList().push_back(this); 501 } 502 503 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace, 504 LinkageTypes Link, const Twine &Name, 505 Constant *Aliasee, Module *ParentModule) { 506 return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule); 507 } 508 509 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace, 510 LinkageTypes Linkage, const Twine &Name, 511 Module *Parent) { 512 return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent); 513 } 514 515 GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace, 516 LinkageTypes Linkage, const Twine &Name, 517 GlobalValue *Aliasee) { 518 return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent()); 519 } 520 521 GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name, 522 GlobalValue *Aliasee) { 523 return create(Aliasee->getValueType(), Aliasee->getAddressSpace(), Link, Name, 524 Aliasee); 525 } 526 527 GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) { 528 return create(Aliasee->getLinkage(), Name, Aliasee); 529 } 530 531 void GlobalAlias::removeFromParent() { 532 getParent()->getAliasList().remove(getIterator()); 533 } 534 535 void GlobalAlias::eraseFromParent() { 536 getParent()->getAliasList().erase(getIterator()); 537 } 538 539 void GlobalAlias::setAliasee(Constant *Aliasee) { 540 assert((!Aliasee || Aliasee->getType() == getType()) && 541 "Alias and aliasee types should match!"); 542 Op<0>().set(Aliasee); 543 } 544 545 const GlobalObject *GlobalAlias::getAliaseeObject() const { 546 DenseSet<const GlobalAlias *> Aliases; 547 return findBaseObject(getOperand(0), Aliases); 548 } 549 550 //===----------------------------------------------------------------------===// 551 // GlobalIFunc Implementation 552 //===----------------------------------------------------------------------===// 553 554 GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link, 555 const Twine &Name, Constant *Resolver, 556 Module *ParentModule) 557 : GlobalObject(Ty, Value::GlobalIFuncVal, &Op<0>(), 1, Link, Name, 558 AddressSpace) { 559 setResolver(Resolver); 560 if (ParentModule) 561 ParentModule->getIFuncList().push_back(this); 562 } 563 564 GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace, 565 LinkageTypes Link, const Twine &Name, 566 Constant *Resolver, Module *ParentModule) { 567 return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule); 568 } 569 570 void GlobalIFunc::removeFromParent() { 571 getParent()->getIFuncList().remove(getIterator()); 572 } 573 574 void GlobalIFunc::eraseFromParent() { 575 getParent()->getIFuncList().erase(getIterator()); 576 } 577 578 const Function *GlobalIFunc::getResolverFunction() const { 579 DenseSet<const GlobalAlias *> Aliases; 580 return dyn_cast<Function>(findBaseObject(getResolver(), Aliases)); 581 } 582