/
LowerTypeTests.cpp
2132 lines (1841 loc) · 78.5 KB
/
LowerTypeTests.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- LowerTypeTests.cpp - type metadata lowering pass -------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This pass lowers type metadata and calls to the llvm.type.test intrinsic.
// It also ensures that globals are properly laid out for the
// llvm.icall.branch.funnel intrinsic.
// See http://llvm.org/docs/TypeMetadata.html for more information.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO/LowerTypeTests.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/EquivalenceClasses.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/TypeMetadataUtils.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/GlobalObject.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ModuleSummaryIndex.h"
#include "llvm/IR/ModuleSummaryIndexYAML.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/Pass.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/TrailingObjects.h"
#include "llvm/Support/YAMLTraits.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <memory>
#include <set>
#include <string>
#include <system_error>
#include <utility>
#include <vector>
using namespace llvm;
using namespace lowertypetests;
#define DEBUG_TYPE "lowertypetests"
STATISTIC(ByteArraySizeBits, "Byte array size in bits");
STATISTIC(ByteArraySizeBytes, "Byte array size in bytes");
STATISTIC(NumByteArraysCreated, "Number of byte arrays created");
STATISTIC(NumTypeTestCallsLowered, "Number of type test calls lowered");
STATISTIC(NumTypeIdDisjointSets, "Number of disjoint sets of type identifiers");
static cl::opt<bool> AvoidReuse(
"lowertypetests-avoid-reuse",
cl::desc("Try to avoid reuse of byte array addresses using aliases"),
cl::Hidden, cl::init(true));
static cl::opt<PassSummaryAction> ClSummaryAction(
"lowertypetests-summary-action",
cl::desc("What to do with the summary when running this pass"),
cl::values(clEnumValN(PassSummaryAction::None, "none", "Do nothing"),
clEnumValN(PassSummaryAction::Import, "import",
"Import typeid resolutions from summary and globals"),
clEnumValN(PassSummaryAction::Export, "export",
"Export typeid resolutions to summary and globals")),
cl::Hidden);
static cl::opt<std::string> ClReadSummary(
"lowertypetests-read-summary",
cl::desc("Read summary from given YAML file before running pass"),
cl::Hidden);
static cl::opt<std::string> ClWriteSummary(
"lowertypetests-write-summary",
cl::desc("Write summary to given YAML file after running pass"),
cl::Hidden);
bool BitSetInfo::containsGlobalOffset(uint64_t Offset) const {
if (Offset < ByteOffset)
return false;
if ((Offset - ByteOffset) % (uint64_t(1) << AlignLog2) != 0)
return false;
uint64_t BitOffset = (Offset - ByteOffset) >> AlignLog2;
if (BitOffset >= BitSize)
return false;
return Bits.count(BitOffset);
}
void BitSetInfo::print(raw_ostream &OS) const {
OS << "offset " << ByteOffset << " size " << BitSize << " align "
<< (1 << AlignLog2);
if (isAllOnes()) {
OS << " all-ones\n";
return;
}
OS << " { ";
for (uint64_t B : Bits)
OS << B << ' ';
OS << "}\n";
}
BitSetInfo BitSetBuilder::build() {
if (Min > Max)
Min = 0;
// Normalize each offset against the minimum observed offset, and compute
// the bitwise OR of each of the offsets. The number of trailing zeros
// in the mask gives us the log2 of the alignment of all offsets, which
// allows us to compress the bitset by only storing one bit per aligned
// address.
uint64_t Mask = 0;
for (uint64_t &Offset : Offsets) {
Offset -= Min;
Mask |= Offset;
}
BitSetInfo BSI;
BSI.ByteOffset = Min;
BSI.AlignLog2 = 0;
if (Mask != 0)
BSI.AlignLog2 = countTrailingZeros(Mask, ZB_Undefined);
// Build the compressed bitset while normalizing the offsets against the
// computed alignment.
BSI.BitSize = ((Max - Min) >> BSI.AlignLog2) + 1;
for (uint64_t Offset : Offsets) {
Offset >>= BSI.AlignLog2;
BSI.Bits.insert(Offset);
}
return BSI;
}
void GlobalLayoutBuilder::addFragment(const std::set<uint64_t> &F) {
// Create a new fragment to hold the layout for F.
Fragments.emplace_back();
std::vector<uint64_t> &Fragment = Fragments.back();
uint64_t FragmentIndex = Fragments.size() - 1;
for (auto ObjIndex : F) {
uint64_t OldFragmentIndex = FragmentMap[ObjIndex];
if (OldFragmentIndex == 0) {
// We haven't seen this object index before, so just add it to the current
// fragment.
Fragment.push_back(ObjIndex);
} else {
// This index belongs to an existing fragment. Copy the elements of the
// old fragment into this one and clear the old fragment. We don't update
// the fragment map just yet, this ensures that any further references to
// indices from the old fragment in this fragment do not insert any more
// indices.
std::vector<uint64_t> &OldFragment = Fragments[OldFragmentIndex];
Fragment.insert(Fragment.end(), OldFragment.begin(), OldFragment.end());
OldFragment.clear();
}
}
// Update the fragment map to point our object indices to this fragment.
for (uint64_t ObjIndex : Fragment)
FragmentMap[ObjIndex] = FragmentIndex;
}
void ByteArrayBuilder::allocate(const std::set<uint64_t> &Bits,
uint64_t BitSize, uint64_t &AllocByteOffset,
uint8_t &AllocMask) {
// Find the smallest current allocation.
unsigned Bit = 0;
for (unsigned I = 1; I != BitsPerByte; ++I)
if (BitAllocs[I] < BitAllocs[Bit])
Bit = I;
AllocByteOffset = BitAllocs[Bit];
// Add our size to it.
unsigned ReqSize = AllocByteOffset + BitSize;
BitAllocs[Bit] = ReqSize;
if (Bytes.size() < ReqSize)
Bytes.resize(ReqSize);
// Set our bits.
AllocMask = 1 << Bit;
for (uint64_t B : Bits)
Bytes[AllocByteOffset + B] |= AllocMask;
}
namespace {
struct ByteArrayInfo {
std::set<uint64_t> Bits;
uint64_t BitSize;
GlobalVariable *ByteArray;
GlobalVariable *MaskGlobal;
uint8_t *MaskPtr = nullptr;
};
/// A POD-like structure that we use to store a global reference together with
/// its metadata types. In this pass we frequently need to query the set of
/// metadata types referenced by a global, which at the IR level is an expensive
/// operation involving a map lookup; this data structure helps to reduce the
/// number of times we need to do this lookup.
class GlobalTypeMember final : TrailingObjects<GlobalTypeMember, MDNode *> {
friend TrailingObjects;
GlobalObject *GO;
size_t NTypes;
// For functions: true if this is a definition (either in the merged module or
// in one of the thinlto modules).
bool IsDefinition;
// For functions: true if this function is either defined or used in a thinlto
// module and its jumptable entry needs to be exported to thinlto backends.
bool IsExported;
size_t numTrailingObjects(OverloadToken<MDNode *>) const { return NTypes; }
public:
static GlobalTypeMember *create(BumpPtrAllocator &Alloc, GlobalObject *GO,
bool IsDefinition, bool IsExported,
ArrayRef<MDNode *> Types) {
auto *GTM = static_cast<GlobalTypeMember *>(Alloc.Allocate(
totalSizeToAlloc<MDNode *>(Types.size()), alignof(GlobalTypeMember)));
GTM->GO = GO;
GTM->NTypes = Types.size();
GTM->IsDefinition = IsDefinition;
GTM->IsExported = IsExported;
std::uninitialized_copy(Types.begin(), Types.end(),
GTM->getTrailingObjects<MDNode *>());
return GTM;
}
GlobalObject *getGlobal() const {
return GO;
}
bool isDefinition() const {
return IsDefinition;
}
bool isExported() const {
return IsExported;
}
ArrayRef<MDNode *> types() const {
return makeArrayRef(getTrailingObjects<MDNode *>(), NTypes);
}
};
struct ICallBranchFunnel final
: TrailingObjects<ICallBranchFunnel, GlobalTypeMember *> {
static ICallBranchFunnel *create(BumpPtrAllocator &Alloc, CallInst *CI,
ArrayRef<GlobalTypeMember *> Targets,
unsigned UniqueId) {
auto *Call = static_cast<ICallBranchFunnel *>(
Alloc.Allocate(totalSizeToAlloc<GlobalTypeMember *>(Targets.size()),
alignof(ICallBranchFunnel)));
Call->CI = CI;
Call->UniqueId = UniqueId;
Call->NTargets = Targets.size();
std::uninitialized_copy(Targets.begin(), Targets.end(),
Call->getTrailingObjects<GlobalTypeMember *>());
return Call;
}
CallInst *CI;
ArrayRef<GlobalTypeMember *> targets() const {
return makeArrayRef(getTrailingObjects<GlobalTypeMember *>(), NTargets);
}
unsigned UniqueId;
private:
size_t NTargets;
};
class LowerTypeTestsModule {
Module &M;
ModuleSummaryIndex *ExportSummary;
const ModuleSummaryIndex *ImportSummary;
Triple::ArchType Arch;
Triple::OSType OS;
Triple::ObjectFormatType ObjectFormat;
IntegerType *Int1Ty = Type::getInt1Ty(M.getContext());
IntegerType *Int8Ty = Type::getInt8Ty(M.getContext());
PointerType *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
ArrayType *Int8Arr0Ty = ArrayType::get(Type::getInt8Ty(M.getContext()), 0);
IntegerType *Int32Ty = Type::getInt32Ty(M.getContext());
PointerType *Int32PtrTy = PointerType::getUnqual(Int32Ty);
IntegerType *Int64Ty = Type::getInt64Ty(M.getContext());
IntegerType *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext(), 0);
// Indirect function call index assignment counter for WebAssembly
uint64_t IndirectIndex = 1;
// Mapping from type identifiers to the call sites that test them, as well as
// whether the type identifier needs to be exported to ThinLTO backends as
// part of the regular LTO phase of the ThinLTO pipeline (see exportTypeId).
struct TypeIdUserInfo {
std::vector<CallInst *> CallSites;
bool IsExported = false;
};
DenseMap<Metadata *, TypeIdUserInfo> TypeIdUsers;
/// This structure describes how to lower type tests for a particular type
/// identifier. It is either built directly from the global analysis (during
/// regular LTO or the regular LTO phase of ThinLTO), or indirectly using type
/// identifier summaries and external symbol references (in ThinLTO backends).
struct TypeIdLowering {
TypeTestResolution::Kind TheKind = TypeTestResolution::Unsat;
/// All except Unsat: the start address within the combined global.
Constant *OffsetedGlobal;
/// ByteArray, Inline, AllOnes: log2 of the required global alignment
/// relative to the start address.
Constant *AlignLog2;
/// ByteArray, Inline, AllOnes: one less than the size of the memory region
/// covering members of this type identifier as a multiple of 2^AlignLog2.
Constant *SizeM1;
/// ByteArray: the byte array to test the address against.
Constant *TheByteArray;
/// ByteArray: the bit mask to apply to bytes loaded from the byte array.
Constant *BitMask;
/// Inline: the bit mask to test the address against.
Constant *InlineBits;
};
std::vector<ByteArrayInfo> ByteArrayInfos;
Function *WeakInitializerFn = nullptr;
bool shouldExportConstantsAsAbsoluteSymbols();
uint8_t *exportTypeId(StringRef TypeId, const TypeIdLowering &TIL);
TypeIdLowering importTypeId(StringRef TypeId);
void importTypeTest(CallInst *CI);
void importFunction(Function *F, bool isDefinition);
BitSetInfo
buildBitSet(Metadata *TypeId,
const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout);
ByteArrayInfo *createByteArray(BitSetInfo &BSI);
void allocateByteArrays();
Value *createBitSetTest(IRBuilder<> &B, const TypeIdLowering &TIL,
Value *BitOffset);
void lowerTypeTestCalls(
ArrayRef<Metadata *> TypeIds, Constant *CombinedGlobalAddr,
const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout);
Value *lowerTypeTestCall(Metadata *TypeId, CallInst *CI,
const TypeIdLowering &TIL);
void buildBitSetsFromGlobalVariables(ArrayRef<Metadata *> TypeIds,
ArrayRef<GlobalTypeMember *> Globals);
unsigned getJumpTableEntrySize();
Type *getJumpTableEntryType();
void createJumpTableEntry(raw_ostream &AsmOS, raw_ostream &ConstraintOS,
Triple::ArchType JumpTableArch,
SmallVectorImpl<Value *> &AsmArgs, Function *Dest);
void verifyTypeMDNode(GlobalObject *GO, MDNode *Type);
void buildBitSetsFromFunctions(ArrayRef<Metadata *> TypeIds,
ArrayRef<GlobalTypeMember *> Functions);
void buildBitSetsFromFunctionsNative(ArrayRef<Metadata *> TypeIds,
ArrayRef<GlobalTypeMember *> Functions);
void buildBitSetsFromFunctionsWASM(ArrayRef<Metadata *> TypeIds,
ArrayRef<GlobalTypeMember *> Functions);
void
buildBitSetsFromDisjointSet(ArrayRef<Metadata *> TypeIds,
ArrayRef<GlobalTypeMember *> Globals,
ArrayRef<ICallBranchFunnel *> ICallBranchFunnels);
void replaceWeakDeclarationWithJumpTablePtr(Function *F, Constant *JT, bool IsDefinition);
void moveInitializerToModuleConstructor(GlobalVariable *GV);
void findGlobalVariableUsersOf(Constant *C,
SmallSetVector<GlobalVariable *, 8> &Out);
void createJumpTable(Function *F, ArrayRef<GlobalTypeMember *> Functions);
/// replaceCfiUses - Go through the uses list for this definition
/// and make each use point to "V" instead of "this" when the use is outside
/// the block. 'This's use list is expected to have at least one element.
/// Unlike replaceAllUsesWith this function skips blockaddr and direct call
/// uses.
void replaceCfiUses(Function *Old, Value *New, bool IsDefinition);
/// replaceDirectCalls - Go through the uses list for this definition and
/// replace each use, which is a direct function call.
void replaceDirectCalls(Value *Old, Value *New);
public:
LowerTypeTestsModule(Module &M, ModuleSummaryIndex *ExportSummary,
const ModuleSummaryIndex *ImportSummary);
bool lower();
// Lower the module using the action and summary passed as command line
// arguments. For testing purposes only.
static bool runForTesting(Module &M);
};
struct LowerTypeTests : public ModulePass {
static char ID;
bool UseCommandLine = false;
ModuleSummaryIndex *ExportSummary;
const ModuleSummaryIndex *ImportSummary;
LowerTypeTests() : ModulePass(ID), UseCommandLine(true) {
initializeLowerTypeTestsPass(*PassRegistry::getPassRegistry());
}
LowerTypeTests(ModuleSummaryIndex *ExportSummary,
const ModuleSummaryIndex *ImportSummary)
: ModulePass(ID), ExportSummary(ExportSummary),
ImportSummary(ImportSummary) {
initializeLowerTypeTestsPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module &M) override {
if (UseCommandLine)
return LowerTypeTestsModule::runForTesting(M);
return LowerTypeTestsModule(M, ExportSummary, ImportSummary).lower();
}
};
} // end anonymous namespace
char LowerTypeTests::ID = 0;
INITIALIZE_PASS(LowerTypeTests, "lowertypetests", "Lower type metadata", false,
false)
ModulePass *
llvm::createLowerTypeTestsPass(ModuleSummaryIndex *ExportSummary,
const ModuleSummaryIndex *ImportSummary) {
return new LowerTypeTests(ExportSummary, ImportSummary);
}
/// Build a bit set for TypeId using the object layouts in
/// GlobalLayout.
BitSetInfo LowerTypeTestsModule::buildBitSet(
Metadata *TypeId,
const DenseMap<GlobalTypeMember *, uint64_t> &GlobalLayout) {
BitSetBuilder BSB;
// Compute the byte offset of each address associated with this type
// identifier.
for (auto &GlobalAndOffset : GlobalLayout) {
for (MDNode *Type : GlobalAndOffset.first->types()) {
if (Type->getOperand(1) != TypeId)
continue;
uint64_t Offset =
cast<ConstantInt>(
cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
->getZExtValue();
BSB.addOffset(GlobalAndOffset.second + Offset);
}
}
return BSB.build();
}
/// Build a test that bit BitOffset mod sizeof(Bits)*8 is set in
/// Bits. This pattern matches to the bt instruction on x86.
static Value *createMaskedBitTest(IRBuilder<> &B, Value *Bits,
Value *BitOffset) {
auto BitsType = cast<IntegerType>(Bits->getType());
unsigned BitWidth = BitsType->getBitWidth();
BitOffset = B.CreateZExtOrTrunc(BitOffset, BitsType);
Value *BitIndex =
B.CreateAnd(BitOffset, ConstantInt::get(BitsType, BitWidth - 1));
Value *BitMask = B.CreateShl(ConstantInt::get(BitsType, 1), BitIndex);
Value *MaskedBits = B.CreateAnd(Bits, BitMask);
return B.CreateICmpNE(MaskedBits, ConstantInt::get(BitsType, 0));
}
ByteArrayInfo *LowerTypeTestsModule::createByteArray(BitSetInfo &BSI) {
// Create globals to stand in for byte arrays and masks. These never actually
// get initialized, we RAUW and erase them later in allocateByteArrays() once
// we know the offset and mask to use.
auto ByteArrayGlobal = new GlobalVariable(
M, Int8Ty, /*isConstant=*/true, GlobalValue::PrivateLinkage, nullptr);
auto MaskGlobal = new GlobalVariable(M, Int8Ty, /*isConstant=*/true,
GlobalValue::PrivateLinkage, nullptr);
ByteArrayInfos.emplace_back();
ByteArrayInfo *BAI = &ByteArrayInfos.back();
BAI->Bits = BSI.Bits;
BAI->BitSize = BSI.BitSize;
BAI->ByteArray = ByteArrayGlobal;
BAI->MaskGlobal = MaskGlobal;
return BAI;
}
void LowerTypeTestsModule::allocateByteArrays() {
llvm::stable_sort(ByteArrayInfos,
[](const ByteArrayInfo &BAI1, const ByteArrayInfo &BAI2) {
return BAI1.BitSize > BAI2.BitSize;
});
std::vector<uint64_t> ByteArrayOffsets(ByteArrayInfos.size());
ByteArrayBuilder BAB;
for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
ByteArrayInfo *BAI = &ByteArrayInfos[I];
uint8_t Mask;
BAB.allocate(BAI->Bits, BAI->BitSize, ByteArrayOffsets[I], Mask);
BAI->MaskGlobal->replaceAllUsesWith(
ConstantExpr::getIntToPtr(ConstantInt::get(Int8Ty, Mask), Int8PtrTy));
BAI->MaskGlobal->eraseFromParent();
if (BAI->MaskPtr)
*BAI->MaskPtr = Mask;
}
Constant *ByteArrayConst = ConstantDataArray::get(M.getContext(), BAB.Bytes);
auto ByteArray =
new GlobalVariable(M, ByteArrayConst->getType(), /*isConstant=*/true,
GlobalValue::PrivateLinkage, ByteArrayConst);
for (unsigned I = 0; I != ByteArrayInfos.size(); ++I) {
ByteArrayInfo *BAI = &ByteArrayInfos[I];
Constant *Idxs[] = {ConstantInt::get(IntPtrTy, 0),
ConstantInt::get(IntPtrTy, ByteArrayOffsets[I])};
Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(
ByteArrayConst->getType(), ByteArray, Idxs);
// Create an alias instead of RAUW'ing the gep directly. On x86 this ensures
// that the pc-relative displacement is folded into the lea instead of the
// test instruction getting another displacement.
GlobalAlias *Alias = GlobalAlias::create(
Int8Ty, 0, GlobalValue::PrivateLinkage, "bits", GEP, &M);
BAI->ByteArray->replaceAllUsesWith(Alias);
BAI->ByteArray->eraseFromParent();
}
ByteArraySizeBits = BAB.BitAllocs[0] + BAB.BitAllocs[1] + BAB.BitAllocs[2] +
BAB.BitAllocs[3] + BAB.BitAllocs[4] + BAB.BitAllocs[5] +
BAB.BitAllocs[6] + BAB.BitAllocs[7];
ByteArraySizeBytes = BAB.Bytes.size();
}
/// Build a test that bit BitOffset is set in the type identifier that was
/// lowered to TIL, which must be either an Inline or a ByteArray.
Value *LowerTypeTestsModule::createBitSetTest(IRBuilder<> &B,
const TypeIdLowering &TIL,
Value *BitOffset) {
if (TIL.TheKind == TypeTestResolution::Inline) {
// If the bit set is sufficiently small, we can avoid a load by bit testing
// a constant.
return createMaskedBitTest(B, TIL.InlineBits, BitOffset);
} else {
Constant *ByteArray = TIL.TheByteArray;
if (AvoidReuse && !ImportSummary) {
// Each use of the byte array uses a different alias. This makes the
// backend less likely to reuse previously computed byte array addresses,
// improving the security of the CFI mechanism based on this pass.
// This won't work when importing because TheByteArray is external.
ByteArray = GlobalAlias::create(Int8Ty, 0, GlobalValue::PrivateLinkage,
"bits_use", ByteArray, &M);
}
Value *ByteAddr = B.CreateGEP(Int8Ty, ByteArray, BitOffset);
Value *Byte = B.CreateLoad(Int8Ty, ByteAddr);
Value *ByteAndMask =
B.CreateAnd(Byte, ConstantExpr::getPtrToInt(TIL.BitMask, Int8Ty));
return B.CreateICmpNE(ByteAndMask, ConstantInt::get(Int8Ty, 0));
}
}
static bool isKnownTypeIdMember(Metadata *TypeId, const DataLayout &DL,
Value *V, uint64_t COffset) {
if (auto GV = dyn_cast<GlobalObject>(V)) {
SmallVector<MDNode *, 2> Types;
GV->getMetadata(LLVMContext::MD_type, Types);
for (MDNode *Type : Types) {
if (Type->getOperand(1) != TypeId)
continue;
uint64_t Offset =
cast<ConstantInt>(
cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
->getZExtValue();
if (COffset == Offset)
return true;
}
return false;
}
if (auto GEP = dyn_cast<GEPOperator>(V)) {
APInt APOffset(DL.getPointerSizeInBits(0), 0);
bool Result = GEP->accumulateConstantOffset(DL, APOffset);
if (!Result)
return false;
COffset += APOffset.getZExtValue();
return isKnownTypeIdMember(TypeId, DL, GEP->getPointerOperand(), COffset);
}
if (auto Op = dyn_cast<Operator>(V)) {
if (Op->getOpcode() == Instruction::BitCast)
return isKnownTypeIdMember(TypeId, DL, Op->getOperand(0), COffset);
if (Op->getOpcode() == Instruction::Select)
return isKnownTypeIdMember(TypeId, DL, Op->getOperand(1), COffset) &&
isKnownTypeIdMember(TypeId, DL, Op->getOperand(2), COffset);
}
return false;
}
/// Lower a llvm.type.test call to its implementation. Returns the value to
/// replace the call with.
Value *LowerTypeTestsModule::lowerTypeTestCall(Metadata *TypeId, CallInst *CI,
const TypeIdLowering &TIL) {
if (TIL.TheKind == TypeTestResolution::Unsat)
return ConstantInt::getFalse(M.getContext());
Value *Ptr = CI->getArgOperand(0);
const DataLayout &DL = M.getDataLayout();
if (isKnownTypeIdMember(TypeId, DL, Ptr, 0))
return ConstantInt::getTrue(M.getContext());
BasicBlock *InitialBB = CI->getParent();
IRBuilder<> B(CI);
Value *PtrAsInt = B.CreatePtrToInt(Ptr, IntPtrTy);
Constant *OffsetedGlobalAsInt =
ConstantExpr::getPtrToInt(TIL.OffsetedGlobal, IntPtrTy);
if (TIL.TheKind == TypeTestResolution::Single)
return B.CreateICmpEQ(PtrAsInt, OffsetedGlobalAsInt);
Value *PtrOffset = B.CreateSub(PtrAsInt, OffsetedGlobalAsInt);
// We need to check that the offset both falls within our range and is
// suitably aligned. We can check both properties at the same time by
// performing a right rotate by log2(alignment) followed by an integer
// comparison against the bitset size. The rotate will move the lower
// order bits that need to be zero into the higher order bits of the
// result, causing the comparison to fail if they are nonzero. The rotate
// also conveniently gives us a bit offset to use during the load from
// the bitset.
Value *OffsetSHR =
B.CreateLShr(PtrOffset, ConstantExpr::getZExt(TIL.AlignLog2, IntPtrTy));
Value *OffsetSHL = B.CreateShl(
PtrOffset, ConstantExpr::getZExt(
ConstantExpr::getSub(
ConstantInt::get(Int8Ty, DL.getPointerSizeInBits(0)),
TIL.AlignLog2),
IntPtrTy));
Value *BitOffset = B.CreateOr(OffsetSHR, OffsetSHL);
Value *OffsetInRange = B.CreateICmpULE(BitOffset, TIL.SizeM1);
// If the bit set is all ones, testing against it is unnecessary.
if (TIL.TheKind == TypeTestResolution::AllOnes)
return OffsetInRange;
// See if the intrinsic is used in the following common pattern:
// br(llvm.type.test(...), thenbb, elsebb)
// where nothing happens between the type test and the br.
// If so, create slightly simpler IR.
if (CI->hasOneUse())
if (auto *Br = dyn_cast<BranchInst>(*CI->user_begin()))
if (CI->getNextNode() == Br) {
BasicBlock *Then = InitialBB->splitBasicBlock(CI->getIterator());
BasicBlock *Else = Br->getSuccessor(1);
BranchInst *NewBr = BranchInst::Create(Then, Else, OffsetInRange);
NewBr->setMetadata(LLVMContext::MD_prof,
Br->getMetadata(LLVMContext::MD_prof));
ReplaceInstWithInst(InitialBB->getTerminator(), NewBr);
// Update phis in Else resulting from InitialBB being split
for (auto &Phi : Else->phis())
Phi.addIncoming(Phi.getIncomingValueForBlock(Then), InitialBB);
IRBuilder<> ThenB(CI);
return createBitSetTest(ThenB, TIL, BitOffset);
}
IRBuilder<> ThenB(SplitBlockAndInsertIfThen(OffsetInRange, CI, false));
// Now that we know that the offset is in range and aligned, load the
// appropriate bit from the bitset.
Value *Bit = createBitSetTest(ThenB, TIL, BitOffset);
// The value we want is 0 if we came directly from the initial block
// (having failed the range or alignment checks), or the loaded bit if
// we came from the block in which we loaded it.
B.SetInsertPoint(CI);
PHINode *P = B.CreatePHI(Int1Ty, 2);
P->addIncoming(ConstantInt::get(Int1Ty, 0), InitialBB);
P->addIncoming(Bit, ThenB.GetInsertBlock());
return P;
}
/// Given a disjoint set of type identifiers and globals, lay out the globals,
/// build the bit sets and lower the llvm.type.test calls.
void LowerTypeTestsModule::buildBitSetsFromGlobalVariables(
ArrayRef<Metadata *> TypeIds, ArrayRef<GlobalTypeMember *> Globals) {
// Build a new global with the combined contents of the referenced globals.
// This global is a struct whose even-indexed elements contain the original
// contents of the referenced globals and whose odd-indexed elements contain
// any padding required to align the next element to the next power of 2 plus
// any additional padding required to meet its alignment requirements.
std::vector<Constant *> GlobalInits;
const DataLayout &DL = M.getDataLayout();
DenseMap<GlobalTypeMember *, uint64_t> GlobalLayout;
uint64_t MaxAlign = 0;
uint64_t CurOffset = 0;
uint64_t DesiredPadding = 0;
for (GlobalTypeMember *G : Globals) {
auto *GV = cast<GlobalVariable>(G->getGlobal());
uint64_t Align = GV->getAlignment();
if (Align == 0)
Align = DL.getABITypeAlignment(GV->getValueType());
MaxAlign = std::max(MaxAlign, Align);
uint64_t GVOffset = alignTo(CurOffset + DesiredPadding, Align);
GlobalLayout[G] = GVOffset;
if (GVOffset != 0) {
uint64_t Padding = GVOffset - CurOffset;
GlobalInits.push_back(
ConstantAggregateZero::get(ArrayType::get(Int8Ty, Padding)));
}
GlobalInits.push_back(GV->getInitializer());
uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
CurOffset = GVOffset + InitSize;
// Compute the amount of padding that we'd like for the next element.
DesiredPadding = NextPowerOf2(InitSize - 1) - InitSize;
// Experiments of different caps with Chromium on both x64 and ARM64
// have shown that the 32-byte cap generates the smallest binary on
// both platforms while different caps yield similar performance.
// (see https://lists.llvm.org/pipermail/llvm-dev/2018-July/124694.html)
if (DesiredPadding > 32)
DesiredPadding = alignTo(InitSize, 32) - InitSize;
}
Constant *NewInit = ConstantStruct::getAnon(M.getContext(), GlobalInits);
auto *CombinedGlobal =
new GlobalVariable(M, NewInit->getType(), /*isConstant=*/true,
GlobalValue::PrivateLinkage, NewInit);
CombinedGlobal->setAlignment(MaxAlign);
StructType *NewTy = cast<StructType>(NewInit->getType());
lowerTypeTestCalls(TypeIds, CombinedGlobal, GlobalLayout);
// Build aliases pointing to offsets into the combined global for each
// global from which we built the combined global, and replace references
// to the original globals with references to the aliases.
for (unsigned I = 0; I != Globals.size(); ++I) {
GlobalVariable *GV = cast<GlobalVariable>(Globals[I]->getGlobal());
// Multiply by 2 to account for padding elements.
Constant *CombinedGlobalIdxs[] = {ConstantInt::get(Int32Ty, 0),
ConstantInt::get(Int32Ty, I * 2)};
Constant *CombinedGlobalElemPtr = ConstantExpr::getGetElementPtr(
NewInit->getType(), CombinedGlobal, CombinedGlobalIdxs);
assert(GV->getType()->getAddressSpace() == 0);
GlobalAlias *GAlias =
GlobalAlias::create(NewTy->getElementType(I * 2), 0, GV->getLinkage(),
"", CombinedGlobalElemPtr, &M);
GAlias->setVisibility(GV->getVisibility());
GAlias->takeName(GV);
GV->replaceAllUsesWith(GAlias);
GV->eraseFromParent();
}
}
bool LowerTypeTestsModule::shouldExportConstantsAsAbsoluteSymbols() {
return (Arch == Triple::x86 || Arch == Triple::x86_64) &&
ObjectFormat == Triple::ELF;
}
/// Export the given type identifier so that ThinLTO backends may import it.
/// Type identifiers are exported by adding coarse-grained information about how
/// to test the type identifier to the summary, and creating symbols in the
/// object file (aliases and absolute symbols) containing fine-grained
/// information about the type identifier.
///
/// Returns a pointer to the location in which to store the bitmask, if
/// applicable.
uint8_t *LowerTypeTestsModule::exportTypeId(StringRef TypeId,
const TypeIdLowering &TIL) {
TypeTestResolution &TTRes =
ExportSummary->getOrInsertTypeIdSummary(TypeId).TTRes;
TTRes.TheKind = TIL.TheKind;
auto ExportGlobal = [&](StringRef Name, Constant *C) {
GlobalAlias *GA =
GlobalAlias::create(Int8Ty, 0, GlobalValue::ExternalLinkage,
"__typeid_" + TypeId + "_" + Name, C, &M);
GA->setVisibility(GlobalValue::HiddenVisibility);
};
auto ExportConstant = [&](StringRef Name, uint64_t &Storage, Constant *C) {
if (shouldExportConstantsAsAbsoluteSymbols())
ExportGlobal(Name, ConstantExpr::getIntToPtr(C, Int8PtrTy));
else
Storage = cast<ConstantInt>(C)->getZExtValue();
};
if (TIL.TheKind != TypeTestResolution::Unsat)
ExportGlobal("global_addr", TIL.OffsetedGlobal);
if (TIL.TheKind == TypeTestResolution::ByteArray ||
TIL.TheKind == TypeTestResolution::Inline ||
TIL.TheKind == TypeTestResolution::AllOnes) {
ExportConstant("align", TTRes.AlignLog2, TIL.AlignLog2);
ExportConstant("size_m1", TTRes.SizeM1, TIL.SizeM1);
uint64_t BitSize = cast<ConstantInt>(TIL.SizeM1)->getZExtValue() + 1;
if (TIL.TheKind == TypeTestResolution::Inline)
TTRes.SizeM1BitWidth = (BitSize <= 32) ? 5 : 6;
else
TTRes.SizeM1BitWidth = (BitSize <= 128) ? 7 : 32;
}
if (TIL.TheKind == TypeTestResolution::ByteArray) {
ExportGlobal("byte_array", TIL.TheByteArray);
if (shouldExportConstantsAsAbsoluteSymbols())
ExportGlobal("bit_mask", TIL.BitMask);
else
return &TTRes.BitMask;
}
if (TIL.TheKind == TypeTestResolution::Inline)
ExportConstant("inline_bits", TTRes.InlineBits, TIL.InlineBits);
return nullptr;
}
LowerTypeTestsModule::TypeIdLowering
LowerTypeTestsModule::importTypeId(StringRef TypeId) {
const TypeIdSummary *TidSummary = ImportSummary->getTypeIdSummary(TypeId);
if (!TidSummary)
return {}; // Unsat: no globals match this type id.
const TypeTestResolution &TTRes = TidSummary->TTRes;
TypeIdLowering TIL;
TIL.TheKind = TTRes.TheKind;
auto ImportGlobal = [&](StringRef Name) {
// Give the global a type of length 0 so that it is not assumed not to alias
// with any other global.
Constant *C = M.getOrInsertGlobal(("__typeid_" + TypeId + "_" + Name).str(),
Int8Arr0Ty);
if (auto *GV = dyn_cast<GlobalVariable>(C))
GV->setVisibility(GlobalValue::HiddenVisibility);
C = ConstantExpr::getBitCast(C, Int8PtrTy);
return C;
};
auto ImportConstant = [&](StringRef Name, uint64_t Const, unsigned AbsWidth,
Type *Ty) {
if (!shouldExportConstantsAsAbsoluteSymbols()) {
Constant *C =
ConstantInt::get(isa<IntegerType>(Ty) ? Ty : Int64Ty, Const);
if (!isa<IntegerType>(Ty))
C = ConstantExpr::getIntToPtr(C, Ty);
return C;
}
Constant *C = ImportGlobal(Name);
auto *GV = cast<GlobalVariable>(C->stripPointerCasts());
if (isa<IntegerType>(Ty))
C = ConstantExpr::getPtrToInt(C, Ty);
if (GV->getMetadata(LLVMContext::MD_absolute_symbol))
return C;
auto SetAbsRange = [&](uint64_t Min, uint64_t Max) {
auto *MinC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Min));
auto *MaxC = ConstantAsMetadata::get(ConstantInt::get(IntPtrTy, Max));
GV->setMetadata(LLVMContext::MD_absolute_symbol,
MDNode::get(M.getContext(), {MinC, MaxC}));
};
if (AbsWidth == IntPtrTy->getBitWidth())
SetAbsRange(~0ull, ~0ull); // Full set.
else
SetAbsRange(0, 1ull << AbsWidth);
return C;
};
if (TIL.TheKind != TypeTestResolution::Unsat)
TIL.OffsetedGlobal = ImportGlobal("global_addr");
if (TIL.TheKind == TypeTestResolution::ByteArray ||
TIL.TheKind == TypeTestResolution::Inline ||
TIL.TheKind == TypeTestResolution::AllOnes) {
TIL.AlignLog2 = ImportConstant("align", TTRes.AlignLog2, 8, Int8Ty);
TIL.SizeM1 =
ImportConstant("size_m1", TTRes.SizeM1, TTRes.SizeM1BitWidth, IntPtrTy);
}
if (TIL.TheKind == TypeTestResolution::ByteArray) {
TIL.TheByteArray = ImportGlobal("byte_array");
TIL.BitMask = ImportConstant("bit_mask", TTRes.BitMask, 8, Int8PtrTy);
}
if (TIL.TheKind == TypeTestResolution::Inline)
TIL.InlineBits = ImportConstant(
"inline_bits", TTRes.InlineBits, 1 << TTRes.SizeM1BitWidth,
TTRes.SizeM1BitWidth <= 5 ? Int32Ty : Int64Ty);
return TIL;
}
void LowerTypeTestsModule::importTypeTest(CallInst *CI) {
auto TypeIdMDVal = dyn_cast<MetadataAsValue>(CI->getArgOperand(1));
if (!TypeIdMDVal)
report_fatal_error("Second argument of llvm.type.test must be metadata");
auto TypeIdStr = dyn_cast<MDString>(TypeIdMDVal->getMetadata());
if (!TypeIdStr)
report_fatal_error(
"Second argument of llvm.type.test must be a metadata string");
TypeIdLowering TIL = importTypeId(TypeIdStr->getString());
Value *Lowered = lowerTypeTestCall(TypeIdStr, CI, TIL);
CI->replaceAllUsesWith(Lowered);
CI->eraseFromParent();
}
// ThinLTO backend: the function F has a jump table entry; update this module
// accordingly. isDefinition describes the type of the jump table entry.
void LowerTypeTestsModule::importFunction(Function *F, bool isDefinition) {
assert(F->getType()->getAddressSpace() == 0);
GlobalValue::VisibilityTypes Visibility = F->getVisibility();
std::string Name = F->getName();
if (F->isDeclarationForLinker() && isDefinition) {
// Non-dso_local functions may be overriden at run time,
// don't short curcuit them
if (F->isDSOLocal()) {
Function *RealF = Function::Create(F->getFunctionType(),
GlobalValue::ExternalLinkage,
F->getAddressSpace(),
Name + ".cfi", &M);
RealF->setVisibility(GlobalVariable::HiddenVisibility);