1 //===-- LowerBitSets.cpp - Bitset lowering pass ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/IPO/LowerBitSets.h"
16 #include "llvm/Transforms/IPO.h"
17 #include "llvm/ADT/EquivalenceClasses.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
35 #define DEBUG_TYPE "lowerbitsets"
37 STATISTIC(ByteArraySizeBits, "Byte array size in bits");
38 STATISTIC(ByteArraySizeBytes, "Byte array size in bytes");
39 STATISTIC(NumByteArraysCreated, "Number of byte arrays created");
40 STATISTIC(NumBitSetCallsLowered, "Number of bitset calls lowered");
41 STATISTIC(NumBitSetDisjointSets, "Number of disjoint sets of bitsets");
43 static cl::opt<bool> AvoidReuse(
44 "lowerbitsets-avoid-reuse",
45 cl::desc("Try to avoid reuse of byte array addresses using aliases"),
46 cl::Hidden, cl::init(true));
48 bool BitSetInfo::containsGlobalOffset(uint64_t Offset) const {
49 if (Offset < ByteOffset)
52 if ((Offset - ByteOffset) % (uint64_t(1) << AlignLog2) != 0)
55 uint64_t BitOffset = (Offset - ByteOffset) >> AlignLog2;
56 if (BitOffset >= BitSize)
59 return Bits.count(BitOffset);
62 bool BitSetInfo::containsValue(
64 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout, Value *V,
65 uint64_t COffset) const {
66 if (auto GV = dyn_cast<GlobalVariable>(V)) {
67 auto I = GlobalLayout.find(GV);
68 if (I == GlobalLayout.end())
70 return containsGlobalOffset(I->second + COffset);
73 if (auto GEP = dyn_cast<GEPOperator>(V)) {
74 APInt APOffset(DL.getPointerSizeInBits(0), 0);
75 bool Result = GEP->accumulateConstantOffset(DL, APOffset);
78 COffset += APOffset.getZExtValue();
79 return containsValue(DL, GlobalLayout, GEP->getPointerOperand(),
83 if (auto Op = dyn_cast<Operator>(V)) {
84 if (Op->getOpcode() == Instruction::BitCast)
85 return containsValue(DL, GlobalLayout, Op->getOperand(0), COffset);
87 if (Op->getOpcode() == Instruction::Select)
88 return containsValue(DL, GlobalLayout, Op->getOperand(1), COffset) &&
89 containsValue(DL, GlobalLayout, Op->getOperand(2), COffset);
95 void BitSetInfo::print(raw_ostream &OS) const {
96 OS << "offset " << ByteOffset << " size " << BitSize << " align "
105 for (uint64_t B : Bits)
111 BitSetInfo BitSetBuilder::build() {
115 // Normalize each offset against the minimum observed offset, and compute
116 // the bitwise OR of each of the offsets. The number of trailing zeros
117 // in the mask gives us the log2 of the alignment of all offsets, which
118 // allows us to compress the bitset by only storing one bit per aligned
121 for (uint64_t &Offset : Offsets) {
127 BSI.ByteOffset = Min;
131 BSI.AlignLog2 = countTrailingZeros(Mask, ZB_Undefined);
133 // Build the compressed bitset while normalizing the offsets against the
134 // computed alignment.
135 BSI.BitSize = ((Max - Min) >> BSI.AlignLog2) + 1;
136 for (uint64_t Offset : Offsets) {
137 Offset >>= BSI.AlignLog2;
138 BSI.Bits.insert(Offset);
144 void GlobalLayoutBuilder::addFragment(const std::set<uint64_t> &F) {
145 // Create a new fragment to hold the layout for F.
146 Fragments.emplace_back();
147 std::vector<uint64_t> &Fragment = Fragments.back();
148 uint64_t FragmentIndex = Fragments.size() - 1;
150 for (auto ObjIndex : F) {
151 uint64_t OldFragmentIndex = FragmentMap[ObjIndex];
152 if (OldFragmentIndex == 0) {
153 // We haven't seen this object index before, so just add it to the current
155 Fragment.push_back(ObjIndex);
157 // This index belongs to an existing fragment. Copy the elements of the
158 // old fragment into this one and clear the old fragment. We don't update
159 // the fragment map just yet, this ensures that any further references to
160 // indices from the old fragment in this fragment do not insert any more
162 std::vector<uint64_t> &OldFragment = Fragments[OldFragmentIndex];
163 Fragment.insert(Fragment.end(), OldFragment.begin(), OldFragment.end());
168 // Update the fragment map to point our object indices to this fragment.
169 for (uint64_t ObjIndex : Fragment)
170 FragmentMap[ObjIndex] = FragmentIndex;
173 void ByteArrayBuilder::allocate(const std::set<uint64_t> &Bits,
174 uint64_t BitSize, uint64_t &AllocByteOffset,
175 uint8_t &AllocMask) {
176 // Find the smallest current allocation.
178 for (unsigned I = 1; I != BitsPerByte; ++I)
179 if (BitAllocs[I] < BitAllocs[Bit])
182 AllocByteOffset = BitAllocs[Bit];
184 // Add our size to it.
185 unsigned ReqSize = AllocByteOffset + BitSize;
186 BitAllocs[Bit] = ReqSize;
187 if (Bytes.size() < ReqSize)
188 Bytes.resize(ReqSize);
191 AllocMask = 1 << Bit;
192 for (uint64_t B : Bits)
193 Bytes[AllocByteOffset + B] |= AllocMask;
198 struct ByteArrayInfo {
199 std::set<uint64_t> Bits;
201 GlobalVariable *ByteArray;
205 struct LowerBitSets : public ModulePass {
207 LowerBitSets() : ModulePass(ID) {
208 initializeLowerBitSetsPass(*PassRegistry::getPassRegistry());
213 bool LinkerSubsectionsViaSymbols;
216 IntegerType *Int32Ty;
218 IntegerType *Int64Ty;
221 // The llvm.bitsets named metadata.
222 NamedMDNode *BitSetNM;
224 // Mapping from bitset mdstrings to the call sites that test them.
225 DenseMap<MDString *, std::vector<CallInst *>> BitSetTestCallSites;
227 std::vector<ByteArrayInfo> ByteArrayInfos;
230 buildBitSet(MDString *BitSet,
231 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
232 ByteArrayInfo *createByteArray(BitSetInfo &BSI);
233 void allocateByteArrays();
234 Value *createBitSetTest(IRBuilder<> &B, BitSetInfo &BSI, ByteArrayInfo *&BAI,
237 lowerBitSetCall(CallInst *CI, BitSetInfo &BSI, ByteArrayInfo *&BAI,
238 GlobalVariable *CombinedGlobal,
239 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout);
240 void buildBitSetsFromGlobals(const std::vector<MDString *> &BitSets,
241 const std::vector<GlobalVariable *> &Globals);
243 bool eraseBitSetMetadata();
245 bool doInitialization(Module &M) override;
246 bool runOnModule(Module &M) override;
251 INITIALIZE_PASS_BEGIN(LowerBitSets, "lowerbitsets",
252 "Lower bitset metadata", false, false)
253 INITIALIZE_PASS_END(LowerBitSets, "lowerbitsets",
254 "Lower bitset metadata", false, false)
255 char LowerBitSets::ID = 0;
257 ModulePass *llvm::createLowerBitSetsPass() { return new LowerBitSets; }
259 bool LowerBitSets::doInitialization(Module &Mod) {
261 const DataLayout &DL = Mod.getDataLayout();
263 Triple TargetTriple(M->getTargetTriple());
264 LinkerSubsectionsViaSymbols = TargetTriple.isMacOSX();
266 Int1Ty = Type::getInt1Ty(M->getContext());
267 Int8Ty = Type::getInt8Ty(M->getContext());
268 Int32Ty = Type::getInt32Ty(M->getContext());
269 Int32PtrTy = PointerType::getUnqual(Int32Ty);
270 Int64Ty = Type::getInt64Ty(M->getContext());
271 IntPtrTy = DL.getIntPtrType(M->getContext(), 0);
273 BitSetNM = M->getNamedMetadata("llvm.bitsets");
275 BitSetTestCallSites.clear();
280 /// Build a bit set for BitSet using the object layouts in
282 BitSetInfo LowerBitSets::buildBitSet(
284 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
287 // Compute the byte offset of each element of this bitset.
289 for (MDNode *Op : BitSetNM->operands()) {
290 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
292 auto OpGlobal = dyn_cast<GlobalVariable>(
293 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
297 cast<ConstantInt>(cast<ConstantAsMetadata>(Op->getOperand(2))
298 ->getValue())->getZExtValue();
300 Offset += GlobalLayout.find(OpGlobal)->second;
302 BSB.addOffset(Offset);
309 /// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
310 /// Bits. This pattern matches to the bt instruction on x86.
311 static Value *createMaskedBitTest(IRBuilder<> &B, Value *Bits,
313 auto BitsType = cast<IntegerType>(Bits->getType());
314 unsigned BitWidth = BitsType->getBitWidth();
316 BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
318 B.CreateAnd(BitOffset, ConstantInt::get(BitsType, BitWidth - 1));
319 Value *BitMask = B.CreateShl(ConstantInt::get(BitsType, 1), BitIndex);
320 Value *MaskedBits = B.CreateAnd(Bits, BitMask);
321 return B.CreateICmpNE(MaskedBits, ConstantInt::get(BitsType, 0));
324 ByteArrayInfo *LowerBitSets::createByteArray(BitSetInfo &BSI) {
325 // Create globals to stand in for byte arrays and masks. These never actually
326 // get initialized, we RAUW and erase them later in allocateByteArrays() once
327 // we know the offset and mask to use.
328 auto ByteArrayGlobal = new GlobalVariable(
329 *M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
330 auto MaskGlobal = new GlobalVariable(
331 *M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
333 ByteArrayInfos.emplace_back();
334 ByteArrayInfo *BAI = &ByteArrayInfos.back();
336 BAI->Bits = BSI.Bits;
337 BAI->BitSize = BSI.BitSize;
338 BAI->ByteArray = ByteArrayGlobal;
339 BAI->Mask = ConstantExpr::getPtrToInt(MaskGlobal, Int8Ty);
343 void LowerBitSets::allocateByteArrays() {
344 std::stable_sort(ByteArrayInfos.begin(), ByteArrayInfos.end(),
345 [](const ByteArrayInfo &BAI1, const ByteArrayInfo &BAI2) {
346 return BAI1.BitSize > BAI2.BitSize;
349 std::vector<uint64_t> ByteArrayOffsets(ByteArrayInfos.size());
351 ByteArrayBuilder BAB;
352 for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
353 ByteArrayInfo *BAI = &ByteArrayInfos[I];
356 BAB.allocate(BAI->Bits, BAI->BitSize, ByteArrayOffsets[I], Mask);
358 BAI->Mask->replaceAllUsesWith(ConstantInt::get(Int8Ty, Mask));
359 cast<GlobalVariable>(BAI->Mask->getOperand(0))->eraseFromParent();
362 Constant *ByteArrayConst = ConstantDataArray::get(M->getContext(), BAB.Bytes);
364 new GlobalVariable(*M, ByteArrayConst->getType(), /*isConstant=*/true,
365 GlobalValue::PrivateLinkage, ByteArrayConst);
367 for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
368 ByteArrayInfo *BAI = &ByteArrayInfos[I];
370 Constant *Idxs[] = {ConstantInt::get(IntPtrTy, 0),
371 ConstantInt::get(IntPtrTy, ByteArrayOffsets[I])};
372 Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(
373 ByteArrayConst->getType(), ByteArray, Idxs);
375 // Create an alias instead of RAUW'ing the gep directly. On x86 this ensures
376 // that the pc-relative displacement is folded into the lea instead of the
377 // test instruction getting another displacement.
378 if (LinkerSubsectionsViaSymbols) {
379 BAI->ByteArray->replaceAllUsesWith(GEP);
382 GlobalAlias::create(PointerType::getUnqual(Int8Ty),
383 GlobalValue::PrivateLinkage, "bits", GEP, M);
384 BAI->ByteArray->replaceAllUsesWith(Alias);
386 BAI->ByteArray->eraseFromParent();
389 ByteArraySizeBits = BAB.BitAllocs[0] + BAB.BitAllocs[1] + BAB.BitAllocs[2] +
390 BAB.BitAllocs[3] + BAB.BitAllocs[4] + BAB.BitAllocs[5] +
391 BAB.BitAllocs[6] + BAB.BitAllocs[7];
392 ByteArraySizeBytes = BAB.Bytes.size();
395 /// Build a test that bit BitOffset is set in BSI, where
396 /// BitSetGlobal is a global containing the bits in BSI.
397 Value *LowerBitSets::createBitSetTest(IRBuilder<> &B, BitSetInfo &BSI,
398 ByteArrayInfo *&BAI, Value *BitOffset) {
399 if (BSI.BitSize <= 64) {
400 // If the bit set is sufficiently small, we can avoid a load by bit testing
403 if (BSI.BitSize <= 32)
409 for (auto Bit : BSI.Bits)
410 Bits |= uint64_t(1) << Bit;
411 Constant *BitsConst = ConstantInt::get(BitsTy, Bits);
412 return createMaskedBitTest(B, BitsConst, BitOffset);
415 ++NumByteArraysCreated;
416 BAI = createByteArray(BSI);
419 Constant *ByteArray = BAI->ByteArray;
420 Type *Ty = BAI->ByteArray->getValueType();
421 if (!LinkerSubsectionsViaSymbols && AvoidReuse) {
422 // Each use of the byte array uses a different alias. This makes the
423 // backend less likely to reuse previously computed byte array addresses,
424 // improving the security of the CFI mechanism based on this pass.
425 ByteArray = GlobalAlias::create(BAI->ByteArray->getType(),
426 GlobalValue::PrivateLinkage, "bits_use",
430 Value *ByteAddr = B.CreateGEP(Ty, ByteArray, BitOffset);
431 Value *Byte = B.CreateLoad(ByteAddr);
433 Value *ByteAndMask = B.CreateAnd(Byte, BAI->Mask);
434 return B.CreateICmpNE(ByteAndMask, ConstantInt::get(Int8Ty, 0));
438 /// Lower a llvm.bitset.test call to its implementation. Returns the value to
439 /// replace the call with.
440 Value *LowerBitSets::lowerBitSetCall(
441 CallInst *CI, BitSetInfo &BSI, ByteArrayInfo *&BAI,
442 GlobalVariable *CombinedGlobal,
443 const DenseMap<GlobalVariable *, uint64_t> &GlobalLayout) {
444 Value *Ptr = CI->getArgOperand(0);
445 const DataLayout &DL = M->getDataLayout();
447 if (BSI.containsValue(DL, GlobalLayout, Ptr))
448 return ConstantInt::getTrue(CombinedGlobal->getParent()->getContext());
450 Constant *GlobalAsInt = ConstantExpr::getPtrToInt(CombinedGlobal, IntPtrTy);
451 Constant *OffsetedGlobalAsInt = ConstantExpr::getAdd(
452 GlobalAsInt, ConstantInt::get(IntPtrTy, BSI.ByteOffset));
454 BasicBlock *InitialBB = CI->getParent();
458 Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
460 if (BSI.isSingleOffset())
461 return B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
463 Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
466 if (BSI.AlignLog2 == 0) {
467 BitOffset = PtrOffset;
469 // We need to check that the offset both falls within our range and is
470 // suitably aligned. We can check both properties at the same time by
471 // performing a right rotate by log2(alignment) followed by an integer
472 // comparison against the bitset size. The rotate will move the lower
473 // order bits that need to be zero into the higher order bits of the
474 // result, causing the comparison to fail if they are nonzero. The rotate
475 // also conveniently gives us a bit offset to use during the load from
478 B.CreateLShr(PtrOffset, ConstantInt::get(IntPtrTy, BSI.AlignLog2));
479 Value *OffsetSHL = B.CreateShl(
481 ConstantInt::get(IntPtrTy, DL.getPointerSizeInBits(0) - BSI.AlignLog2));
482 BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
485 Constant *BitSizeConst = ConstantInt::get(IntPtrTy, BSI.BitSize);
486 Value *OffsetInRange = B.CreateICmpULT(BitOffset, BitSizeConst);
488 // If the bit set is all ones, testing against it is unnecessary.
490 return OffsetInRange;
492 TerminatorInst *Term = SplitBlockAndInsertIfThen(OffsetInRange, CI, false);
493 IRBuilder<> ThenB(Term);
495 // Now that we know that the offset is in range and aligned, load the
496 // appropriate bit from the bitset.
497 Value *Bit = createBitSetTest(ThenB, BSI, BAI, BitOffset);
499 // The value we want is 0 if we came directly from the initial block
500 // (having failed the range or alignment checks), or the loaded bit if
501 // we came from the block in which we loaded it.
502 B.SetInsertPoint(CI);
503 PHINode *P = B.CreatePHI(Int1Ty, 2);
504 P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
505 P->addIncoming(Bit, ThenB.GetInsertBlock());
509 /// Given a disjoint set of bitsets and globals, layout the globals, build the
510 /// bit sets and lower the llvm.bitset.test calls.
511 void LowerBitSets::buildBitSetsFromGlobals(
512 const std::vector<MDString *> &BitSets,
513 const std::vector<GlobalVariable *> &Globals) {
514 // Build a new global with the combined contents of the referenced globals.
515 std::vector<Constant *> GlobalInits;
516 const DataLayout &DL = M->getDataLayout();
517 for (GlobalVariable *G : Globals) {
518 GlobalInits.push_back(G->getInitializer());
519 uint64_t InitSize = DL.getTypeAllocSize(G->getInitializer()->getType());
521 // Compute the amount of padding required to align the next element to the
523 uint64_t Padding = NextPowerOf2(InitSize - 1) - InitSize;
525 // Cap at 128 was found experimentally to have a good data/instruction
526 // overhead tradeoff.
528 Padding = RoundUpToAlignment(InitSize, 128) - InitSize;
530 GlobalInits.push_back(
531 ConstantAggregateZero::get(ArrayType::get(Int8Ty, Padding)));
533 if (!GlobalInits.empty())
534 GlobalInits.pop_back();
535 Constant *NewInit = ConstantStruct::getAnon(M->getContext(), GlobalInits);
536 auto CombinedGlobal =
537 new GlobalVariable(*M, NewInit->getType(), /*isConstant=*/true,
538 GlobalValue::PrivateLinkage, NewInit);
540 const StructLayout *CombinedGlobalLayout =
541 DL.getStructLayout(cast<StructType>(NewInit->getType()));
543 // Compute the offsets of the original globals within the new global.
544 DenseMap<GlobalVariable *, uint64_t> GlobalLayout;
545 for (unsigned I = 0; I != Globals.size(); ++I)
546 // Multiply by 2 to account for padding elements.
547 GlobalLayout[Globals[I]] = CombinedGlobalLayout->getElementOffset(I * 2);
549 // For each bitset in this disjoint set...
550 for (MDString *BS : BitSets) {
552 BitSetInfo BSI = buildBitSet(BS, GlobalLayout);
554 dbgs() << BS->getString() << ": ";
558 ByteArrayInfo *BAI = 0;
560 // Lower each call to llvm.bitset.test for this bitset.
561 for (CallInst *CI : BitSetTestCallSites[BS]) {
562 ++NumBitSetCallsLowered;
563 Value *Lowered = lowerBitSetCall(CI, BSI, BAI, CombinedGlobal, GlobalLayout);
564 CI->replaceAllUsesWith(Lowered);
565 CI->eraseFromParent();
569 // Build aliases pointing to offsets into the combined global for each
570 // global from which we built the combined global, and replace references
571 // to the original globals with references to the aliases.
572 for (unsigned I = 0; I != Globals.size(); ++I) {
573 // Multiply by 2 to account for padding elements.
574 Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
575 ConstantInt::get(Int32Ty, I * 2)};
576 Constant *CombinedGlobalElemPtr = ConstantExpr::getGetElementPtr(
577 NewInit->getType(), CombinedGlobal, CombinedGlobalIdxs);
578 if (LinkerSubsectionsViaSymbols) {
579 Globals[I]->replaceAllUsesWith(CombinedGlobalElemPtr);
581 GlobalAlias *GAlias =
582 GlobalAlias::create(Globals[I]->getType(), Globals[I]->getLinkage(),
583 "", CombinedGlobalElemPtr, M);
584 GAlias->takeName(Globals[I]);
585 Globals[I]->replaceAllUsesWith(GAlias);
587 Globals[I]->eraseFromParent();
591 /// Lower all bit sets in this module.
592 bool LowerBitSets::buildBitSets() {
593 Function *BitSetTestFunc =
594 M->getFunction(Intrinsic::getName(Intrinsic::bitset_test));
598 // Equivalence class set containing bitsets and the globals they reference.
599 // This is used to partition the set of bitsets in the module into disjoint
601 typedef EquivalenceClasses<PointerUnion<GlobalVariable *, MDString *>>
603 GlobalClassesTy GlobalClasses;
605 for (const Use &U : BitSetTestFunc->uses()) {
606 auto CI = cast<CallInst>(U.getUser());
608 auto BitSetMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
609 if (!BitSetMDVal || !isa<MDString>(BitSetMDVal->getMetadata()))
611 "Second argument of llvm.bitset.test must be metadata string");
612 auto BitSet = cast<MDString>(BitSetMDVal->getMetadata());
614 // Add the call site to the list of call sites for this bit set. We also use
615 // BitSetTestCallSites to keep track of whether we have seen this bit set
616 // before. If we have, we don't need to re-add the referenced globals to the
617 // equivalence class.
618 std::pair<DenseMap<MDString *, std::vector<CallInst *>>::iterator,
620 BitSetTestCallSites.insert(
621 std::make_pair(BitSet, std::vector<CallInst *>()));
622 Ins.first->second.push_back(CI);
626 // Add the bitset to the equivalence class.
627 GlobalClassesTy::iterator GCI = GlobalClasses.insert(BitSet);
628 GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
633 // Verify the bitset metadata and add the referenced globals to the bitset's
634 // equivalence class.
635 for (MDNode *Op : BitSetNM->operands()) {
636 if (Op->getNumOperands() != 3)
638 "All operands of llvm.bitsets metadata must have 3 elements");
640 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
643 auto OpConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(1));
645 report_fatal_error("Bit set element must be a constant");
646 auto OpGlobal = dyn_cast<GlobalVariable>(OpConstMD->getValue());
650 auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(2));
652 report_fatal_error("Bit set element offset must be a constant");
653 auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
656 "Bit set element offset must be an integer constant");
658 CurSet = GlobalClasses.unionSets(
659 CurSet, GlobalClasses.findLeader(GlobalClasses.insert(OpGlobal)));
663 if (GlobalClasses.empty())
666 // For each disjoint set we found...
667 for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
668 E = GlobalClasses.end();
670 if (!I->isLeader()) continue;
672 ++NumBitSetDisjointSets;
674 // Build the list of bitsets and referenced globals in this disjoint set.
675 std::vector<MDString *> BitSets;
676 std::vector<GlobalVariable *> Globals;
677 llvm::DenseMap<MDString *, uint64_t> BitSetIndices;
678 llvm::DenseMap<GlobalVariable *, uint64_t> GlobalIndices;
679 for (GlobalClassesTy::member_iterator MI = GlobalClasses.member_begin(I);
680 MI != GlobalClasses.member_end(); ++MI) {
681 if ((*MI).is<MDString *>()) {
682 BitSetIndices[MI->get<MDString *>()] = BitSets.size();
683 BitSets.push_back(MI->get<MDString *>());
685 GlobalIndices[MI->get<GlobalVariable *>()] = Globals.size();
686 Globals.push_back(MI->get<GlobalVariable *>());
690 // For each bitset, build a set of indices that refer to globals referenced
692 std::vector<std::set<uint64_t>> BitSetMembers(BitSets.size());
694 for (MDNode *Op : BitSetNM->operands()) {
695 // Op = { bitset name, global, offset }
696 if (!Op->getOperand(1))
698 auto I = BitSetIndices.find(cast<MDString>(Op->getOperand(0)));
699 if (I == BitSetIndices.end())
702 auto OpGlobal = dyn_cast<GlobalVariable>(
703 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
706 BitSetMembers[I->second].insert(GlobalIndices[OpGlobal]);
710 // Order the sets of indices by size. The GlobalLayoutBuilder works best
711 // when given small index sets first.
713 BitSetMembers.begin(), BitSetMembers.end(),
714 [](const std::set<uint64_t> &O1, const std::set<uint64_t> &O2) {
715 return O1.size() < O2.size();
718 // Create a GlobalLayoutBuilder and provide it with index sets as layout
719 // fragments. The GlobalLayoutBuilder tries to lay out members of fragments
720 // as close together as possible.
721 GlobalLayoutBuilder GLB(Globals.size());
722 for (auto &&MemSet : BitSetMembers)
723 GLB.addFragment(MemSet);
725 // Build a vector of globals with the computed layout.
726 std::vector<GlobalVariable *> OrderedGlobals(Globals.size());
727 auto OGI = OrderedGlobals.begin();
728 for (auto &&F : GLB.Fragments)
729 for (auto &&Offset : F)
730 *OGI++ = Globals[Offset];
732 // Order bitsets by name for determinism.
733 std::sort(BitSets.begin(), BitSets.end(), [](MDString *S1, MDString *S2) {
734 return S1->getString() < S2->getString();
737 // Build the bitsets from this disjoint set.
738 buildBitSetsFromGlobals(BitSets, OrderedGlobals);
741 allocateByteArrays();
746 bool LowerBitSets::eraseBitSetMetadata() {
750 M->eraseNamedMetadata(BitSetNM);
754 bool LowerBitSets::runOnModule(Module &M) {
755 bool Changed = buildBitSets();
756 Changed |= eraseBitSetMetadata();