Globals.cpp 20 KB

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