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