GlobalSplit.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. //===- GlobalSplit.cpp - global variable splitter -------------------------===//
  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 pass uses inrange annotations on GEP indices to split globals where
  10. // beneficial. Clang currently attaches these annotations to references to
  11. // virtual table globals under the Itanium ABI for the benefit of the
  12. // whole-program virtual call optimization and control flow integrity passes.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Transforms/IPO/GlobalSplit.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/StringExtras.h"
  18. #include "llvm/IR/Constant.h"
  19. #include "llvm/IR/Constants.h"
  20. #include "llvm/IR/DataLayout.h"
  21. #include "llvm/IR/Function.h"
  22. #include "llvm/IR/GlobalValue.h"
  23. #include "llvm/IR/GlobalVariable.h"
  24. #include "llvm/IR/Intrinsics.h"
  25. #include "llvm/IR/LLVMContext.h"
  26. #include "llvm/IR/Metadata.h"
  27. #include "llvm/IR/Module.h"
  28. #include "llvm/IR/Operator.h"
  29. #include "llvm/IR/Type.h"
  30. #include "llvm/IR/User.h"
  31. #include "llvm/InitializePasses.h"
  32. #include "llvm/Pass.h"
  33. #include "llvm/Support/Casting.h"
  34. #include "llvm/Transforms/IPO.h"
  35. #include <cstdint>
  36. #include <vector>
  37. using namespace llvm;
  38. static bool splitGlobal(GlobalVariable &GV) {
  39. // If the address of the global is taken outside of the module, we cannot
  40. // apply this transformation.
  41. if (!GV.hasLocalLinkage())
  42. return false;
  43. // We currently only know how to split ConstantStructs.
  44. auto *Init = dyn_cast_or_null<ConstantStruct>(GV.getInitializer());
  45. if (!Init)
  46. return false;
  47. // Verify that each user of the global is an inrange getelementptr constant.
  48. // From this it follows that any loads from or stores to that global must use
  49. // a pointer derived from an inrange getelementptr constant, which is
  50. // sufficient to allow us to apply the splitting transform.
  51. for (User *U : GV.users()) {
  52. if (!isa<Constant>(U))
  53. return false;
  54. auto *GEP = dyn_cast<GEPOperator>(U);
  55. if (!GEP || !GEP->getInRangeIndex() || *GEP->getInRangeIndex() != 1 ||
  56. !isa<ConstantInt>(GEP->getOperand(1)) ||
  57. !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
  58. !isa<ConstantInt>(GEP->getOperand(2)))
  59. return false;
  60. }
  61. SmallVector<MDNode *, 2> Types;
  62. GV.getMetadata(LLVMContext::MD_type, Types);
  63. const DataLayout &DL = GV.getParent()->getDataLayout();
  64. const StructLayout *SL = DL.getStructLayout(Init->getType());
  65. IntegerType *Int32Ty = Type::getInt32Ty(GV.getContext());
  66. std::vector<GlobalVariable *> SplitGlobals(Init->getNumOperands());
  67. for (unsigned I = 0; I != Init->getNumOperands(); ++I) {
  68. // Build a global representing this split piece.
  69. auto *SplitGV =
  70. new GlobalVariable(*GV.getParent(), Init->getOperand(I)->getType(),
  71. GV.isConstant(), GlobalValue::PrivateLinkage,
  72. Init->getOperand(I), GV.getName() + "." + utostr(I));
  73. SplitGlobals[I] = SplitGV;
  74. unsigned SplitBegin = SL->getElementOffset(I);
  75. unsigned SplitEnd = (I == Init->getNumOperands() - 1)
  76. ? SL->getSizeInBytes()
  77. : SL->getElementOffset(I + 1);
  78. // Rebuild type metadata, adjusting by the split offset.
  79. // FIXME: See if we can use DW_OP_piece to preserve debug metadata here.
  80. for (MDNode *Type : Types) {
  81. uint64_t ByteOffset = cast<ConstantInt>(
  82. cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
  83. ->getZExtValue();
  84. // Type metadata may be attached one byte after the end of the vtable, for
  85. // classes without virtual methods in Itanium ABI. AFAIK, it is never
  86. // attached to the first byte of a vtable. Subtract one to get the right
  87. // slice.
  88. // This is making an assumption that vtable groups are the only kinds of
  89. // global variables that !type metadata can be attached to, and that they
  90. // are either Itanium ABI vtable groups or contain a single vtable (i.e.
  91. // Microsoft ABI vtables).
  92. uint64_t AttachedTo = (ByteOffset == 0) ? ByteOffset : ByteOffset - 1;
  93. if (AttachedTo < SplitBegin || AttachedTo >= SplitEnd)
  94. continue;
  95. SplitGV->addMetadata(
  96. LLVMContext::MD_type,
  97. *MDNode::get(GV.getContext(),
  98. {ConstantAsMetadata::get(
  99. ConstantInt::get(Int32Ty, ByteOffset - SplitBegin)),
  100. Type->getOperand(1)}));
  101. }
  102. if (GV.hasMetadata(LLVMContext::MD_vcall_visibility))
  103. SplitGV->setVCallVisibilityMetadata(GV.getVCallVisibility());
  104. }
  105. for (User *U : GV.users()) {
  106. auto *GEP = cast<GEPOperator>(U);
  107. unsigned I = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
  108. if (I >= SplitGlobals.size())
  109. continue;
  110. SmallVector<Value *, 4> Ops;
  111. Ops.push_back(ConstantInt::get(Int32Ty, 0));
  112. for (unsigned I = 3; I != GEP->getNumOperands(); ++I)
  113. Ops.push_back(GEP->getOperand(I));
  114. auto *NewGEP = ConstantExpr::getGetElementPtr(
  115. SplitGlobals[I]->getInitializer()->getType(), SplitGlobals[I], Ops,
  116. GEP->isInBounds());
  117. GEP->replaceAllUsesWith(NewGEP);
  118. }
  119. // Finally, remove the original global. Any remaining uses refer to invalid
  120. // elements of the global, so replace with poison.
  121. if (!GV.use_empty())
  122. GV.replaceAllUsesWith(PoisonValue::get(GV.getType()));
  123. GV.eraseFromParent();
  124. return true;
  125. }
  126. static bool splitGlobals(Module &M) {
  127. // First, see if the module uses either of the llvm.type.test or
  128. // llvm.type.checked.load intrinsics, which indicates that splitting globals
  129. // may be beneficial.
  130. Function *TypeTestFunc =
  131. M.getFunction(Intrinsic::getName(Intrinsic::type_test));
  132. Function *TypeCheckedLoadFunc =
  133. M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
  134. if ((!TypeTestFunc || TypeTestFunc->use_empty()) &&
  135. (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
  136. return false;
  137. bool Changed = false;
  138. for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals()))
  139. Changed |= splitGlobal(GV);
  140. return Changed;
  141. }
  142. namespace {
  143. struct GlobalSplit : public ModulePass {
  144. static char ID;
  145. GlobalSplit() : ModulePass(ID) {
  146. initializeGlobalSplitPass(*PassRegistry::getPassRegistry());
  147. }
  148. bool runOnModule(Module &M) override {
  149. if (skipModule(M))
  150. return false;
  151. return splitGlobals(M);
  152. }
  153. };
  154. } // end anonymous namespace
  155. char GlobalSplit::ID = 0;
  156. INITIALIZE_PASS(GlobalSplit, "globalsplit", "Global splitter", false, false)
  157. ModulePass *llvm::createGlobalSplitPass() {
  158. return new GlobalSplit;
  159. }
  160. PreservedAnalyses GlobalSplitPass::run(Module &M, ModuleAnalysisManager &AM) {
  161. if (!splitGlobals(M))
  162. return PreservedAnalyses::all();
  163. return PreservedAnalyses::none();
  164. }