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