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