LowerBitSets.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. //===-- LowerBitSets.cpp - Bitset lowering pass ---------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass lowers bitset metadata and calls to the llvm.bitset.test intrinsic.
  11. // See http://llvm.org/docs/LangRef.html#bitsets for more information.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/IPO/LowerBitSets.h"
  15. #include "llvm/Transforms/IPO.h"
  16. #include "llvm/ADT/EquivalenceClasses.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/ADT/Triple.h"
  19. #include "llvm/IR/Constant.h"
  20. #include "llvm/IR/Constants.h"
  21. #include "llvm/IR/GlobalVariable.h"
  22. #include "llvm/IR/IRBuilder.h"
  23. #include "llvm/IR/Instructions.h"
  24. #include "llvm/IR/Intrinsics.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/IR/Operator.h"
  27. #include "llvm/Pass.h"
  28. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  29. using namespace llvm;
  30. #define DEBUG_TYPE "lowerbitsets"
  31. STATISTIC(ByteArraySizeBits, "Byte array size in bits");
  32. STATISTIC(ByteArraySizeBytes, "Byte array size in bytes");
  33. STATISTIC(NumByteArraysCreated, "Number of byte arrays created");
  34. STATISTIC(NumBitSetCallsLowered, "Number of bitset calls lowered");
  35. STATISTIC(NumBitSetDisjointSets, "Number of disjoint sets of bitsets");
  36. #if 0 // HLSL Change
  37. static cl::opt<bool> AvoidReuse(
  38. "lowerbitsets-avoid-reuse",
  39. cl::desc("Try to avoid reuse of byte array addresses using aliases"),
  40. cl::Hidden, cl::init(true));
  41. #else
  42. static bool AvoidReuse = true;
  43. #endif
  44. bool BitSetInfo::containsGlobalOffset(uint64_t Offset) const {
  45. if (Offset < ByteOffset)
  46. return false;
  47. if ((Offset - ByteOffset) % (uint64_t(1) << AlignLog2) != 0)
  48. return false;
  49. uint64_t BitOffset = (Offset - ByteOffset) >> AlignLog2;
  50. if (BitOffset >= BitSize)
  51. return false;
  52. return Bits.count(BitOffset);
  53. }
  54. bool BitSetInfo::containsValue(
  55. const DataLayout &DL,
  56. const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout, Value *V,
  57. uint64_t COffset) const {
  58. if (auto GV = dyn_cast<GlobalVariable>(V)) {
  59. auto I = GlobalLayout.find(GV);
  60. if (I == GlobalLayout.end())
  61. return false;
  62. return containsGlobalOffset(I->second + COffset);
  63. }
  64. if (auto GEP = dyn_cast<GEPOperator>(V)) {
  65. APInt APOffset(DL.getPointerSizeInBits(0), 0);
  66. bool Result = GEP->accumulateConstantOffset(DL, APOffset);
  67. if (!Result)
  68. return false;
  69. COffset += APOffset.getZExtValue();
  70. return containsValue(DL, GlobalLayout, GEP->getPointerOperand(),
  71. COffset);
  72. }
  73. if (auto Op = dyn_cast<Operator>(V)) {
  74. if (Op->getOpcode() == Instruction::BitCast)
  75. return containsValue(DL, GlobalLayout, Op->getOperand(0), COffset);
  76. if (Op->getOpcode() == Instruction::Select)
  77. return containsValue(DL, GlobalLayout, Op->getOperand(1), COffset) &&
  78. containsValue(DL, GlobalLayout, Op->getOperand(2), COffset);
  79. }
  80. return false;
  81. }
  82. BitSetInfo BitSetBuilder::build() {
  83. if (Min > Max)
  84. Min = 0;
  85. // Normalize each offset against the minimum observed offset, and compute
  86. // the bitwise OR of each of the offsets. The number of trailing zeros
  87. // in the mask gives us the log2 of the alignment of all offsets, which
  88. // allows us to compress the bitset by only storing one bit per aligned
  89. // address.
  90. uint64_t Mask = 0;
  91. for (uint64_t &Offset : Offsets) {
  92. Offset -= Min;
  93. Mask |= Offset;
  94. }
  95. BitSetInfo BSI;
  96. BSI.ByteOffset = Min;
  97. BSI.AlignLog2 = 0;
  98. if (Mask != 0)
  99. BSI.AlignLog2 = countTrailingZeros(Mask, ZB_Undefined);
  100. // Build the compressed bitset while normalizing the offsets against the
  101. // computed alignment.
  102. BSI.BitSize = ((Max - Min) >> BSI.AlignLog2) + 1;
  103. for (uint64_t Offset : Offsets) {
  104. Offset >>= BSI.AlignLog2;
  105. BSI.Bits.insert(Offset);
  106. }
  107. return BSI;
  108. }
  109. void GlobalLayoutBuilder::addFragment(const std::set<uint64_t> &F) {
  110. // Create a new fragment to hold the layout for F.
  111. Fragments.emplace_back();
  112. std::vector<uint64_t> &Fragment = Fragments.back();
  113. uint64_t FragmentIndex = Fragments.size() - 1;
  114. for (auto ObjIndex : F) {
  115. uint64_t OldFragmentIndex = FragmentMap[ObjIndex];
  116. if (OldFragmentIndex == 0) {
  117. // We haven't seen this object index before, so just add it to the current
  118. // fragment.
  119. Fragment.push_back(ObjIndex);
  120. } else {
  121. // This index belongs to an existing fragment. Copy the elements of the
  122. // old fragment into this one and clear the old fragment. We don't update
  123. // the fragment map just yet, this ensures that any further references to
  124. // indices from the old fragment in this fragment do not insert any more
  125. // indices.
  126. std::vector<uint64_t> &OldFragment = Fragments[OldFragmentIndex];
  127. Fragment.insert(Fragment.end(), OldFragment.begin(), OldFragment.end());
  128. OldFragment.clear();
  129. }
  130. }
  131. // Update the fragment map to point our object indices to this fragment.
  132. for (uint64_t ObjIndex : Fragment)
  133. FragmentMap[ObjIndex] = FragmentIndex;
  134. }
  135. void ByteArrayBuilder::allocate(const std::set<uint64_t> &Bits,
  136. uint64_t BitSize, uint64_t &AllocByteOffset,
  137. uint8_t &AllocMask) {
  138. // Find the smallest current allocation.
  139. unsigned Bit = 0;
  140. for (unsigned I = 1; I != BitsPerByte; ++I)
  141. if (BitAllocs[I] < BitAllocs[Bit])
  142. Bit = I;
  143. AllocByteOffset = BitAllocs[Bit];
  144. // Add our size to it.
  145. unsigned ReqSize = AllocByteOffset + BitSize;
  146. BitAllocs[Bit] = ReqSize;
  147. if (Bytes.size() < ReqSize)
  148. Bytes.resize(ReqSize);
  149. // Set our bits.
  150. AllocMask = 1 << Bit;
  151. for (uint64_t B : Bits)
  152. Bytes[AllocByteOffset + B] |= AllocMask;
  153. }
  154. namespace {
  155. struct ByteArrayInfo {
  156. std::set<uint64_t> Bits;
  157. uint64_t BitSize;
  158. GlobalVariable *ByteArray;
  159. Constant *Mask;
  160. };
  161. struct LowerBitSets : public ModulePass {
  162. static char ID;
  163. LowerBitSets() : ModulePass(ID) {
  164. initializeLowerBitSetsPass(*PassRegistry::getPassRegistry());
  165. }
  166. Module *M;
  167. bool LinkerSubsectionsViaSymbols;
  168. IntegerType *Int1Ty;
  169. IntegerType *Int8Ty;
  170. IntegerType *Int32Ty;
  171. Type *Int32PtrTy;
  172. IntegerType *Int64Ty;
  173. Type *IntPtrTy;
  174. // The llvm.bitsets named metadata.
  175. NamedMDNode *BitSetNM;
  176. // Mapping from bitset mdstrings to the call sites that test them.
  177. DenseMap<MDString *, std::vector<CallInst *>> BitSetTestCallSites;
  178. std::vector<ByteArrayInfo> ByteArrayInfos;
  179. BitSetInfo
  180. buildBitSet(MDString *BitSet,
  181. const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
  182. ByteArrayInfo *createByteArray(BitSetInfo &BSI);
  183. void allocateByteArrays();
  184. Value *createBitSetTest(IRBuilder<> &B, BitSetInfo &BSI, ByteArrayInfo *&BAI,
  185. Value *BitOffset);
  186. Value *
  187. lowerBitSetCall(CallInst *CI, BitSetInfo &BSI, ByteArrayInfo *&BAI,
  188. GlobalVariable *CombinedGlobal,
  189. const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
  190. void buildBitSetsFromGlobals(const std::vector<MDString *> &BitSets,
  191. const std::vector<GlobalVariable *> &Globals);
  192. bool buildBitSets();
  193. bool eraseBitSetMetadata();
  194. bool doInitialization(Module &M) override;
  195. bool runOnModule(Module &M) override;
  196. };
  197. } // namespace
  198. INITIALIZE_PASS_BEGIN(LowerBitSets, "lowerbitsets",
  199. "Lower bitset metadata", false, false)
  200. INITIALIZE_PASS_END(LowerBitSets, "lowerbitsets",
  201. "Lower bitset metadata", false, false)
  202. char LowerBitSets::ID = 0;
  203. ModulePass *llvm::createLowerBitSetsPass() { return new LowerBitSets; }
  204. bool LowerBitSets::doInitialization(Module &Mod) {
  205. M = &Mod;
  206. const DataLayout &DL = Mod.getDataLayout();
  207. Triple TargetTriple(M->getTargetTriple());
  208. LinkerSubsectionsViaSymbols = TargetTriple.isMacOSX();
  209. Int1Ty = Type::getInt1Ty(M->getContext());
  210. Int8Ty = Type::getInt8Ty(M->getContext());
  211. Int32Ty = Type::getInt32Ty(M->getContext());
  212. Int32PtrTy = PointerType::getUnqual(Int32Ty);
  213. Int64Ty = Type::getInt64Ty(M->getContext());
  214. IntPtrTy = DL.getIntPtrType(M->getContext(), 0);
  215. BitSetNM = M->getNamedMetadata("llvm.bitsets");
  216. BitSetTestCallSites.clear();
  217. return false;
  218. }
  219. /// Build a bit set for BitSet using the object layouts in
  220. /// GlobalLayout.
  221. BitSetInfo LowerBitSets::buildBitSet(
  222. MDString *BitSet,
  223. const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
  224. BitSetBuilder BSB;
  225. // Compute the byte offset of each element of this bitset.
  226. if (BitSetNM) {
  227. for (MDNode *Op : BitSetNM->operands()) {
  228. if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
  229. continue;
  230. auto OpGlobal = dyn_cast<GlobalVariable>(
  231. cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
  232. if (!OpGlobal)
  233. continue;
  234. uint64_t Offset =
  235. cast<ConstantInt>(cast<ConstantAsMetadata>(Op->getOperand(2))
  236. ->getValue())->getZExtValue();
  237. Offset += GlobalLayout.find(OpGlobal)->second;
  238. BSB.addOffset(Offset);
  239. }
  240. }
  241. return BSB.build();
  242. }
  243. /// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
  244. /// Bits. This pattern matches to the bt instruction on x86.
  245. static Value *createMaskedBitTest(IRBuilder<> &B, Value *Bits,
  246. Value *BitOffset) {
  247. auto BitsType = cast<IntegerType>(Bits->getType());
  248. unsigned BitWidth = BitsType->getBitWidth();
  249. BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
  250. Value *BitIndex =
  251. B.CreateAnd(BitOffset, ConstantInt::get(BitsType, BitWidth - 1));
  252. Value *BitMask = B.CreateShl(ConstantInt::get(BitsType, 1), BitIndex);
  253. Value *MaskedBits = B.CreateAnd(Bits, BitMask);
  254. return B.CreateICmpNE(MaskedBits, ConstantInt::get(BitsType, 0));
  255. }
  256. ByteArrayInfo *LowerBitSets::createByteArray(BitSetInfo &BSI) {
  257. // Create globals to stand in for byte arrays and masks. These never actually
  258. // get initialized, we RAUW and erase them later in allocateByteArrays() once
  259. // we know the offset and mask to use.
  260. auto ByteArrayGlobal = new GlobalVariable(
  261. *M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
  262. auto MaskGlobal = new GlobalVariable(
  263. *M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
  264. ByteArrayInfos.emplace_back();
  265. ByteArrayInfo *BAI = &ByteArrayInfos.back();
  266. BAI->Bits = BSI.Bits;
  267. BAI->BitSize = BSI.BitSize;
  268. BAI->ByteArray = ByteArrayGlobal;
  269. BAI->Mask = ConstantExpr::getPtrToInt(MaskGlobal, Int8Ty);
  270. return BAI;
  271. }
  272. void LowerBitSets::allocateByteArrays() {
  273. std::stable_sort(ByteArrayInfos.begin(), ByteArrayInfos.end(),
  274. [](const ByteArrayInfo &BAI1, const ByteArrayInfo &BAI2) {
  275. return BAI1.BitSize > BAI2.BitSize;
  276. });
  277. std::vector<uint64_t> ByteArrayOffsets(ByteArrayInfos.size());
  278. ByteArrayBuilder BAB;
  279. for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
  280. ByteArrayInfo *BAI = &ByteArrayInfos[I];
  281. uint8_t Mask;
  282. BAB.allocate(BAI->Bits, BAI->BitSize, ByteArrayOffsets[I], Mask);
  283. BAI->Mask->replaceAllUsesWith(ConstantInt::get(Int8Ty, Mask));
  284. cast<GlobalVariable>(BAI->Mask->getOperand(0))->eraseFromParent();
  285. }
  286. Constant *ByteArrayConst = ConstantDataArray::get(M->getContext(), BAB.Bytes);
  287. auto ByteArray =
  288. new GlobalVariable(*M, ByteArrayConst->getType(), /*isConstant=*/true,
  289. GlobalValue::PrivateLinkage, ByteArrayConst);
  290. for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
  291. ByteArrayInfo *BAI = &ByteArrayInfos[I];
  292. Constant *Idxs[] = {ConstantInt::get(IntPtrTy, 0),
  293. ConstantInt::get(IntPtrTy, ByteArrayOffsets[I])};
  294. Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(
  295. ByteArrayConst->getType(), ByteArray, Idxs);
  296. // Create an alias instead of RAUW'ing the gep directly. On x86 this ensures
  297. // that the pc-relative displacement is folded into the lea instead of the
  298. // test instruction getting another displacement.
  299. if (LinkerSubsectionsViaSymbols) {
  300. BAI->ByteArray->replaceAllUsesWith(GEP);
  301. } else {
  302. GlobalAlias *Alias =
  303. GlobalAlias::create(PointerType::getUnqual(Int8Ty),
  304. GlobalValue::PrivateLinkage, "bits", GEP, M);
  305. BAI->ByteArray->replaceAllUsesWith(Alias);
  306. }
  307. BAI->ByteArray->eraseFromParent();
  308. }
  309. ByteArraySizeBits = BAB.BitAllocs[0] + BAB.BitAllocs[1] + BAB.BitAllocs[2] +
  310. BAB.BitAllocs[3] + BAB.BitAllocs[4] + BAB.BitAllocs[5] +
  311. BAB.BitAllocs[6] + BAB.BitAllocs[7];
  312. ByteArraySizeBytes = BAB.Bytes.size();
  313. }
  314. /// Build a test that bit BitOffset is set in BSI, where
  315. /// BitSetGlobal is a global containing the bits in BSI.
  316. Value *LowerBitSets::createBitSetTest(IRBuilder<> &B, BitSetInfo &BSI,
  317. ByteArrayInfo *&BAI, Value *BitOffset) {
  318. if (BSI.BitSize <= 64) {
  319. // If the bit set is sufficiently small, we can avoid a load by bit testing
  320. // a constant.
  321. IntegerType *BitsTy;
  322. if (BSI.BitSize <= 32)
  323. BitsTy = Int32Ty;
  324. else
  325. BitsTy = Int64Ty;
  326. uint64_t Bits = 0;
  327. for (auto Bit : BSI.Bits)
  328. Bits |= uint64_t(1) << Bit;
  329. Constant *BitsConst = ConstantInt::get(BitsTy, Bits);
  330. return createMaskedBitTest(B, BitsConst, BitOffset);
  331. } else {
  332. if (!BAI) {
  333. ++NumByteArraysCreated;
  334. BAI = createByteArray(BSI);
  335. }
  336. Constant *ByteArray = BAI->ByteArray;
  337. Type *Ty = BAI->ByteArray->getValueType();
  338. if (!LinkerSubsectionsViaSymbols && AvoidReuse) {
  339. // Each use of the byte array uses a different alias. This makes the
  340. // backend less likely to reuse previously computed byte array addresses,
  341. // improving the security of the CFI mechanism based on this pass.
  342. ByteArray = GlobalAlias::create(BAI->ByteArray->getType(),
  343. GlobalValue::PrivateLinkage, "bits_use",
  344. ByteArray, M);
  345. }
  346. Value *ByteAddr = B.CreateGEP(Ty, ByteArray, BitOffset);
  347. Value *Byte = B.CreateLoad(ByteAddr);
  348. Value *ByteAndMask = B.CreateAnd(Byte, BAI->Mask);
  349. return B.CreateICmpNE(ByteAndMask, ConstantInt::get(Int8Ty, 0));
  350. }
  351. }
  352. /// Lower a llvm.bitset.test call to its implementation. Returns the value to
  353. /// replace the call with.
  354. Value *LowerBitSets::lowerBitSetCall(
  355. CallInst *CI, BitSetInfo &BSI, ByteArrayInfo *&BAI,
  356. GlobalVariable *CombinedGlobal,
  357. const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
  358. Value *Ptr = CI->getArgOperand(0);
  359. const DataLayout &DL = M->getDataLayout();
  360. if (BSI.containsValue(DL, GlobalLayout, Ptr))
  361. return ConstantInt::getTrue(CombinedGlobal->getParent()->getContext());
  362. Constant *GlobalAsInt = ConstantExpr::getPtrToInt(CombinedGlobal, IntPtrTy);
  363. Constant *OffsetedGlobalAsInt = ConstantExpr::getAdd(
  364. GlobalAsInt, ConstantInt::get(IntPtrTy, BSI.ByteOffset));
  365. BasicBlock *InitialBB = CI->getParent();
  366. IRBuilder<> B(CI);
  367. Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
  368. if (BSI.isSingleOffset())
  369. return B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
  370. Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
  371. Value *BitOffset;
  372. if (BSI.AlignLog2 == 0) {
  373. BitOffset = PtrOffset;
  374. } else {
  375. // We need to check that the offset both falls within our range and is
  376. // suitably aligned. We can check both properties at the same time by
  377. // performing a right rotate by log2(alignment) followed by an integer
  378. // comparison against the bitset size. The rotate will move the lower
  379. // order bits that need to be zero into the higher order bits of the
  380. // result, causing the comparison to fail if they are nonzero. The rotate
  381. // also conveniently gives us a bit offset to use during the load from
  382. // the bitset.
  383. Value *OffsetSHR =
  384. B.CreateLShr(PtrOffset, ConstantInt::get(IntPtrTy, BSI.AlignLog2));
  385. Value *OffsetSHL = B.CreateShl(
  386. PtrOffset,
  387. ConstantInt::get(IntPtrTy, DL.getPointerSizeInBits(0) - BSI.AlignLog2));
  388. BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
  389. }
  390. Constant *BitSizeConst = ConstantInt::get(IntPtrTy, BSI.BitSize);
  391. Value *OffsetInRange = B.CreateICmpULT(BitOffset, BitSizeConst);
  392. // If the bit set is all ones, testing against it is unnecessary.
  393. if (BSI.isAllOnes())
  394. return OffsetInRange;
  395. TerminatorInst *Term = SplitBlockAndInsertIfThen(OffsetInRange, CI, false);
  396. IRBuilder<> ThenB(Term);
  397. // Now that we know that the offset is in range and aligned, load the
  398. // appropriate bit from the bitset.
  399. Value *Bit = createBitSetTest(ThenB, BSI, BAI, BitOffset);
  400. // The value we want is 0 if we came directly from the initial block
  401. // (having failed the range or alignment checks), or the loaded bit if
  402. // we came from the block in which we loaded it.
  403. B.SetInsertPoint(CI);
  404. PHINode *P = B.CreatePHI(Int1Ty, 2);
  405. P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
  406. P->addIncoming(Bit, ThenB.GetInsertBlock());
  407. return P;
  408. }
  409. /// Given a disjoint set of bitsets and globals, layout the globals, build the
  410. /// bit sets and lower the llvm.bitset.test calls.
  411. void LowerBitSets::buildBitSetsFromGlobals(
  412. const std::vector<MDString *> &BitSets,
  413. const std::vector<GlobalVariable *> &Globals) {
  414. // Build a new global with the combined contents of the referenced globals.
  415. std::vector<Constant *> GlobalInits;
  416. const DataLayout &DL = M->getDataLayout();
  417. for (GlobalVariable *G : Globals) {
  418. GlobalInits.push_back(G->getInitializer());
  419. uint64_t InitSize = DL.getTypeAllocSize(G->getInitializer()->getType());
  420. // Compute the amount of padding required to align the next element to the
  421. // next power of 2.
  422. uint64_t Padding = NextPowerOf2(InitSize - 1) - InitSize;
  423. // Cap at 128 was found experimentally to have a good data/instruction
  424. // overhead tradeoff.
  425. if (Padding > 128)
  426. Padding = RoundUpToAlignment(InitSize, 128) - InitSize;
  427. GlobalInits.push_back(
  428. ConstantAggregateZero::get(ArrayType::get(Int8Ty, Padding)));
  429. }
  430. if (!GlobalInits.empty())
  431. GlobalInits.pop_back();
  432. Constant *NewInit = ConstantStruct::getAnon(M->getContext(), GlobalInits);
  433. auto CombinedGlobal =
  434. new GlobalVariable(*M, NewInit->getType(), /*isConstant=*/true,
  435. GlobalValue::PrivateLinkage, NewInit);
  436. const StructLayout *CombinedGlobalLayout =
  437. DL.getStructLayout(cast<StructType>(NewInit->getType()));
  438. // Compute the offsets of the original globals within the new global.
  439. DenseMap<GlobalVariable *, uint64_t> GlobalLayout;
  440. for (unsigned I = 0; I != Globals.size(); ++I)
  441. // Multiply by 2 to account for padding elements.
  442. GlobalLayout[Globals[I]] = CombinedGlobalLayout->getElementOffset(I * 2);
  443. // For each bitset in this disjoint set...
  444. for (MDString *BS : BitSets) {
  445. // Build the bitset.
  446. BitSetInfo BSI = buildBitSet(BS, GlobalLayout);
  447. ByteArrayInfo *BAI = 0;
  448. // Lower each call to llvm.bitset.test for this bitset.
  449. for (CallInst *CI : BitSetTestCallSites[BS]) {
  450. ++NumBitSetCallsLowered;
  451. Value *Lowered = lowerBitSetCall(CI, BSI, BAI, CombinedGlobal, GlobalLayout);
  452. CI->replaceAllUsesWith(Lowered);
  453. CI->eraseFromParent();
  454. }
  455. }
  456. // Build aliases pointing to offsets into the combined global for each
  457. // global from which we built the combined global, and replace references
  458. // to the original globals with references to the aliases.
  459. for (unsigned I = 0; I != Globals.size(); ++I) {
  460. // Multiply by 2 to account for padding elements.
  461. Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
  462. ConstantInt::get(Int32Ty, I * 2)};
  463. Constant *CombinedGlobalElemPtr = ConstantExpr::getGetElementPtr(
  464. NewInit->getType(), CombinedGlobal, CombinedGlobalIdxs);
  465. if (LinkerSubsectionsViaSymbols) {
  466. Globals[I]->replaceAllUsesWith(CombinedGlobalElemPtr);
  467. } else {
  468. GlobalAlias *GAlias =
  469. GlobalAlias::create(Globals[I]->getType(), Globals[I]->getLinkage(),
  470. "", CombinedGlobalElemPtr, M);
  471. GAlias->takeName(Globals[I]);
  472. Globals[I]->replaceAllUsesWith(GAlias);
  473. }
  474. Globals[I]->eraseFromParent();
  475. }
  476. }
  477. /// Lower all bit sets in this module.
  478. bool LowerBitSets::buildBitSets() {
  479. Function *BitSetTestFunc =
  480. M->getFunction(Intrinsic::getName(Intrinsic::bitset_test));
  481. if (!BitSetTestFunc)
  482. return false;
  483. // Equivalence class set containing bitsets and the globals they reference.
  484. // This is used to partition the set of bitsets in the module into disjoint
  485. // sets.
  486. typedef EquivalenceClasses<PointerUnion<GlobalVariable *, MDString *>>
  487. GlobalClassesTy;
  488. GlobalClassesTy GlobalClasses;
  489. for (const Use &U : BitSetTestFunc->uses()) {
  490. auto CI = cast<CallInst>(U.getUser());
  491. auto BitSetMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
  492. if (!BitSetMDVal || !isa<MDString>(BitSetMDVal->getMetadata()))
  493. report_fatal_error(
  494. "Second argument of llvm.bitset.test must be metadata string");
  495. auto BitSet = cast<MDString>(BitSetMDVal->getMetadata());
  496. // Add the call site to the list of call sites for this bit set. We also use
  497. // BitSetTestCallSites to keep track of whether we have seen this bit set
  498. // before. If we have, we don't need to re-add the referenced globals to the
  499. // equivalence class.
  500. std::pair<DenseMap<MDString *, std::vector<CallInst *>>::iterator,
  501. bool> Ins =
  502. BitSetTestCallSites.insert(
  503. std::make_pair(BitSet, std::vector<CallInst *>()));
  504. Ins.first->second.push_back(CI);
  505. if (!Ins.second)
  506. continue;
  507. // Add the bitset to the equivalence class.
  508. GlobalClassesTy::iterator GCI = GlobalClasses.insert(BitSet);
  509. GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
  510. if (!BitSetNM)
  511. continue;
  512. // Verify the bitset metadata and add the referenced globals to the bitset's
  513. // equivalence class.
  514. for (MDNode *Op : BitSetNM->operands()) {
  515. if (Op->getNumOperands() != 3)
  516. report_fatal_error(
  517. "All operands of llvm.bitsets metadata must have 3 elements");
  518. if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
  519. continue;
  520. auto OpConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(1));
  521. if (!OpConstMD)
  522. report_fatal_error("Bit set element must be a constant");
  523. auto OpGlobal = dyn_cast<GlobalVariable>(OpConstMD->getValue());
  524. if (!OpGlobal)
  525. continue;
  526. auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(2));
  527. if (!OffsetConstMD)
  528. report_fatal_error("Bit set element offset must be a constant");
  529. auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
  530. if (!OffsetInt)
  531. report_fatal_error(
  532. "Bit set element offset must be an integer constant");
  533. CurSet = GlobalClasses.unionSets(
  534. CurSet, GlobalClasses.findLeader(GlobalClasses.insert(OpGlobal)));
  535. }
  536. }
  537. if (GlobalClasses.empty())
  538. return false;
  539. // For each disjoint set we found...
  540. for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
  541. E = GlobalClasses.end();
  542. I != E; ++I) {
  543. if (!I->isLeader()) continue;
  544. ++NumBitSetDisjointSets;
  545. // Build the list of bitsets and referenced globals in this disjoint set.
  546. std::vector<MDString *> BitSets;
  547. std::vector<GlobalVariable *> Globals;
  548. llvm::DenseMap<MDString *, uint64_t> BitSetIndices;
  549. llvm::DenseMap<GlobalVariable *, uint64_t> GlobalIndices;
  550. for (GlobalClassesTy::member_iterator MI = GlobalClasses.member_begin(I);
  551. MI != GlobalClasses.member_end(); ++MI) {
  552. if ((*MI).is<MDString *>()) {
  553. BitSetIndices[MI->get<MDString *>()] = BitSets.size();
  554. BitSets.push_back(MI->get<MDString *>());
  555. } else {
  556. GlobalIndices[MI->get<GlobalVariable *>()] = Globals.size();
  557. Globals.push_back(MI->get<GlobalVariable *>());
  558. }
  559. }
  560. // For each bitset, build a set of indices that refer to globals referenced
  561. // by the bitset.
  562. std::vector<std::set<uint64_t>> BitSetMembers(BitSets.size());
  563. if (BitSetNM) {
  564. for (MDNode *Op : BitSetNM->operands()) {
  565. // Op = { bitset name, global, offset }
  566. if (!Op->getOperand(1))
  567. continue;
  568. auto I = BitSetIndices.find(cast<MDString>(Op->getOperand(0)));
  569. if (I == BitSetIndices.end())
  570. continue;
  571. auto OpGlobal = dyn_cast<GlobalVariable>(
  572. cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
  573. if (!OpGlobal)
  574. continue;
  575. BitSetMembers[I->second].insert(GlobalIndices[OpGlobal]);
  576. }
  577. }
  578. // Order the sets of indices by size. The GlobalLayoutBuilder works best
  579. // when given small index sets first.
  580. std::stable_sort(
  581. BitSetMembers.begin(), BitSetMembers.end(),
  582. [](const std::set<uint64_t> &O1, const std::set<uint64_t> &O2) {
  583. return O1.size() < O2.size();
  584. });
  585. // Create a GlobalLayoutBuilder and provide it with index sets as layout
  586. // fragments. The GlobalLayoutBuilder tries to lay out members of fragments
  587. // as close together as possible.
  588. GlobalLayoutBuilder GLB(Globals.size());
  589. for (auto &&MemSet : BitSetMembers)
  590. GLB.addFragment(MemSet);
  591. // Build a vector of globals with the computed layout.
  592. std::vector<GlobalVariable *> OrderedGlobals(Globals.size());
  593. auto OGI = OrderedGlobals.begin();
  594. for (auto &&F : GLB.Fragments)
  595. for (auto &&Offset : F)
  596. *OGI++ = Globals[Offset];
  597. // Order bitsets by name for determinism.
  598. std::sort(BitSets.begin(), BitSets.end(), [](MDString *S1, MDString *S2) {
  599. return S1->getString() < S2->getString();
  600. });
  601. // Build the bitsets from this disjoint set.
  602. buildBitSetsFromGlobals(BitSets, OrderedGlobals);
  603. }
  604. allocateByteArrays();
  605. return true;
  606. }
  607. bool LowerBitSets::eraseBitSetMetadata() {
  608. if (!BitSetNM)
  609. return false;
  610. M->eraseNamedMetadata(BitSetNM);
  611. return true;
  612. }
  613. bool LowerBitSets::runOnModule(Module &M) {
  614. bool Changed = buildBitSets();
  615. Changed |= eraseBitSetMetadata();
  616. return Changed;
  617. }