blob: 78981fdedad7560170658f5194719d987a80aaeb [file] [log] [blame]
Peter Collingbournee6909c82015-02-20 20:30:47 +00001//===-- 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"
Peter Collingbournec9f277f2015-03-14 00:00:49 +000019#include "llvm/ADT/Triple.h"
Peter Collingbournee6909c82015-02-20 20:30:47 +000020#include "llvm/IR/Constant.h"
21#include "llvm/IR/Constants.h"
Peter Collingbourne8d24ae92015-09-08 22:49:35 +000022#include "llvm/IR/Function.h"
23#include "llvm/IR/GlobalObject.h"
Peter Collingbournee6909c82015-02-20 20:30:47 +000024#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"
Peter Collingbourne3eddf492015-07-29 18:12:36 +000031#include "llvm/Support/Debug.h"
32#include "llvm/Support/raw_ostream.h"
Peter Collingbournee6909c82015-02-20 20:30:47 +000033#include "llvm/Transforms/Utils/BasicBlockUtils.h"
34
35using namespace llvm;
Peter Collingbournedd711b92016-04-01 18:46:50 +000036using namespace lowerbitsets;
Peter Collingbournee6909c82015-02-20 20:30:47 +000037
38#define DEBUG_TYPE "lowerbitsets"
39
Peter Collingbourneda2dbf22015-03-03 00:49:28 +000040STATISTIC(ByteArraySizeBits, "Byte array size in bits");
41STATISTIC(ByteArraySizeBytes, "Byte array size in bytes");
42STATISTIC(NumByteArraysCreated, "Number of byte arrays created");
Peter Collingbournee6909c82015-02-20 20:30:47 +000043STATISTIC(NumBitSetCallsLowered, "Number of bitset calls lowered");
44STATISTIC(NumBitSetDisjointSets, "Number of disjoint sets of bitsets");
45
Peter Collingbourne994ba3d2015-03-19 22:02:10 +000046static cl::opt<bool> AvoidReuse(
47 "lowerbitsets-avoid-reuse",
48 cl::desc("Try to avoid reuse of byte array addresses using aliases"),
49 cl::Hidden, cl::init(true));
50
Peter Collingbournee6909c82015-02-20 20:30:47 +000051bool BitSetInfo::containsGlobalOffset(uint64_t Offset) const {
52 if (Offset < ByteOffset)
53 return false;
54
55 if ((Offset - ByteOffset) % (uint64_t(1) << AlignLog2) != 0)
56 return false;
57
58 uint64_t BitOffset = (Offset - ByteOffset) >> AlignLog2;
59 if (BitOffset >= BitSize)
60 return false;
61
Peter Collingbourneda2dbf22015-03-03 00:49:28 +000062 return Bits.count(BitOffset);
Peter Collingbournee6909c82015-02-20 20:30:47 +000063}
64
65bool BitSetInfo::containsValue(
Mehdi Aminia28d91d2015-03-10 02:37:25 +000066 const DataLayout &DL,
Peter Collingbourne8d24ae92015-09-08 22:49:35 +000067 const DenseMap<GlobalObject *, uint64_t> &GlobalLayout, Value *V,
Peter Collingbournee6909c82015-02-20 20:30:47 +000068 uint64_t COffset) const {
Peter Collingbourne8d24ae92015-09-08 22:49:35 +000069 if (auto GV = dyn_cast<GlobalObject>(V)) {
Peter Collingbournee6909c82015-02-20 20:30:47 +000070 auto I = GlobalLayout.find(GV);
71 if (I == GlobalLayout.end())
72 return false;
73 return containsGlobalOffset(I->second + COffset);
74 }
75
76 if (auto GEP = dyn_cast<GEPOperator>(V)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000077 APInt APOffset(DL.getPointerSizeInBits(0), 0);
78 bool Result = GEP->accumulateConstantOffset(DL, APOffset);
Peter Collingbournee6909c82015-02-20 20:30:47 +000079 if (!Result)
80 return false;
81 COffset += APOffset.getZExtValue();
82 return containsValue(DL, GlobalLayout, GEP->getPointerOperand(),
83 COffset);
84 }
85
86 if (auto Op = dyn_cast<Operator>(V)) {
87 if (Op->getOpcode() == Instruction::BitCast)
88 return containsValue(DL, GlobalLayout, Op->getOperand(0), COffset);
89
90 if (Op->getOpcode() == Instruction::Select)
91 return containsValue(DL, GlobalLayout, Op->getOperand(1), COffset) &&
92 containsValue(DL, GlobalLayout, Op->getOperand(2), COffset);
93 }
94
95 return false;
96}
97
Peter Collingbourne3eddf492015-07-29 18:12:36 +000098void BitSetInfo::print(raw_ostream &OS) const {
99 OS << "offset " << ByteOffset << " size " << BitSize << " align "
100 << (1 << AlignLog2);
101
102 if (isAllOnes()) {
103 OS << " all-ones\n";
104 return;
105 }
106
107 OS << " { ";
108 for (uint64_t B : Bits)
109 OS << B << ' ';
110 OS << "}\n";
Peter Collingbourne3eddf492015-07-29 18:12:36 +0000111}
112
Peter Collingbournee6909c82015-02-20 20:30:47 +0000113BitSetInfo 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;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000132 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;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000138 for (uint64_t Offset : Offsets) {
139 Offset >>= BSI.AlignLog2;
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000140 BSI.Bits.insert(Offset);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000141 }
142
143 return BSI;
144}
145
Peter Collingbourne1baeaa32015-02-24 23:17:02 +0000146void 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
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000175void 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
Peter Collingbournee6909c82015-02-20 20:30:47 +0000198namespace {
199
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000200struct ByteArrayInfo {
201 std::set<uint64_t> Bits;
202 uint64_t BitSize;
203 GlobalVariable *ByteArray;
204 Constant *Mask;
205};
206
Peter Collingbournee6909c82015-02-20 20:30:47 +0000207struct LowerBitSets : public ModulePass {
208 static char ID;
209 LowerBitSets() : ModulePass(ID) {
210 initializeLowerBitSetsPass(*PassRegistry::getPassRegistry());
211 }
212
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000213 Module *M;
214
Peter Collingbournec9f277f2015-03-14 00:00:49 +0000215 bool LinkerSubsectionsViaSymbols;
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000216 Triple::ArchType Arch;
217 Triple::ObjectFormatType ObjectFormat;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000218 IntegerType *Int1Ty;
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000219 IntegerType *Int8Ty;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000220 IntegerType *Int32Ty;
221 Type *Int32PtrTy;
222 IntegerType *Int64Ty;
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000223 IntegerType *IntPtrTy;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000224
225 // The llvm.bitsets named metadata.
226 NamedMDNode *BitSetNM;
227
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000228 // Mapping from bitset identifiers to the call sites that test them.
229 DenseMap<Metadata *, std::vector<CallInst *>> BitSetTestCallSites;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000230
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000231 std::vector<ByteArrayInfo> ByteArrayInfos;
232
Peter Collingbournee6909c82015-02-20 20:30:47 +0000233 BitSetInfo
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000234 buildBitSet(Metadata *BitSet,
235 const DenseMap<GlobalObject *, uint64_t> &GlobalLayout);
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000236 ByteArrayInfo *createByteArray(BitSetInfo &BSI);
237 void allocateByteArrays();
238 Value *createBitSetTest(IRBuilder<> &B, BitSetInfo &BSI, ByteArrayInfo *&BAI,
239 Value *BitOffset);
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000240 void lowerBitSetCalls(ArrayRef<Metadata *> BitSets,
241 Constant *CombinedGlobalAddr,
242 const DenseMap<GlobalObject *, uint64_t> &GlobalLayout);
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000243 Value *
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000244 lowerBitSetCall(CallInst *CI, BitSetInfo &BSI, ByteArrayInfo *&BAI,
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000245 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);
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000258 bool buildBitSets();
259 bool eraseBitSetMetadata();
Peter Collingbournee6909c82015-02-20 20:30:47 +0000260
261 bool doInitialization(Module &M) override;
262 bool runOnModule(Module &M) override;
263};
264
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000265} // anonymous namespace
Peter Collingbournee6909c82015-02-20 20:30:47 +0000266
267INITIALIZE_PASS_BEGIN(LowerBitSets, "lowerbitsets",
268 "Lower bitset metadata", false, false)
269INITIALIZE_PASS_END(LowerBitSets, "lowerbitsets",
270 "Lower bitset metadata", false, false)
271char LowerBitSets::ID = 0;
272
273ModulePass *llvm::createLowerBitSetsPass() { return new LowerBitSets; }
274
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000275bool LowerBitSets::doInitialization(Module &Mod) {
276 M = &Mod;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000277 const DataLayout &DL = Mod.getDataLayout();
Peter Collingbournee6909c82015-02-20 20:30:47 +0000278
Peter Collingbournec9f277f2015-03-14 00:00:49 +0000279 Triple TargetTriple(M->getTargetTriple());
280 LinkerSubsectionsViaSymbols = TargetTriple.isMacOSX();
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000281 Arch = TargetTriple.getArch();
282 ObjectFormat = TargetTriple.getObjectFormat();
Peter Collingbournec9f277f2015-03-14 00:00:49 +0000283
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000284 Int1Ty = Type::getInt1Ty(M->getContext());
285 Int8Ty = Type::getInt8Ty(M->getContext());
286 Int32Ty = Type::getInt32Ty(M->getContext());
Peter Collingbournee6909c82015-02-20 20:30:47 +0000287 Int32PtrTy = PointerType::getUnqual(Int32Ty);
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000288 Int64Ty = Type::getInt64Ty(M->getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000289 IntPtrTy = DL.getIntPtrType(M->getContext(), 0);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000290
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000291 BitSetNM = M->getNamedMetadata("llvm.bitsets");
Peter Collingbournee6909c82015-02-20 20:30:47 +0000292
293 BitSetTestCallSites.clear();
294
295 return false;
296}
297
NAKAMURA Takumi6c246842015-02-22 09:51:42 +0000298/// Build a bit set for BitSet using the object layouts in
299/// GlobalLayout.
Peter Collingbournee6909c82015-02-20 20:30:47 +0000300BitSetInfo LowerBitSets::buildBitSet(
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000301 Metadata *BitSet,
302 const DenseMap<GlobalObject *, uint64_t> &GlobalLayout) {
Peter Collingbournee6909c82015-02-20 20:30:47 +0000303 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;
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000310 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);
Peter Collingbourneba4c8b52015-06-27 00:17:51 +0000315 if (!OpGlobal)
316 continue;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000317 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
NAKAMURA Takumi6c246842015-02-22 09:51:42 +0000330/// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
331/// Bits. This pattern matches to the bt instruction on x86.
Peter Collingbournee6909c82015-02-20 20:30:47 +0000332static 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
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000345ByteArrayInfo *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
364void 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])};
David Blaikie4a2e73b2015-04-02 18:55:32 +0000393 Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(
394 ByteArrayConst->getType(), ByteArray, Idxs);
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000395
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.
Peter Collingbournead0bdcd2015-03-16 23:36:24 +0000399 if (LinkerSubsectionsViaSymbols) {
400 BAI->ByteArray->replaceAllUsesWith(GEP);
401 } else {
David Blaikie16a2f3e2015-09-14 18:01:59 +0000402 GlobalAlias *Alias = GlobalAlias::create(
403 Int8Ty, 0, GlobalValue::PrivateLinkage, "bits", GEP, M);
Peter Collingbournead0bdcd2015-03-16 23:36:24 +0000404 BAI->ByteArray->replaceAllUsesWith(Alias);
405 }
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000406 BAI->ByteArray->eraseFromParent();
407 }
408
409 ByteArraySizeBits = BAB.BitAllocs[0] + BAB.BitAllocs[1] + BAB.BitAllocs[2] +
410 BAB.BitAllocs[3] + BAB.BitAllocs[4] + BAB.BitAllocs[5] +
411 BAB.BitAllocs[6] + BAB.BitAllocs[7];
412 ByteArraySizeBytes = BAB.Bytes.size();
413}
414
NAKAMURA Takumi6c246842015-02-22 09:51:42 +0000415/// Build a test that bit BitOffset is set in BSI, where
416/// BitSetGlobal is a global containing the bits in BSI.
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000417Value *LowerBitSets::createBitSetTest(IRBuilder<> &B, BitSetInfo &BSI,
418 ByteArrayInfo *&BAI, Value *BitOffset) {
419 if (BSI.BitSize <= 64) {
Peter Collingbournee6909c82015-02-20 20:30:47 +0000420 // If the bit set is sufficiently small, we can avoid a load by bit testing
421 // a constant.
422 IntegerType *BitsTy;
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000423 if (BSI.BitSize <= 32)
Peter Collingbournee6909c82015-02-20 20:30:47 +0000424 BitsTy = Int32Ty;
425 else
426 BitsTy = Int64Ty;
427
428 uint64_t Bits = 0;
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000429 for (auto Bit : BSI.Bits)
430 Bits |= uint64_t(1) << Bit;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000431 Constant *BitsConst = ConstantInt::get(BitsTy, Bits);
432 return createMaskedBitTest(B, BitsConst, BitOffset);
433 } else {
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000434 if (!BAI) {
435 ++NumByteArraysCreated;
436 BAI = createByteArray(BSI);
437 }
Peter Collingbournee6909c82015-02-20 20:30:47 +0000438
Peter Collingbourne994ba3d2015-03-19 22:02:10 +0000439 Constant *ByteArray = BAI->ByteArray;
David Blaikie93c54442015-04-03 19:41:44 +0000440 Type *Ty = BAI->ByteArray->getValueType();
Peter Collingbourne994ba3d2015-03-19 22:02:10 +0000441 if (!LinkerSubsectionsViaSymbols && AvoidReuse) {
442 // Each use of the byte array uses a different alias. This makes the
443 // backend less likely to reuse previously computed byte array addresses,
444 // improving the security of the CFI mechanism based on this pass.
David Blaikie16a2f3e2015-09-14 18:01:59 +0000445 ByteArray = GlobalAlias::create(BAI->ByteArray->getValueType(), 0,
David Blaikie93c54442015-04-03 19:41:44 +0000446 GlobalValue::PrivateLinkage, "bits_use",
447 ByteArray, M);
Peter Collingbourne994ba3d2015-03-19 22:02:10 +0000448 }
449
David Blaikie93c54442015-04-03 19:41:44 +0000450 Value *ByteAddr = B.CreateGEP(Ty, ByteArray, BitOffset);
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000451 Value *Byte = B.CreateLoad(ByteAddr);
452
453 Value *ByteAndMask = B.CreateAnd(Byte, BAI->Mask);
454 return B.CreateICmpNE(ByteAndMask, ConstantInt::get(Int8Ty, 0));
Peter Collingbournee6909c82015-02-20 20:30:47 +0000455 }
456}
457
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000458/// Lower a llvm.bitset.test call to its implementation. Returns the value to
459/// replace the call with.
460Value *LowerBitSets::lowerBitSetCall(
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000461 CallInst *CI, BitSetInfo &BSI, ByteArrayInfo *&BAI,
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000462 Constant *CombinedGlobalIntAddr,
463 const DenseMap<GlobalObject *, uint64_t> &GlobalLayout) {
Peter Collingbournee6909c82015-02-20 20:30:47 +0000464 Value *Ptr = CI->getArgOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000465 const DataLayout &DL = M->getDataLayout();
Peter Collingbournee6909c82015-02-20 20:30:47 +0000466
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000467 if (BSI.containsValue(DL, GlobalLayout, Ptr))
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000468 return ConstantInt::getTrue(M->getContext());
Peter Collingbournee6909c82015-02-20 20:30:47 +0000469
Peter Collingbournee6909c82015-02-20 20:30:47 +0000470 Constant *OffsetedGlobalAsInt = ConstantExpr::getAdd(
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000471 CombinedGlobalIntAddr, ConstantInt::get(IntPtrTy, BSI.ByteOffset));
Peter Collingbournee6909c82015-02-20 20:30:47 +0000472
473 BasicBlock *InitialBB = CI->getParent();
474
475 IRBuilder<> B(CI);
476
477 Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
478
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000479 if (BSI.isSingleOffset())
480 return B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000481
482 Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
483
484 Value *BitOffset;
485 if (BSI.AlignLog2 == 0) {
486 BitOffset = PtrOffset;
487 } else {
488 // We need to check that the offset both falls within our range and is
489 // suitably aligned. We can check both properties at the same time by
490 // performing a right rotate by log2(alignment) followed by an integer
491 // comparison against the bitset size. The rotate will move the lower
492 // order bits that need to be zero into the higher order bits of the
493 // result, causing the comparison to fail if they are nonzero. The rotate
494 // also conveniently gives us a bit offset to use during the load from
495 // the bitset.
496 Value *OffsetSHR =
497 B.CreateLShr(PtrOffset, ConstantInt::get(IntPtrTy, BSI.AlignLog2));
498 Value *OffsetSHL = B.CreateShl(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000499 PtrOffset,
500 ConstantInt::get(IntPtrTy, DL.getPointerSizeInBits(0) - BSI.AlignLog2));
Peter Collingbournee6909c82015-02-20 20:30:47 +0000501 BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
502 }
503
504 Constant *BitSizeConst = ConstantInt::get(IntPtrTy, BSI.BitSize);
505 Value *OffsetInRange = B.CreateICmpULT(BitOffset, BitSizeConst);
506
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000507 // If the bit set is all ones, testing against it is unnecessary.
508 if (BSI.isAllOnes())
509 return OffsetInRange;
510
Peter Collingbournee6909c82015-02-20 20:30:47 +0000511 TerminatorInst *Term = SplitBlockAndInsertIfThen(OffsetInRange, CI, false);
512 IRBuilder<> ThenB(Term);
513
514 // Now that we know that the offset is in range and aligned, load the
515 // appropriate bit from the bitset.
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000516 Value *Bit = createBitSetTest(ThenB, BSI, BAI, BitOffset);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000517
518 // The value we want is 0 if we came directly from the initial block
519 // (having failed the range or alignment checks), or the loaded bit if
520 // we came from the block in which we loaded it.
521 B.SetInsertPoint(CI);
522 PHINode *P = B.CreatePHI(Int1Ty, 2);
523 P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
524 P->addIncoming(Bit, ThenB.GetInsertBlock());
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000525 return P;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000526}
527
528/// Given a disjoint set of bitsets and globals, layout the globals, build the
529/// bit sets and lower the llvm.bitset.test calls.
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000530void LowerBitSets::buildBitSetsFromGlobalVariables(
531 ArrayRef<Metadata *> BitSets, ArrayRef<GlobalVariable *> Globals) {
Peter Collingbournee6909c82015-02-20 20:30:47 +0000532 // Build a new global with the combined contents of the referenced globals.
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000533 // This global is a struct whose even-indexed elements contain the original
534 // contents of the referenced globals and whose odd-indexed elements contain
535 // any padding required to align the next element to the next power of 2.
Peter Collingbournee6909c82015-02-20 20:30:47 +0000536 std::vector<Constant *> GlobalInits;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000537 const DataLayout &DL = M->getDataLayout();
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000538 for (GlobalVariable *G : Globals) {
Peter Collingbournee6909c82015-02-20 20:30:47 +0000539 GlobalInits.push_back(G->getInitializer());
David Blaikie6614d8d2015-09-14 20:29:26 +0000540 uint64_t InitSize = DL.getTypeAllocSize(G->getValueType());
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000541
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000542 // Compute the amount of padding required.
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000543 uint64_t Padding = NextPowerOf2(InitSize - 1) - InitSize;
544
545 // Cap at 128 was found experimentally to have a good data/instruction
546 // overhead tradeoff.
547 if (Padding > 128)
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000548 Padding = alignTo(InitSize, 128) - InitSize;
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000549
550 GlobalInits.push_back(
551 ConstantAggregateZero::get(ArrayType::get(Int8Ty, Padding)));
552 }
553 if (!GlobalInits.empty())
554 GlobalInits.pop_back();
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000555 Constant *NewInit = ConstantStruct::getAnon(M->getContext(), GlobalInits);
David Blaikie6614d8d2015-09-14 20:29:26 +0000556 auto *CombinedGlobal =
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000557 new GlobalVariable(*M, NewInit->getType(), /*isConstant=*/true,
Peter Collingbournee6909c82015-02-20 20:30:47 +0000558 GlobalValue::PrivateLinkage, NewInit);
559
David Blaikie6614d8d2015-09-14 20:29:26 +0000560 StructType *NewTy = cast<StructType>(NewInit->getType());
561 const StructLayout *CombinedGlobalLayout = DL.getStructLayout(NewTy);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000562
563 // Compute the offsets of the original globals within the new global.
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000564 DenseMap<GlobalObject *, uint64_t> GlobalLayout;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000565 for (unsigned I = 0; I != Globals.size(); ++I)
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000566 // Multiply by 2 to account for padding elements.
567 GlobalLayout[Globals[I]] = CombinedGlobalLayout->getElementOffset(I * 2);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000568
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000569 lowerBitSetCalls(BitSets, CombinedGlobal, GlobalLayout);
Peter Collingbournee6909c82015-02-20 20:30:47 +0000570
571 // Build aliases pointing to offsets into the combined global for each
572 // global from which we built the combined global, and replace references
573 // to the original globals with references to the aliases.
574 for (unsigned I = 0; I != Globals.size(); ++I) {
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000575 // Multiply by 2 to account for padding elements.
Peter Collingbournee6909c82015-02-20 20:30:47 +0000576 Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
Peter Collingbourneeba7f732015-02-25 20:42:41 +0000577 ConstantInt::get(Int32Ty, I * 2)};
David Blaikie4a2e73b2015-04-02 18:55:32 +0000578 Constant *CombinedGlobalElemPtr = ConstantExpr::getGetElementPtr(
579 NewInit->getType(), CombinedGlobal, CombinedGlobalIdxs);
Peter Collingbournead0bdcd2015-03-16 23:36:24 +0000580 if (LinkerSubsectionsViaSymbols) {
581 Globals[I]->replaceAllUsesWith(CombinedGlobalElemPtr);
582 } else {
David Blaikie6614d8d2015-09-14 20:29:26 +0000583 assert(Globals[I]->getType()->getAddressSpace() == 0);
584 GlobalAlias *GAlias = GlobalAlias::create(NewTy->getElementType(I * 2), 0,
585 Globals[I]->getLinkage(), "",
586 CombinedGlobalElemPtr, M);
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000587 GAlias->setVisibility(Globals[I]->getVisibility());
Peter Collingbourne4fc603d2015-06-17 18:31:02 +0000588 GAlias->takeName(Globals[I]);
Peter Collingbournead0bdcd2015-03-16 23:36:24 +0000589 Globals[I]->replaceAllUsesWith(GAlias);
590 }
Peter Collingbournee6909c82015-02-20 20:30:47 +0000591 Globals[I]->eraseFromParent();
592 }
593}
594
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000595void 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
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000613 ByteArrayInfo *BAI = nullptr;
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000614
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
626void 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");
Evgeniy Stepanov40cd1512016-04-15 22:55:38 +0000642 if (isa<GlobalVariable>(OpGlobal) && OpGlobal->hasSection())
643 report_fatal_error(
644 "Bit set global var element may not have an explicit section");
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000645
646 if (isa<GlobalVariable>(OpGlobal) && OpGlobal->isDeclarationForLinker())
647 report_fatal_error("Bit set global var element must be a definition");
648
649 auto OffsetConstMD = dyn_cast<ConstantAsMetadata>(Op->getOperand(2));
650 if (!OffsetConstMD)
651 report_fatal_error("Bit set element offset must be a constant");
652 auto OffsetInt = dyn_cast<ConstantInt>(OffsetConstMD->getValue());
653 if (!OffsetInt)
654 report_fatal_error("Bit set element offset must be an integer constant");
655}
656
657static const unsigned kX86JumpTableEntrySize = 8;
658
659unsigned LowerBitSets::getJumpTableEntrySize() {
660 if (Arch != Triple::x86 && Arch != Triple::x86_64)
661 report_fatal_error("Unsupported architecture for jump tables");
662
663 return kX86JumpTableEntrySize;
664}
665
666// Create a constant representing a jump table entry for the target. This
667// consists of an instruction sequence containing a relative branch to Dest. The
668// constant will be laid out at address Src+(Len*Distance) where Len is the
669// target-specific jump table entry size.
670Constant *LowerBitSets::createJumpTableEntry(GlobalObject *Src, Function *Dest,
671 unsigned Distance) {
672 if (Arch != Triple::x86 && Arch != Triple::x86_64)
673 report_fatal_error("Unsupported architecture for jump tables");
674
675 const unsigned kJmpPCRel32Code = 0xe9;
676 const unsigned kInt3Code = 0xcc;
677
678 ConstantInt *Jmp = ConstantInt::get(Int8Ty, kJmpPCRel32Code);
679
680 // Build a constant representing the displacement between the constant's
681 // address and Dest. This will resolve to a PC32 relocation referring to Dest.
682 Constant *DestInt = ConstantExpr::getPtrToInt(Dest, IntPtrTy);
683 Constant *SrcInt = ConstantExpr::getPtrToInt(Src, IntPtrTy);
684 Constant *Disp = ConstantExpr::getSub(DestInt, SrcInt);
685 ConstantInt *DispOffset =
686 ConstantInt::get(IntPtrTy, Distance * kX86JumpTableEntrySize + 5);
687 Constant *OffsetedDisp = ConstantExpr::getSub(Disp, DispOffset);
Evgeniy Stepanovfda72c52015-12-21 22:14:04 +0000688 OffsetedDisp = ConstantExpr::getTruncOrBitCast(OffsetedDisp, Int32Ty);
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000689
690 ConstantInt *Int3 = ConstantInt::get(Int8Ty, kInt3Code);
691
692 Constant *Fields[] = {
693 Jmp, OffsetedDisp, Int3, Int3, Int3,
694 };
695 return ConstantStruct::getAnon(Fields, /*Packed=*/true);
696}
697
698Type *LowerBitSets::getJumpTableEntryType() {
699 if (Arch != Triple::x86 && Arch != Triple::x86_64)
700 report_fatal_error("Unsupported architecture for jump tables");
701
702 return StructType::get(M->getContext(),
703 {Int8Ty, Int32Ty, Int8Ty, Int8Ty, Int8Ty},
704 /*Packed=*/true);
705}
706
707/// Given a disjoint set of bitsets and functions, build a jump table for the
708/// functions, build the bit sets and lower the llvm.bitset.test calls.
709void LowerBitSets::buildBitSetsFromFunctions(ArrayRef<Metadata *> BitSets,
710 ArrayRef<Function *> Functions) {
711 // Unlike the global bitset builder, the function bitset builder cannot
712 // re-arrange functions in a particular order and base its calculations on the
713 // layout of the functions' entry points, as we have no idea how large a
714 // particular function will end up being (the size could even depend on what
715 // this pass does!) Instead, we build a jump table, which is a block of code
716 // consisting of one branch instruction for each of the functions in the bit
717 // set that branches to the target function, and redirect any taken function
718 // addresses to the corresponding jump table entry. In the object file's
719 // symbol table, the symbols for the target functions also refer to the jump
720 // table entries, so that addresses taken outside the module will pass any
721 // verification done inside the module.
722 //
723 // In more concrete terms, suppose we have three functions f, g, h which are
724 // members of a single bitset, and a function foo that returns their
725 // addresses:
726 //
727 // f:
728 // mov 0, %eax
729 // ret
730 //
731 // g:
732 // mov 1, %eax
733 // ret
734 //
735 // h:
736 // mov 2, %eax
737 // ret
738 //
739 // foo:
740 // mov f, %eax
741 // mov g, %edx
742 // mov h, %ecx
743 // ret
744 //
745 // To create a jump table for these functions, we instruct the LLVM code
746 // generator to output a jump table in the .text section. This is done by
747 // representing the instructions in the jump table as an LLVM constant and
748 // placing them in a global variable in the .text section. The end result will
749 // (conceptually) look like this:
750 //
751 // f:
752 // jmp .Ltmp0 ; 5 bytes
753 // int3 ; 1 byte
754 // int3 ; 1 byte
755 // int3 ; 1 byte
756 //
757 // g:
758 // jmp .Ltmp1 ; 5 bytes
759 // int3 ; 1 byte
760 // int3 ; 1 byte
761 // int3 ; 1 byte
762 //
763 // h:
764 // jmp .Ltmp2 ; 5 bytes
765 // int3 ; 1 byte
766 // int3 ; 1 byte
767 // int3 ; 1 byte
768 //
769 // .Ltmp0:
770 // mov 0, %eax
771 // ret
772 //
773 // .Ltmp1:
774 // mov 1, %eax
775 // ret
776 //
777 // .Ltmp2:
778 // mov 2, %eax
779 // ret
780 //
781 // foo:
782 // mov f, %eax
783 // mov g, %edx
784 // mov h, %ecx
785 // ret
786 //
787 // Because the addresses of f, g, h are evenly spaced at a power of 2, in the
788 // normal case the check can be carried out using the same kind of simple
789 // arithmetic that we normally use for globals.
790
791 assert(!Functions.empty());
792
793 // Build a simple layout based on the regular layout of jump tables.
794 DenseMap<GlobalObject *, uint64_t> GlobalLayout;
795 unsigned EntrySize = getJumpTableEntrySize();
796 for (unsigned I = 0; I != Functions.size(); ++I)
797 GlobalLayout[Functions[I]] = I * EntrySize;
798
799 // Create a constant to hold the jump table.
800 ArrayType *JumpTableType =
801 ArrayType::get(getJumpTableEntryType(), Functions.size());
802 auto JumpTable = new GlobalVariable(*M, JumpTableType,
803 /*isConstant=*/true,
804 GlobalValue::PrivateLinkage, nullptr);
805 JumpTable->setSection(ObjectFormat == Triple::MachO
806 ? "__TEXT,__text,regular,pure_instructions"
807 : ".text");
808 lowerBitSetCalls(BitSets, JumpTable, GlobalLayout);
809
810 // Build aliases pointing to offsets into the jump table, and replace
811 // references to the original functions with references to the aliases.
812 for (unsigned I = 0; I != Functions.size(); ++I) {
813 Constant *CombinedGlobalElemPtr = ConstantExpr::getBitCast(
814 ConstantExpr::getGetElementPtr(
815 JumpTableType, JumpTable,
816 ArrayRef<Constant *>{ConstantInt::get(IntPtrTy, 0),
817 ConstantInt::get(IntPtrTy, I)}),
818 Functions[I]->getType());
819 if (LinkerSubsectionsViaSymbols || Functions[I]->isDeclarationForLinker()) {
820 Functions[I]->replaceAllUsesWith(CombinedGlobalElemPtr);
821 } else {
David Blaikie6614d8d2015-09-14 20:29:26 +0000822 assert(Functions[I]->getType()->getAddressSpace() == 0);
823 GlobalAlias *GAlias = GlobalAlias::create(Functions[I]->getValueType(), 0,
824 Functions[I]->getLinkage(), "",
825 CombinedGlobalElemPtr, M);
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000826 GAlias->setVisibility(Functions[I]->getVisibility());
827 GAlias->takeName(Functions[I]);
828 Functions[I]->replaceAllUsesWith(GAlias);
829 }
830 if (!Functions[I]->isDeclarationForLinker())
831 Functions[I]->setLinkage(GlobalValue::PrivateLinkage);
832 }
833
834 // Build and set the jump table's initializer.
835 std::vector<Constant *> JumpTableEntries;
836 for (unsigned I = 0; I != Functions.size(); ++I)
837 JumpTableEntries.push_back(
838 createJumpTableEntry(JumpTable, Functions[I], I));
839 JumpTable->setInitializer(
840 ConstantArray::get(JumpTableType, JumpTableEntries));
841}
842
843void LowerBitSets::buildBitSetsFromDisjointSet(
844 ArrayRef<Metadata *> BitSets, ArrayRef<GlobalObject *> Globals) {
845 llvm::DenseMap<Metadata *, uint64_t> BitSetIndices;
846 llvm::DenseMap<GlobalObject *, uint64_t> GlobalIndices;
847 for (unsigned I = 0; I != BitSets.size(); ++I)
848 BitSetIndices[BitSets[I]] = I;
849 for (unsigned I = 0; I != Globals.size(); ++I)
850 GlobalIndices[Globals[I]] = I;
851
852 // For each bitset, build a set of indices that refer to globals referenced by
853 // the bitset.
854 std::vector<std::set<uint64_t>> BitSetMembers(BitSets.size());
855 if (BitSetNM) {
856 for (MDNode *Op : BitSetNM->operands()) {
857 // Op = { bitset name, global, offset }
858 if (!Op->getOperand(1))
859 continue;
860 auto I = BitSetIndices.find(Op->getOperand(0));
861 if (I == BitSetIndices.end())
862 continue;
863
864 auto OpGlobal = dyn_cast<GlobalObject>(
865 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
866 if (!OpGlobal)
867 continue;
868 BitSetMembers[I->second].insert(GlobalIndices[OpGlobal]);
869 }
870 }
871
872 // Order the sets of indices by size. The GlobalLayoutBuilder works best
873 // when given small index sets first.
874 std::stable_sort(
875 BitSetMembers.begin(), BitSetMembers.end(),
876 [](const std::set<uint64_t> &O1, const std::set<uint64_t> &O2) {
877 return O1.size() < O2.size();
878 });
879
880 // Create a GlobalLayoutBuilder and provide it with index sets as layout
881 // fragments. The GlobalLayoutBuilder tries to lay out members of fragments as
882 // close together as possible.
883 GlobalLayoutBuilder GLB(Globals.size());
884 for (auto &&MemSet : BitSetMembers)
885 GLB.addFragment(MemSet);
886
887 // Build the bitsets from this disjoint set.
888 if (Globals.empty() || isa<GlobalVariable>(Globals[0])) {
889 // Build a vector of global variables with the computed layout.
890 std::vector<GlobalVariable *> OrderedGVs(Globals.size());
891 auto OGI = OrderedGVs.begin();
892 for (auto &&F : GLB.Fragments) {
893 for (auto &&Offset : F) {
894 auto GV = dyn_cast<GlobalVariable>(Globals[Offset]);
895 if (!GV)
896 report_fatal_error(
897 "Bit set may not contain both global variables and functions");
898 *OGI++ = GV;
899 }
900 }
901
902 buildBitSetsFromGlobalVariables(BitSets, OrderedGVs);
903 } else {
904 // Build a vector of functions with the computed layout.
905 std::vector<Function *> OrderedFns(Globals.size());
906 auto OFI = OrderedFns.begin();
907 for (auto &&F : GLB.Fragments) {
908 for (auto &&Offset : F) {
909 auto Fn = dyn_cast<Function>(Globals[Offset]);
910 if (!Fn)
911 report_fatal_error(
912 "Bit set may not contain both global variables and functions");
913 *OFI++ = Fn;
914 }
915 }
916
917 buildBitSetsFromFunctions(BitSets, OrderedFns);
918 }
919}
920
Peter Collingbournee6909c82015-02-20 20:30:47 +0000921/// Lower all bit sets in this module.
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000922bool LowerBitSets::buildBitSets() {
Peter Collingbournee6909c82015-02-20 20:30:47 +0000923 Function *BitSetTestFunc =
Peter Collingbourneda2dbf22015-03-03 00:49:28 +0000924 M->getFunction(Intrinsic::getName(Intrinsic::bitset_test));
Peter Collingbourne0c0d7e22016-02-03 03:48:46 +0000925 if (!BitSetTestFunc || BitSetTestFunc->use_empty())
Peter Collingbournee6909c82015-02-20 20:30:47 +0000926 return false;
927
928 // Equivalence class set containing bitsets and the globals they reference.
929 // This is used to partition the set of bitsets in the module into disjoint
930 // sets.
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000931 typedef EquivalenceClasses<PointerUnion<GlobalObject *, Metadata *>>
Peter Collingbournee6909c82015-02-20 20:30:47 +0000932 GlobalClassesTy;
933 GlobalClassesTy GlobalClasses;
934
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000935 // Verify the bitset metadata and build a mapping from bitset identifiers to
936 // their last observed index in BitSetNM. This will used later to
937 // deterministically order the list of bitset identifiers.
938 llvm::DenseMap<Metadata *, unsigned> BitSetIdIndices;
939 if (BitSetNM) {
940 for (unsigned I = 0, E = BitSetNM->getNumOperands(); I != E; ++I) {
941 MDNode *Op = BitSetNM->getOperand(I);
942 verifyBitSetMDNode(Op);
Peter Collingbourne1cbc91e2015-09-09 22:30:32 +0000943 BitSetIdIndices[Op->getOperand(0)] = I;
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000944 }
945 }
946
Peter Collingbournee6909c82015-02-20 20:30:47 +0000947 for (const Use &U : BitSetTestFunc->uses()) {
948 auto CI = cast<CallInst>(U.getUser());
949
950 auto BitSetMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000951 if (!BitSetMDVal)
Peter Collingbournee6909c82015-02-20 20:30:47 +0000952 report_fatal_error(
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000953 "Second argument of llvm.bitset.test must be metadata");
954 auto BitSet = BitSetMDVal->getMetadata();
Peter Collingbournee6909c82015-02-20 20:30:47 +0000955
956 // Add the call site to the list of call sites for this bit set. We also use
957 // BitSetTestCallSites to keep track of whether we have seen this bit set
958 // before. If we have, we don't need to re-add the referenced globals to the
959 // equivalence class.
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000960 std::pair<DenseMap<Metadata *, std::vector<CallInst *>>::iterator,
Peter Collingbournee6909c82015-02-20 20:30:47 +0000961 bool> Ins =
962 BitSetTestCallSites.insert(
963 std::make_pair(BitSet, std::vector<CallInst *>()));
964 Ins.first->second.push_back(CI);
965 if (!Ins.second)
966 continue;
967
968 // Add the bitset to the equivalence class.
969 GlobalClassesTy::iterator GCI = GlobalClasses.insert(BitSet);
970 GlobalClassesTy::member_iterator CurSet = GlobalClasses.findLeader(GCI);
971
972 if (!BitSetNM)
973 continue;
974
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000975 // Add the referenced globals to the bitset's equivalence class.
Peter Collingbournee6909c82015-02-20 20:30:47 +0000976 for (MDNode *Op : BitSetNM->operands()) {
Peter Collingbournee6909c82015-02-20 20:30:47 +0000977 if (Op->getOperand(0) != BitSet || !Op->getOperand(1))
978 continue;
979
Peter Collingbourne8d24ae92015-09-08 22:49:35 +0000980 auto OpGlobal = dyn_cast<GlobalObject>(
981 cast<ConstantAsMetadata>(Op->getOperand(1))->getValue());
Peter Collingbournee6909c82015-02-20 20:30:47 +0000982 if (!OpGlobal)
Peter Collingbourneba4c8b52015-06-27 00:17:51 +0000983 continue;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000984
Peter Collingbournee6909c82015-02-20 20:30:47 +0000985 CurSet = GlobalClasses.unionSets(
986 CurSet, GlobalClasses.findLeader(GlobalClasses.insert(OpGlobal)));
987 }
988 }
989
990 if (GlobalClasses.empty())
991 return false;
992
Peter Collingbourne1cbc91e2015-09-09 22:30:32 +0000993 // Build a list of disjoint sets ordered by their maximum BitSetNM index
994 // for determinism.
995 std::vector<std::pair<GlobalClassesTy::iterator, unsigned>> Sets;
Peter Collingbournee6909c82015-02-20 20:30:47 +0000996 for (GlobalClassesTy::iterator I = GlobalClasses.begin(),
997 E = GlobalClasses.end();
998 I != E; ++I) {
999 if (!I->isLeader()) continue;
Peter Collingbournee6909c82015-02-20 20:30:47 +00001000 ++NumBitSetDisjointSets;
1001
Peter Collingbourne1cbc91e2015-09-09 22:30:32 +00001002 unsigned MaxIndex = 0;
1003 for (GlobalClassesTy::member_iterator MI = GlobalClasses.member_begin(I);
1004 MI != GlobalClasses.member_end(); ++MI) {
1005 if ((*MI).is<Metadata *>())
1006 MaxIndex = std::max(MaxIndex, BitSetIdIndices[MI->get<Metadata *>()]);
1007 }
1008 Sets.emplace_back(I, MaxIndex);
1009 }
1010 std::sort(Sets.begin(), Sets.end(),
1011 [](const std::pair<GlobalClassesTy::iterator, unsigned> &S1,
1012 const std::pair<GlobalClassesTy::iterator, unsigned> &S2) {
1013 return S1.second < S2.second;
1014 });
1015
1016 // For each disjoint set we found...
1017 for (const auto &S : Sets) {
Peter Collingbourne8d24ae92015-09-08 22:49:35 +00001018 // Build the list of bitsets in this disjoint set.
1019 std::vector<Metadata *> BitSets;
1020 std::vector<GlobalObject *> Globals;
Peter Collingbourne1cbc91e2015-09-09 22:30:32 +00001021 for (GlobalClassesTy::member_iterator MI =
1022 GlobalClasses.member_begin(S.first);
Peter Collingbournee6909c82015-02-20 20:30:47 +00001023 MI != GlobalClasses.member_end(); ++MI) {
Peter Collingbourne8d24ae92015-09-08 22:49:35 +00001024 if ((*MI).is<Metadata *>())
1025 BitSets.push_back(MI->get<Metadata *>());
1026 else
1027 Globals.push_back(MI->get<GlobalObject *>());
Peter Collingbournee6909c82015-02-20 20:30:47 +00001028 }
1029
Peter Collingbourne8d24ae92015-09-08 22:49:35 +00001030 // Order bitsets by BitSetNM index for determinism. This ordering is stable
1031 // as there is a one-to-one mapping between metadata and indices.
1032 std::sort(BitSets.begin(), BitSets.end(), [&](Metadata *M1, Metadata *M2) {
1033 return BitSetIdIndices[M1] < BitSetIdIndices[M2];
Peter Collingbournee6909c82015-02-20 20:30:47 +00001034 });
Peter Collingbournee6909c82015-02-20 20:30:47 +00001035
Peter Collingbourne8d24ae92015-09-08 22:49:35 +00001036 // Lower the bitsets in this disjoint set.
1037 buildBitSetsFromDisjointSet(BitSets, Globals);
Peter Collingbournee6909c82015-02-20 20:30:47 +00001038 }
1039
Peter Collingbourneda2dbf22015-03-03 00:49:28 +00001040 allocateByteArrays();
1041
Peter Collingbournee6909c82015-02-20 20:30:47 +00001042 return true;
1043}
1044
Peter Collingbourneda2dbf22015-03-03 00:49:28 +00001045bool LowerBitSets::eraseBitSetMetadata() {
Peter Collingbournee6909c82015-02-20 20:30:47 +00001046 if (!BitSetNM)
1047 return false;
1048
Peter Collingbourneda2dbf22015-03-03 00:49:28 +00001049 M->eraseNamedMetadata(BitSetNM);
Peter Collingbournee6909c82015-02-20 20:30:47 +00001050 return true;
1051}
1052
1053bool LowerBitSets::runOnModule(Module &M) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001054 if (skipModule(M))
1055 return false;
1056
Peter Collingbourneda2dbf22015-03-03 00:49:28 +00001057 bool Changed = buildBitSets();
1058 Changed |= eraseBitSetMetadata();
Peter Collingbournee6909c82015-02-20 20:30:47 +00001059 return Changed;
1060}