549c4bf557abec04847390989c91794e2b1bd517
[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/ADT/Triple.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/GlobalObject.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34
35 using namespace llvm;
36
37 #define DEBUG_TYPE "lowerbitsets"
38
39 STATISTIC(ByteArraySizeBits, "Byte array size in bits");
40 STATISTIC(ByteArraySizeBytes, "Byte array size in bytes");
41 STATISTIC(NumByteArraysCreated, "Number of byte arrays created");
42 STATISTIC(NumBitSetCallsLowered, "Number of bitset calls lowered");
43 STATISTIC(NumBitSetDisjointSets, "Number of disjoint sets of bitsets");
44
45 static cl::opt<bool> AvoidReuse(
46     "lowerbitsets-avoid-reuse",
47     cl::desc("Try to avoid reuse of byte array addresses using aliases"),
48     cl::Hidden, cl::init(true));
49
50 bool BitSetInfo::containsGlobalOffset(uint64_t Offset) const {
51   if (Offset < ByteOffset)
52     return false;
53
54   if ((Offset - ByteOffset) % (uint64_t(1) << AlignLog2) != 0)
55     return false;
56
57   uint64_t BitOffset = (Offset - ByteOffset) >> AlignLog2;
58   if (BitOffset >= BitSize)
59     return false;
60
61   return Bits.count(BitOffset);
62 }
63
64 bool BitSetInfo::containsValue(
65     const DataLayout &DL,
66     const DenseMap<GlobalObject *, uint64_t> &GlobalLayout, Value *V,
67     uint64_t COffset) const {
68   if (auto GV = dyn_cast<GlobalObject>(V)) {
69     auto I = GlobalLayout.find(GV);
70     if (I == GlobalLayout.end())
71       return false;
72     return containsGlobalOffset(I->second + COffset);
73   }
74
75   if (auto GEP = dyn_cast<GEPOperator>(V)) {
76     APInt APOffset(DL.getPointerSizeInBits(0), 0);
77     bool Result = GEP->accumulateConstantOffset(DL, APOffset);
78     if (!Result)
79       return false;
80     COffset += APOffset.getZExtValue();
81     return containsValue(DL, GlobalLayout, GEP->getPointerOperand(),
82                          COffset);
83   }
84
85   if (auto Op = dyn_cast<Operator>(V)) {
86     if (Op->getOpcode() == Instruction::BitCast)
87       return containsValue(DL, GlobalLayout, Op->getOperand(0), COffset);
88
89     if (Op->getOpcode() == Instruction::Select)
90       return containsValue(DL, GlobalLayout, Op->getOperand(1), COffset) &&
91              containsValue(DL, GlobalLayout, Op->getOperand(2), COffset);
92   }
93
94   return false;
95 }
96
97 void BitSetInfo::print(raw_ostream &OS) const {
98   OS << "offset " << ByteOffset << " size " << BitSize << " align "
99      << (1 << AlignLog2);
100
101   if (isAllOnes()) {
102     OS << " all-ones\n";
103     return;
104   }
105
106   OS << " { ";
107   for (uint64_t B : Bits)
108     OS << B << ' ';
109   OS << "}\n";
110   return;
111 }
112
113 BitSetInfo BitSetBuilder::build() {
114   if (Min > Max)
115     Min = 0;
116
117   // Normalize each offset against the minimum observed offset, and compute
118   // the bitwise OR of each of the offsets. The number of trailing zeros
119   // in the mask gives us the log2 of the alignment of all offsets, which
120   // allows us to compress the bitset by only storing one bit per aligned
121   // address.
122   uint64_t Mask = 0;
123   for (uint64_t &Offset : Offsets) {
124     Offset -= Min;
125     Mask |= Offset;
126   }
127
128   BitSetInfo BSI;
129   BSI.ByteOffset = Min;
130
131   BSI.AlignLog2 = 0;
132   if (Mask != 0)
133     BSI.AlignLog2 = countTrailingZeros(Mask, ZB_Undefined);
134
135   // Build the compressed bitset while normalizing the offsets against the
136   // computed alignment.
137   BSI.BitSize = ((Max - Min) >> BSI.AlignLog2) + 1;
138   for (uint64_t Offset : Offsets) {
139     Offset >>= BSI.AlignLog2;
140     BSI.Bits.insert(Offset);
141   }
142
143   return BSI;
144 }
145
146 void GlobalLayoutBuilder::addFragment(const std::set<uint64_t> &F) {
147   // Create a new fragment to hold the layout for F.
148   Fragments.emplace_back();
149   std::vector<uint64_t> &Fragment = Fragments.back();
150   uint64_t FragmentIndex = Fragments.size() - 1;
151
152   for (auto ObjIndex : F) {
153     uint64_t OldFragmentIndex = FragmentMap[ObjIndex];
154     if (OldFragmentIndex == 0) {
155       // We haven't seen this object index before, so just add it to the current
156       // fragment.
157       Fragment.push_back(ObjIndex);
158     } else {
159       // This index belongs to an existing fragment. Copy the elements of the
160       // old fragment into this one and clear the old fragment. We don't update
161       // the fragment map just yet, this ensures that any further references to
162       // indices from the old fragment in this fragment do not insert any more
163       // indices.
164       std::vector<uint64_t> &OldFragment = Fragments[OldFragmentIndex];
165       Fragment.insert(Fragment.end(), OldFragment.begin(), OldFragment.end());
166       OldFragment.clear();
167     }
168   }
169
170   // Update the fragment map to point our object indices to this fragment.
171   for (uint64_t ObjIndex : Fragment)
172     FragmentMap[ObjIndex] = FragmentIndex;
173 }
174
175 void ByteArrayBuilder::allocate(const std::set<uint64_t> &Bits,
176                                 uint64_t BitSize, uint64_t &AllocByteOffset,
177                                 uint8_t &AllocMask) {
178   // Find the smallest current allocation.
179   unsigned Bit = 0;
180   for (unsigned I = 1; I != BitsPerByte; ++I)
181     if (BitAllocs[I] < BitAllocs[Bit])
182       Bit = I;
183
184   AllocByteOffset = BitAllocs[Bit];
185
186   // Add our size to it.
187   unsigned ReqSize = AllocByteOffset + BitSize;
188   BitAllocs[Bit] = ReqSize;
189   if (Bytes.size() < ReqSize)
190     Bytes.resize(ReqSize);
191
192   // Set our bits.
193   AllocMask = 1 << Bit;
194   for (uint64_t B : Bits)
195     Bytes[AllocByteOffset + B] |= AllocMask;
196 }
197
198 namespace {
199
200 struct ByteArrayInfo {
201   std::set<uint64_t> Bits;
202   uint64_t BitSize;
203   GlobalVariable *ByteArray;
204   Constant *Mask;
205 };
206
207 struct LowerBitSets : public ModulePass {
208   static char ID;
209   LowerBitSets() : ModulePass(ID) {
210     initializeLowerBitSetsPass(*PassRegistry::getPassRegistry());
211   }
212
213   Module *M;
214
215   bool LinkerSubsectionsViaSymbols;
216   Triple::ArchType Arch;
217   Triple::ObjectFormatType ObjectFormat;
218   IntegerType *Int1Ty;
219   IntegerType *Int8Ty;
220   IntegerType *Int32Ty;
221   Type *Int32PtrTy;
222   IntegerType *Int64Ty;
223   IntegerType *IntPtrTy;
224
225   // The llvm.bitsets named metadata.
226   NamedMDNode *BitSetNM;
227
228   // Mapping from bitset identifiers to the call sites that test them.
229   DenseMap<Metadata *, std::vector<CallInst *>> BitSetTestCallSites;
230
231   std::vector<ByteArrayInfo> ByteArrayInfos;
232
233   BitSetInfo
234   buildBitSet(Metadata *BitSet,
235               const DenseMap<GlobalObject *, uint64_t> &GlobalLayout);
236   ByteArrayInfo *createByteArray(BitSetInfo &BSI);
237   void allocateByteArrays();
238   Value *createBitSetTest(IRBuilder<> &B, BitSetInfo &BSI, ByteArrayInfo *&BAI,
239                           Value *BitOffset);
240   void lowerBitSetCalls(ArrayRef<Metadata *> BitSets,
241                         Constant *CombinedGlobalAddr,
242                         const DenseMap<GlobalObject *, uint64_t> &GlobalLayout);
243   Value *
244   lowerBitSetCall(CallInst *CI, BitSetInfo &BSI, ByteArrayInfo *&BAI,
245                   Constant *CombinedGlobal,
246                   const DenseMap<GlobalObject *, uint64_t> &GlobalLayout);
247   void buildBitSetsFromGlobalVariables(ArrayRef<Metadata *> BitSets,
248                                        ArrayRef<GlobalVariable *> Globals);
249   unsigned getJumpTableEntrySize();
250   Type *getJumpTableEntryType();
251   Constant *createJumpTableEntry(GlobalObject *Src, Function *Dest,
252                                  unsigned Distance);
253   void verifyBitSetMDNode(MDNode *Op);
254   void buildBitSetsFromFunctions(ArrayRef<Metadata *> BitSets,
255                                  ArrayRef<Function *> Functions);
256   void buildBitSetsFromDisjointSet(ArrayRef<Metadata *> BitSets,
257                                    ArrayRef<GlobalObject *> Globals);
258   bool buildBitSets();
259   bool eraseBitSetMetadata();
260
261   bool doInitialization(Module &M) override;
262   bool runOnModule(Module &M) override;
263 };
264
265 } // namespace
266
267 INITIALIZE_PASS_BEGIN(LowerBitSets, "lowerbitsets",
268                 "Lower bitset metadata", false, false)
269 INITIALIZE_PASS_END(LowerBitSets, "lowerbitsets",
270                 "Lower bitset metadata", false, false)
271 char LowerBitSets::ID = 0;
272
273 ModulePass *llvm::createLowerBitSetsPass() { return new LowerBitSets; }
274
275 bool LowerBitSets::doInitialization(Module &Mod) {
276   M = &Mod;
277   const DataLayout &DL = Mod.getDataLayout();
278
279   Triple TargetTriple(M->getTargetTriple());
280   LinkerSubsectionsViaSymbols = TargetTriple.isMacOSX();
281   Arch = TargetTriple.getArch();
282   ObjectFormat = TargetTriple.getObjectFormat();
283
284   Int1Ty = Type::getInt1Ty(M->getContext());
285   Int8Ty = Type::getInt8Ty(M->getContext());
286   Int32Ty = Type::getInt32Ty(M->getContext());
287   Int32PtrTy = PointerType::getUnqual(Int32Ty);
288   Int64Ty = Type::getInt64Ty(M->getContext());
289   IntPtrTy = DL.getIntPtrType(M->getContext(), 0);
290
291   BitSetNM = M->getNamedMetadata("llvm.bitsets");
292
293   BitSetTestCallSites.clear();
294
295   return false;
296 }
297
298 /// Build a bit set for BitSet using the object layouts in
299 /// GlobalLayout.
300 BitSetInfo LowerBitSets::buildBitSet(
301     Metadata *BitSet,
302     const DenseMap<GlobalObject *, uint64_t> &GlobalLayout) {
303   BitSetBuilder BSB;
304
305   // Compute the byte offset of each element of this bitset.
306   if (BitSetNM) {
307     for (MDNode *Op : BitSetNM->operands()) {
308       if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
309         continue;
310       Constant *OpConst =
311           cast<ConstantAsMetadata>(Op->getOperand(1))->getValue();
312       if (auto GA = dyn_cast<GlobalAlias>(OpConst))
313         OpConst = GA->getAliasee();
314       auto OpGlobal = dyn_cast<GlobalObject>(OpConst);
315       if (!OpGlobal)
316         continue;
317       uint64_t Offset =
318           cast<ConstantInt>(cast<ConstantAsMetadata>(Op->getOperand(2))
319                                 ->getValue())->getZExtValue();
320
321       Offset += GlobalLayout.find(OpGlobal)->second;
322
323       BSB.addOffset(Offset);
324     }
325   }
326
327   return BSB.build();
328 }
329
330 /// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
331 /// Bits. This pattern matches to the bt instruction on x86.
332 static Value *createMaskedBitTest(IRBuilder<> &B, Value *Bits,
333                                   Value *BitOffset) {
334   auto BitsType = cast<IntegerType>(Bits->getType());
335   unsigned BitWidth = BitsType->getBitWidth();
336
337   BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
338   Value *BitIndex =
339       B.CreateAnd(BitOffset, ConstantInt::get(BitsType, BitWidth - 1));
340   Value *BitMask = B.CreateShl(ConstantInt::get(BitsType, 1), BitIndex);
341   Value *MaskedBits = B.CreateAnd(Bits, BitMask);
342   return B.CreateICmpNE(MaskedBits, ConstantInt::get(BitsType, 0));
343 }
344
345 ByteArrayInfo *LowerBitSets::createByteArray(BitSetInfo &BSI) {
346   // Create globals to stand in for byte arrays and masks. These never actually
347   // get initialized, we RAUW and erase them later in allocateByteArrays() once
348   // we know the offset and mask to use.
349   auto ByteArrayGlobal = new GlobalVariable(
350       *M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
351   auto MaskGlobal = new GlobalVariable(
352       *M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
353
354   ByteArrayInfos.emplace_back();
355   ByteArrayInfo *BAI = &ByteArrayInfos.back();
356
357   BAI->Bits = BSI.Bits;
358   BAI->BitSize = BSI.BitSize;
359   BAI->ByteArray = ByteArrayGlobal;
360   BAI->Mask = ConstantExpr::getPtrToInt(MaskGlobal, Int8Ty);
361   return BAI;
362 }
363
364 void LowerBitSets::allocateByteArrays() {
365   std::stable_sort(ByteArrayInfos.begin(), ByteArrayInfos.end(),
366                    [](const ByteArrayInfo &BAI1, const ByteArrayInfo &BAI2) {
367                      return BAI1.BitSize > BAI2.BitSize;
368                    });
369
370   std::vector<uint64_t> ByteArrayOffsets(ByteArrayInfos.size());
371
372   ByteArrayBuilder BAB;
373   for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
374     ByteArrayInfo *BAI = &ByteArrayInfos[I];
375
376     uint8_t Mask;
377     BAB.allocate(BAI->Bits, BAI->BitSize, ByteArrayOffsets[I], Mask);
378
379     BAI->Mask->replaceAllUsesWith(ConstantInt::get(Int8Ty, Mask));
380     cast<GlobalVariable>(BAI->Mask->getOperand(0))->eraseFromParent();
381   }
382
383   Constant *ByteArrayConst = ConstantDataArray::get(M->getContext(), BAB.Bytes);
384   auto ByteArray =
385       new GlobalVariable(*M, ByteArrayConst->getType(), /*isConstant=*/true,
386                          GlobalValue::PrivateLinkage, ByteArrayConst);
387
388   for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
389     ByteArrayInfo *BAI = &ByteArrayInfos[I];
390
391     Constant *Idxs[] = {ConstantInt::get(IntPtrTy, 0),
392                         ConstantInt::get(IntPtrTy, ByteArrayOffsets[I])};
393     Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(
394         ByteArrayConst->getType(), ByteArray, Idxs);
395
396     // Create an alias instead of RAUW'ing the gep directly. On x86 this ensures
397     // that the pc-relative displacement is folded into the lea instead of the
398     // test instruction getting another displacement.
399     if (LinkerSubsectionsViaSymbols) {
400       BAI->ByteArray->replaceAllUsesWith(GEP);
401     } else {
402       GlobalAlias *Alias =
403           GlobalAlias::create(PointerType::getUnqual(Int8Ty),
404                               GlobalValue::PrivateLinkage, "bits", GEP, M);
405       BAI->ByteArray->replaceAllUsesWith(Alias);
406     }
407     BAI->ByteArray->eraseFromParent();
408   }
409
410   ByteArraySizeBits = BAB.BitAllocs[0] + BAB.BitAllocs[1] + BAB.BitAllocs[2] +
411                       BAB.BitAllocs[3] + BAB.BitAllocs[4] + BAB.BitAllocs[5] +
412                       BAB.BitAllocs[6] + BAB.BitAllocs[7];
413   ByteArraySizeBytes = BAB.Bytes.size();
414 }
415
416 /// Build a test that bit BitOffset is set in BSI, where
417 /// BitSetGlobal is a global containing the bits in BSI.
418 Value *LowerBitSets::createBitSetTest(IRBuilder<> &B, BitSetInfo &BSI,
419                                       ByteArrayInfo *&BAI, Value *BitOffset) {
420   if (BSI.BitSize <= 64) {
421     // If the bit set is sufficiently small, we can avoid a load by bit testing
422     // a constant.
423     IntegerType *BitsTy;
424     if (BSI.BitSize <= 32)
425       BitsTy = Int32Ty;
426     else
427       BitsTy = Int64Ty;
428
429     uint64_t Bits = 0;
430     for (auto Bit : BSI.Bits)
431       Bits |= uint64_t(1) << Bit;
432     Constant *BitsConst = ConstantInt::get(BitsTy, Bits);
433     return createMaskedBitTest(B, BitsConst, BitOffset);
434   } else {
435     if (!BAI) {
436       ++NumByteArraysCreated;
437       BAI = createByteArray(BSI);
438     }
439
440     Constant *ByteArray = BAI->ByteArray;
441     Type *Ty = BAI->ByteArray->getValueType();
442     if (!LinkerSubsectionsViaSymbols && AvoidReuse) {
443       // Each use of the byte array uses a different alias. This makes the
444       // backend less likely to reuse previously computed byte array addresses,
445       // improving the security of the CFI mechanism based on this pass.
446       ByteArray = GlobalAlias::create(BAI->ByteArray->getType(),
447                                       GlobalValue::PrivateLinkage, "bits_use",
448                                       ByteArray, M);
449     }
450
451     Value *ByteAddr = B.CreateGEP(Ty, ByteArray, BitOffset);
452     Value *Byte = B.CreateLoad(ByteAddr);
453
454     Value *ByteAndMask = B.CreateAnd(Byte, BAI->Mask);
455     return B.CreateICmpNE(ByteAndMask, ConstantInt::get(Int8Ty, 0));
456   }
457 }
458
459 /// Lower a llvm.bitset.test call to its implementation. Returns the value to
460 /// replace the call with.
461 Value *LowerBitSets::lowerBitSetCall(
462     CallInst *CI, BitSetInfo &BSI, ByteArrayInfo *&BAI,
463     Constant *CombinedGlobalIntAddr,
464     const DenseMap<GlobalObject *, uint64_t> &GlobalLayout) {
465   Value *Ptr = CI->getArgOperand(0);
466   const DataLayout &DL = M->getDataLayout();
467
468   if (BSI.containsValue(DL, GlobalLayout, Ptr))
469     return ConstantInt::getTrue(M->getContext());
470
471   Constant *OffsetedGlobalAsInt = ConstantExpr::getAdd(
472       CombinedGlobalIntAddr, ConstantInt::get(IntPtrTy, BSI.ByteOffset));
473
474   BasicBlock *InitialBB = CI->getParent();
475
476   IRBuilder<> B(CI);
477
478   Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
479
480   if (BSI.isSingleOffset())
481     return B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
482
483   Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
484
485   Value *BitOffset;
486   if (BSI.AlignLog2 == 0) {
487     BitOffset = PtrOffset;
488   } else {
489     // We need to check that the offset both falls within our range and is
490     // suitably aligned. We can check both properties at the same time by
491     // performing a right rotate by log2(alignment) followed by an integer
492     // comparison against the bitset size. The rotate will move the lower
493     // order bits that need to be zero into the higher order bits of the
494     // result, causing the comparison to fail if they are nonzero. The rotate
495     // also conveniently gives us a bit offset to use during the load from
496     // the bitset.
497     Value *OffsetSHR =
498         B.CreateLShr(PtrOffset, ConstantInt::get(IntPtrTy, BSI.AlignLog2));
499     Value *OffsetSHL = B.CreateShl(
500         PtrOffset,
501         ConstantInt::get(IntPtrTy, DL.getPointerSizeInBits(0) - BSI.AlignLog2));
502     BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
503   }
504
505   Constant *BitSizeConst = ConstantInt::get(IntPtrTy, BSI.BitSize);
506   Value *OffsetInRange = B.CreateICmpULT(BitOffset, BitSizeConst);
507
508   // If the bit set is all ones, testing against it is unnecessary.
509   if (BSI.isAllOnes())
510     return OffsetInRange;
511
512   TerminatorInst *Term = SplitBlockAndInsertIfThen(OffsetInRange, CI, false);
513   IRBuilder<> ThenB(Term);
514
515   // Now that we know that the offset is in range and aligned, load the
516   // appropriate bit from the bitset.
517   Value *Bit = createBitSetTest(ThenB, BSI, BAI, BitOffset);
518
519   // The value we want is 0 if we came directly from the initial block
520   // (having failed the range or alignment checks), or the loaded bit if
521   // we came from the block in which we loaded it.
522   B.SetInsertPoint(CI);
523   PHINode *P = B.CreatePHI(Int1Ty, 2);
524   P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
525   P->addIncoming(Bit, ThenB.GetInsertBlock());
526   return P;
527 }
528
529 /// Given a disjoint set of bitsets and globals, layout the globals, build the
530 /// bit sets and lower the llvm.bitset.test calls.
531 void LowerBitSets::buildBitSetsFromGlobalVariables(
532     ArrayRef<Metadata *> BitSets, ArrayRef<GlobalVariable *> Globals) {
533   // Build a new global with the combined contents of the referenced globals.
534   // This global is a struct whose even-indexed elements contain the original
535   // contents of the referenced globals and whose odd-indexed elements contain
536   // any padding required to align the next element to the next power of 2.
537   std::vector<Constant *> GlobalInits;
538   const DataLayout &DL = M->getDataLayout();
539   for (GlobalVariable *G : Globals) {
540     GlobalInits.push_back(G->getInitializer());
541     uint64_t InitSize = DL.getTypeAllocSize(G->getInitializer()->getType());
542
543     // Compute the amount of padding required.
544     uint64_t Padding = NextPowerOf2(InitSize - 1) - InitSize;
545
546     // Cap at 128 was found experimentally to have a good data/instruction
547     // overhead tradeoff.
548     if (Padding > 128)
549       Padding = RoundUpToAlignment(InitSize, 128) - InitSize;
550
551     GlobalInits.push_back(
552         ConstantAggregateZero::get(ArrayType::get(Int8Ty, Padding)));
553   }
554   if (!GlobalInits.empty())
555     GlobalInits.pop_back();
556   Constant *NewInit = ConstantStruct::getAnon(M->getContext(), GlobalInits);
557   auto CombinedGlobal =
558       new GlobalVariable(*M, NewInit->getType(), /*isConstant=*/true,
559                          GlobalValue::PrivateLinkage, NewInit);
560
561   const StructLayout *CombinedGlobalLayout =
562       DL.getStructLayout(cast<StructType>(NewInit->getType()));
563
564   // Compute the offsets of the original globals within the new global.
565   DenseMap<GlobalObject *, uint64_t> GlobalLayout;
566   for (unsigned I = 0; I != Globals.size(); ++I)
567     // Multiply by 2 to account for padding elements.
568     GlobalLayout[Globals[I]] = CombinedGlobalLayout->getElementOffset(I * 2);
569
570   lowerBitSetCalls(BitSets, CombinedGlobal, GlobalLayout);
571
572   // Build aliases pointing to offsets into the combined global for each
573   // global from which we built the combined global, and replace references
574   // to the original globals with references to the aliases.
575   for (unsigned I = 0; I != Globals.size(); ++I) {
576     // Multiply by 2 to account for padding elements.
577     Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
578                                       ConstantInt::get(Int32Ty, I * 2)};
579     Constant *CombinedGlobalElemPtr = ConstantExpr::getGetElementPtr(
580         NewInit->getType(), CombinedGlobal, CombinedGlobalIdxs);
581     if (LinkerSubsectionsViaSymbols) {
582       Globals[I]->replaceAllUsesWith(CombinedGlobalElemPtr);
583     } else {
584       GlobalAlias *GAlias =
585           GlobalAlias::create(Globals[I]->getType(), Globals[I]->getLinkage(),
586                               "", CombinedGlobalElemPtr, M);
587       GAlias->setVisibility(Globals[I]->getVisibility());
588       GAlias->takeName(Globals[I]);
589       Globals[I]->replaceAllUsesWith(GAlias);
590     }
591     Globals[I]->eraseFromParent();
592   }
593 }
594
595 void LowerBitSets::lowerBitSetCalls(
596     ArrayRef<Metadata *> BitSets, Constant *CombinedGlobalAddr,
597     const DenseMap<GlobalObject *, uint64_t> &GlobalLayout) {
598   Constant *CombinedGlobalIntAddr =
599       ConstantExpr::getPtrToInt(CombinedGlobalAddr, IntPtrTy);
600
601   // For each bitset in this disjoint set...
602   for (Metadata *BS : BitSets) {
603     // Build the bitset.
604     BitSetInfo BSI = buildBitSet(BS, GlobalLayout);
605     DEBUG({
606       if (auto BSS = dyn_cast<MDString>(BS))
607         dbgs() << BSS->getString() << ": ";
608       else
609         dbgs() << "<unnamed>: ";
610       BSI.print(dbgs());
611     });
612
613     ByteArrayInfo *BAI = 0;
614
615     // Lower each call to llvm.bitset.test for this bitset.
616     for (CallInst *CI : BitSetTestCallSites[BS]) {
617       ++NumBitSetCallsLowered;
618       Value *Lowered =
619           lowerBitSetCall(CI, BSI, BAI, CombinedGlobalIntAddr, GlobalLayout);
620       CI->replaceAllUsesWith(Lowered);
621       CI->eraseFromParent();
622     }
623   }
624 }
625
626 void LowerBitSets::verifyBitSetMDNode(MDNode *Op) {
627   if (Op->getNumOperands() != 3)
628     report_fatal_error(
629         "All operands of llvm.bitsets metadata must have 3 elements");
630   if (!Op->getOperand(1))
631     return;
632
633   auto OpConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(1));
634   if (!OpConstMD)
635     report_fatal_error("Bit set element must be a constant");
636   auto OpGlobal = dyn_cast<GlobalObject>(OpConstMD->getValue());
637   if (!OpGlobal)
638     return;
639
640   if (OpGlobal->isThreadLocal())
641     report_fatal_error("Bit set element may not be thread-local");
642   if (OpGlobal->hasSection())
643     report_fatal_error("Bit set element may not have an explicit section");
644
645   if (isa<GlobalVariable>(OpGlobal) && OpGlobal->isDeclarationForLinker())
646     report_fatal_error("Bit set global var element must be a definition");
647
648   auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(2));
649   if (!OffsetConstMD)
650     report_fatal_error("Bit set element offset must be a constant");
651   auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
652   if (!OffsetInt)
653     report_fatal_error("Bit set element offset must be an integer constant");
654 }
655
656 static const unsigned kX86JumpTableEntrySize = 8;
657
658 unsigned LowerBitSets::getJumpTableEntrySize() {
659   if (Arch != Triple::x86 && Arch != Triple::x86_64)
660     report_fatal_error("Unsupported architecture for jump tables");
661
662   return kX86JumpTableEntrySize;
663 }
664
665 // Create a constant representing a jump table entry for the target. This
666 // consists of an instruction sequence containing a relative branch to Dest. The
667 // constant will be laid out at address Src+(Len*Distance) where Len is the
668 // target-specific jump table entry size.
669 Constant *LowerBitSets::createJumpTableEntry(GlobalObject *Src, Function *Dest,
670                                              unsigned Distance) {
671   if (Arch != Triple::x86 && Arch != Triple::x86_64)
672     report_fatal_error("Unsupported architecture for jump tables");
673
674   const unsigned kJmpPCRel32Code = 0xe9;
675   const unsigned kInt3Code = 0xcc;
676
677   ConstantInt *Jmp = ConstantInt::get(Int8Ty, kJmpPCRel32Code);
678
679   // Build a constant representing the displacement between the constant's
680   // address and Dest. This will resolve to a PC32 relocation referring to Dest.
681   Constant *DestInt = ConstantExpr::getPtrToInt(Dest, IntPtrTy);
682   Constant *SrcInt = ConstantExpr::getPtrToInt(Src, IntPtrTy);
683   Constant *Disp = ConstantExpr::getSub(DestInt, SrcInt);
684   ConstantInt *DispOffset =
685       ConstantInt::get(IntPtrTy, Distance * kX86JumpTableEntrySize + 5);
686   Constant *OffsetedDisp = ConstantExpr::getSub(Disp, DispOffset);
687   OffsetedDisp = ConstantExpr::getTrunc(OffsetedDisp, Int32Ty);
688
689   ConstantInt *Int3 = ConstantInt::get(Int8Ty, kInt3Code);
690
691   Constant *Fields[] = {
692       Jmp, OffsetedDisp, Int3, Int3, Int3,
693   };
694   return ConstantStruct::getAnon(Fields, /*Packed=*/true);
695 }
696
697 Type *LowerBitSets::getJumpTableEntryType() {
698   if (Arch != Triple::x86 && Arch != Triple::x86_64)
699     report_fatal_error("Unsupported architecture for jump tables");
700
701   return StructType::get(M->getContext(),
702                          {Int8Ty, Int32Ty, Int8Ty, Int8Ty, Int8Ty},
703                          /*Packed=*/true);
704 }
705
706 /// Given a disjoint set of bitsets and functions, build a jump table for the
707 /// functions, build the bit sets and lower the llvm.bitset.test calls.
708 void LowerBitSets::buildBitSetsFromFunctions(ArrayRef<Metadata *> BitSets,
709                                              ArrayRef<Function *> Functions) {
710   // Unlike the global bitset builder, the function bitset builder cannot
711   // re-arrange functions in a particular order and base its calculations on the
712   // layout of the functions' entry points, as we have no idea how large a
713   // particular function will end up being (the size could even depend on what
714   // this pass does!) Instead, we build a jump table, which is a block of code
715   // consisting of one branch instruction for each of the functions in the bit
716   // set that branches to the target function, and redirect any taken function
717   // addresses to the corresponding jump table entry. In the object file's
718   // symbol table, the symbols for the target functions also refer to the jump
719   // table entries, so that addresses taken outside the module will pass any
720   // verification done inside the module.
721   //
722   // In more concrete terms, suppose we have three functions f, g, h which are
723   // members of a single bitset, and a function foo that returns their
724   // addresses:
725   //
726   // f:
727   // mov 0, %eax
728   // ret
729   //
730   // g:
731   // mov 1, %eax
732   // ret
733   //
734   // h:
735   // mov 2, %eax
736   // ret
737   //
738   // foo:
739   // mov f, %eax
740   // mov g, %edx
741   // mov h, %ecx
742   // ret
743   //
744   // To create a jump table for these functions, we instruct the LLVM code
745   // generator to output a jump table in the .text section. This is done by
746   // representing the instructions in the jump table as an LLVM constant and
747   // placing them in a global variable in the .text section. The end result will
748   // (conceptually) look like this:
749   //
750   // f:
751   // jmp .Ltmp0 ; 5 bytes
752   // int3       ; 1 byte
753   // int3       ; 1 byte
754   // int3       ; 1 byte
755   //
756   // g:
757   // jmp .Ltmp1 ; 5 bytes
758   // int3       ; 1 byte
759   // int3       ; 1 byte
760   // int3       ; 1 byte
761   //
762   // h:
763   // jmp .Ltmp2 ; 5 bytes
764   // int3       ; 1 byte
765   // int3       ; 1 byte
766   // int3       ; 1 byte
767   //
768   // .Ltmp0:
769   // mov 0, %eax
770   // ret
771   //
772   // .Ltmp1:
773   // mov 1, %eax
774   // ret
775   //
776   // .Ltmp2:
777   // mov 2, %eax
778   // ret
779   //
780   // foo:
781   // mov f, %eax
782   // mov g, %edx
783   // mov h, %ecx
784   // ret
785   //
786   // Because the addresses of f, g, h are evenly spaced at a power of 2, in the
787   // normal case the check can be carried out using the same kind of simple
788   // arithmetic that we normally use for globals.
789
790   assert(!Functions.empty());
791
792   // Build a simple layout based on the regular layout of jump tables.
793   DenseMap<GlobalObject *, uint64_t> GlobalLayout;
794   unsigned EntrySize = getJumpTableEntrySize();
795   for (unsigned I = 0; I != Functions.size(); ++I)
796     GlobalLayout[Functions[I]] = I * EntrySize;
797
798   // Create a constant to hold the jump table.
799   ArrayType *JumpTableType =
800       ArrayType::get(getJumpTableEntryType(), Functions.size());
801   auto JumpTable = new GlobalVariable(*M, JumpTableType,
802                                       /*isConstant=*/true,
803                                       GlobalValue::PrivateLinkage, nullptr);
804   JumpTable->setSection(ObjectFormat == Triple::MachO
805                             ? "__TEXT,__text,regular,pure_instructions"
806                             : ".text");
807   lowerBitSetCalls(BitSets, JumpTable, GlobalLayout);
808
809   // Build aliases pointing to offsets into the jump table, and replace
810   // references to the original functions with references to the aliases.
811   for (unsigned I = 0; I != Functions.size(); ++I) {
812     Constant *CombinedGlobalElemPtr = ConstantExpr::getBitCast(
813         ConstantExpr::getGetElementPtr(
814             JumpTableType, JumpTable,
815             ArrayRef<Constant *>{ConstantInt::get(IntPtrTy, 0),
816                                  ConstantInt::get(IntPtrTy, I)}),
817         Functions[I]->getType());
818     if (LinkerSubsectionsViaSymbols || Functions[I]->isDeclarationForLinker()) {
819       Functions[I]->replaceAllUsesWith(CombinedGlobalElemPtr);
820     } else {
821       GlobalAlias *GAlias = GlobalAlias::create(Functions[I]->getType(),
822                                                 Functions[I]->getLinkage(), "",
823                                                 CombinedGlobalElemPtr, M);
824       GAlias->setVisibility(Functions[I]->getVisibility());
825       GAlias->takeName(Functions[I]);
826       Functions[I]->replaceAllUsesWith(GAlias);
827     }
828     if (!Functions[I]->isDeclarationForLinker())
829       Functions[I]->setLinkage(GlobalValue::PrivateLinkage);
830   }
831
832   // Build and set the jump table's initializer.
833   std::vector<Constant *> JumpTableEntries;
834   for (unsigned I = 0; I != Functions.size(); ++I)
835     JumpTableEntries.push_back(
836         createJumpTableEntry(JumpTable, Functions[I], I));
837   JumpTable->setInitializer(
838       ConstantArray::get(JumpTableType, JumpTableEntries));
839 }
840
841 void LowerBitSets::buildBitSetsFromDisjointSet(
842     ArrayRef<Metadata *> BitSets, ArrayRef<GlobalObject *> Globals) {
843   llvm::DenseMap<Metadata *, uint64_t> BitSetIndices;
844   llvm::DenseMap<GlobalObject *, uint64_t> GlobalIndices;
845   for (unsigned I = 0; I != BitSets.size(); ++I)
846     BitSetIndices[BitSets[I]] = I;
847   for (unsigned I = 0; I != Globals.size(); ++I)
848     GlobalIndices[Globals[I]] = I;
849
850   // For each bitset, build a set of indices that refer to globals referenced by
851   // the bitset.
852   std::vector<std::set<uint64_t>> BitSetMembers(BitSets.size());
853   if (BitSetNM) {
854     for (MDNode *Op : BitSetNM->operands()) {
855       // Op = { bitset name, global, offset }
856       if (!Op->getOperand(1))
857         continue;
858       auto I = BitSetIndices.find(Op->getOperand(0));
859       if (I == BitSetIndices.end())
860         continue;
861
862       auto OpGlobal = dyn_cast<GlobalObject>(
863           cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
864       if (!OpGlobal)
865         continue;
866       BitSetMembers[I->second].insert(GlobalIndices[OpGlobal]);
867     }
868   }
869
870   // Order the sets of indices by size. The GlobalLayoutBuilder works best
871   // when given small index sets first.
872   std::stable_sort(
873       BitSetMembers.begin(), BitSetMembers.end(),
874       [](const std::set<uint64_t> &O1, const std::set<uint64_t> &O2) {
875         return O1.size() < O2.size();
876       });
877
878   // Create a GlobalLayoutBuilder and provide it with index sets as layout
879   // fragments. The GlobalLayoutBuilder tries to lay out members of fragments as
880   // close together as possible.
881   GlobalLayoutBuilder GLB(Globals.size());
882   for (auto &&MemSet : BitSetMembers)
883     GLB.addFragment(MemSet);
884
885   // Build the bitsets from this disjoint set.
886   if (Globals.empty() || isa<GlobalVariable>(Globals[0])) {
887     // Build a vector of global variables with the computed layout.
888     std::vector<GlobalVariable *> OrderedGVs(Globals.size());
889     auto OGI = OrderedGVs.begin();
890     for (auto &&F : GLB.Fragments) {
891       for (auto &&Offset : F) {
892         auto GV = dyn_cast<GlobalVariable>(Globals[Offset]);
893         if (!GV)
894           report_fatal_error(
895               "Bit set may not contain both global variables and functions");
896         *OGI++ = GV;
897       }
898     }
899
900     buildBitSetsFromGlobalVariables(BitSets, OrderedGVs);
901   } else {
902     // Build a vector of functions with the computed layout.
903     std::vector<Function *> OrderedFns(Globals.size());
904     auto OFI = OrderedFns.begin();
905     for (auto &&F : GLB.Fragments) {
906       for (auto &&Offset : F) {
907         auto Fn = dyn_cast<Function>(Globals[Offset]);
908         if (!Fn)
909           report_fatal_error(
910               "Bit set may not contain both global variables and functions");
911         *OFI++ = Fn;
912       }
913     }
914
915     buildBitSetsFromFunctions(BitSets, OrderedFns);
916   }
917 }
918
919 /// Lower all bit sets in this module.
920 bool LowerBitSets::buildBitSets() {
921   Function *BitSetTestFunc =
922       M->getFunction(Intrinsic::getName(Intrinsic::bitset_test));
923   if (!BitSetTestFunc)
924     return false;
925
926   // Equivalence class set containing bitsets and the globals they reference.
927   // This is used to partition the set of bitsets in the module into disjoint
928   // sets.
929   typedef EquivalenceClasses<PointerUnion<GlobalObject *, Metadata *>>
930       GlobalClassesTy;
931   GlobalClassesTy GlobalClasses;
932
933   // Verify the bitset metadata and build a mapping from bitset identifiers to
934   // their last observed index in BitSetNM. This will used later to
935   // deterministically order the list of bitset identifiers.
936   llvm::DenseMap<Metadata *, unsigned> BitSetIdIndices;
937   if (BitSetNM) {
938     for (unsigned I = 0, E = BitSetNM->getNumOperands(); I != E; ++I) {
939       MDNode *Op = BitSetNM->getOperand(I);
940       verifyBitSetMDNode(Op);
941       BitSetIdIndices[Op->getOperand(0)] = I;
942     }
943   }
944
945   for (const Use &U : BitSetTestFunc->uses()) {
946     auto CI = cast<CallInst>(U.getUser());
947
948     auto BitSetMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
949     if (!BitSetMDVal)
950       report_fatal_error(
951           "Second argument of llvm.bitset.test must be metadata");
952     auto BitSet = BitSetMDVal->getMetadata();
953
954     // Add the call site to the list of call sites for this bit set. We also use
955     // BitSetTestCallSites to keep track of whether we have seen this bit set
956     // before. If we have, we don't need to re-add the referenced globals to the
957     // equivalence class.
958     std::pair<DenseMap<Metadata *, std::vector<CallInst *>>::iterator,
959               bool> Ins =
960         BitSetTestCallSites.insert(
961             std::make_pair(BitSet, std::vector<CallInst *>()));
962     Ins.first->second.push_back(CI);
963     if (!Ins.second)
964       continue;
965
966     // Add the bitset to the equivalence class.
967     GlobalClassesTy::iterator GCI = GlobalClasses.insert(BitSet);
968     GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
969
970     if (!BitSetNM)
971       continue;
972
973     // Add the referenced globals to the bitset's equivalence class.
974     for (MDNode *Op : BitSetNM->operands()) {
975       if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
976         continue;
977
978       auto OpGlobal = dyn_cast<GlobalObject>(
979           cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
980       if (!OpGlobal)
981         continue;
982
983       CurSet = GlobalClasses.unionSets(
984           CurSet, GlobalClasses.findLeader(GlobalClasses.insert(OpGlobal)));
985     }
986   }
987
988   if (GlobalClasses.empty())
989     return false;
990
991   // Build a list of disjoint sets ordered by their maximum BitSetNM index
992   // for determinism.
993   std::vector<std::pair<GlobalClassesTy::iterator, unsigned>> Sets;
994   for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
995                                  E = GlobalClasses.end();
996        I != E; ++I) {
997     if (!I->isLeader()) continue;
998     ++NumBitSetDisjointSets;
999
1000     unsigned MaxIndex = 0;
1001     for (GlobalClassesTy::member_iterator MI = GlobalClasses.member_begin(I);
1002          MI != GlobalClasses.member_end(); ++MI) {
1003       if ((*MI).is<Metadata *>())
1004         MaxIndex = std::max(MaxIndex, BitSetIdIndices[MI->get<Metadata *>()]);
1005     }
1006     Sets.emplace_back(I, MaxIndex);
1007   }
1008   std::sort(Sets.begin(), Sets.end(),
1009             [](const std::pair<GlobalClassesTy::iterator, unsigned> &S1,
1010                const std::pair<GlobalClassesTy::iterator, unsigned> &S2) {
1011               return S1.second < S2.second;
1012             });
1013
1014   // For each disjoint set we found...
1015   for (const auto &S : Sets) {
1016     // Build the list of bitsets in this disjoint set.
1017     std::vector<Metadata *> BitSets;
1018     std::vector<GlobalObject *> Globals;
1019     for (GlobalClassesTy::member_iterator MI =
1020              GlobalClasses.member_begin(S.first);
1021          MI != GlobalClasses.member_end(); ++MI) {
1022       if ((*MI).is<Metadata *>())
1023         BitSets.push_back(MI->get<Metadata *>());
1024       else
1025         Globals.push_back(MI->get<GlobalObject *>());
1026     }
1027
1028     // Order bitsets by BitSetNM index for determinism. This ordering is stable
1029     // as there is a one-to-one mapping between metadata and indices.
1030     std::sort(BitSets.begin(), BitSets.end(), [&](Metadata *M1, Metadata *M2) {
1031       return BitSetIdIndices[M1] < BitSetIdIndices[M2];
1032     });
1033
1034     // Lower the bitsets in this disjoint set.
1035     buildBitSetsFromDisjointSet(BitSets, Globals);
1036   }
1037
1038   allocateByteArrays();
1039
1040   return true;
1041 }
1042
1043 bool LowerBitSets::eraseBitSetMetadata() {
1044   if (!BitSetNM)
1045     return false;
1046
1047   M->eraseNamedMetadata(BitSetNM);
1048   return true;
1049 }
1050
1051 bool LowerBitSets::runOnModule(Module &M) {
1052   bool Changed = buildBitSets();
1053   Changed |= eraseBitSetMetadata();
1054   return Changed;
1055 }