LLVM 24.0.0git
LowerTypeTests.h
Go to the documentation of this file.
1//===- LowerTypeTests.h - type metadata lowering pass -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines parts of the type test lowering pass implementation that
10// may be usefully unit tested.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_TRANSFORMS_IPO_LOWERTYPETESTS_H
15#define LLVM_TRANSFORMS_IPO_LOWERTYPETESTS_H
16
17#include <cstdint>
18#include <cstring>
19#include <limits>
20#include <set>
21#include <vector>
22
23#include "llvm/ADT/ArrayRef.h"
26#include "llvm/ADT/SetVector.h"
28#include "llvm/IR/PassManager.h"
30
31namespace llvm {
32
33class Function;
34class GlobalObject;
35class GlobalValue;
36class Module;
38class raw_ostream;
39
40namespace lowertypetests {
41
42struct BitSetInfo {
43 // The indices of the set bits in the bitset.
44 std::set<uint64_t> Bits;
45
46 // The byte offset into the combined global represented by the bitset.
48
49 // The size of the bitset in bits.
51
52 // Log2 alignment of the bit set relative to the combined global.
53 // For example, a log2 alignment of 3 means that bits in the bitset
54 // represent addresses 8 bytes apart.
55 unsigned AlignLog2;
56
57 bool isSingleOffset() const {
58 return Bits.size() == 1;
59 }
60
61 bool isAllOnes() const {
62 return Bits.size() == BitSize;
63 }
64
66
67 LLVM_ABI void print(raw_ostream &OS) const;
68};
69
72 uint64_t Min = std::numeric_limits<uint64_t>::max();
74
76 if (!Offsets.empty()) {
77 auto [MinIt, MaxIt] = std::minmax_element(Offsets.begin(), Offsets.end());
78 Min = *MinIt;
79 Max = *MaxIt;
80 }
81 }
82
84};
85
86/// This class implements a layout algorithm for globals referenced by bit sets
87/// that tries to keep members of small bit sets together. This can
88/// significantly reduce bit set sizes in many cases.
89///
90/// It works by assembling fragments of layout from sets of referenced globals.
91/// Each set of referenced globals causes the algorithm to create a new
92/// fragment, which is assembled by appending each referenced global in the set
93/// into the fragment. If a referenced global has already been referenced by an
94/// fragment created earlier, we instead delete that fragment and append its
95/// contents into the fragment we are assembling.
96///
97/// By starting with the smallest fragments, we minimize the size of the
98/// fragments that are copied into larger fragments. This is most intuitively
99/// thought about when considering the case where the globals are virtual tables
100/// and the bit sets represent their derived classes: in a single inheritance
101/// hierarchy, the optimum layout would involve a depth-first search of the
102/// class hierarchy (and in fact the computed layout ends up looking a lot like
103/// a DFS), but a naive DFS would not work well in the presence of multiple
104/// inheritance. This aspect of the algorithm ends up fitting smaller
105/// hierarchies inside larger ones where that would be beneficial.
106///
107/// For example, consider this class hierarchy:
108///
109/// A B
110/// \ / | \
111/// C D E
112///
113/// We have five bit sets: bsA (A, C), bsB (B, C, D, E), bsC (C), bsD (D) and
114/// bsE (E). If we laid out our objects by DFS traversing B followed by A, our
115/// layout would be {B, C, D, E, A}. This is optimal for bsB as it needs to
116/// cover the only 4 objects in its hierarchy, but not for bsA as it needs to
117/// cover 5 objects, i.e. the entire layout. Our algorithm proceeds as follows:
118///
119/// Add bsC, fragments {{C}}
120/// Add bsD, fragments {{C}, {D}}
121/// Add bsE, fragments {{C}, {D}, {E}}
122/// Add bsA, fragments {{A, C}, {D}, {E}}
123/// Add bsB, fragments {{B, A, C, D, E}}
124///
125/// This layout is optimal for bsA, as it now only needs to cover two (i.e. 3
126/// fewer) objects, at the cost of bsB needing to cover 1 more object.
127///
128/// The bit set lowering pass assigns an object index to each object that needs
129/// to be laid out, and calls addFragment for each bit set passing the object
130/// indices of its referenced globals. It then assembles a layout by calling
131/// build().
133 /// The computed layout. Each element of this vector contains a fragment of
134 /// layout (which may be empty) consisting of object indices.
135 std::vector<std::vector<uint64_t>> Fragments;
136
137 /// Mapping from object index to fragment index.
138 std::vector<uint64_t> FragmentMap;
139
140 /// Optional comparator for object hotness/ordering.
142
143public:
144 /// Construct a layout builder for \p NumObjects objects.
145 /// If \p Less is provided, it is used to sort sub-fragments and root
146 /// fragments by maximum element.
148 unique_function<bool(uint64_t, uint64_t)> Less = nullptr)
149 : Fragments(1), FragmentMap(NumObjects), Less(std::move(Less)) {}
150
151 /// Add F to the layout while trying to keep its indices contiguous.
152 /// If a previously seen fragment uses any of F's indices, that
153 /// fragment will be laid out inside F.
154 LLVM_ABI void addFragment(const std::set<uint64_t> &F);
155
156 /// Flatten fragments into a single layout and return it.
157 LLVM_ABI const std::vector<uint64_t> &build();
158};
159
160/// This class is used to build a byte array containing overlapping bit sets. By
161/// loading from indexed offsets into the byte array and applying a mask, a
162/// program can test bits from the bit set with a relatively short instruction
163/// sequence. For example, suppose we have 15 bit sets to lay out:
164///
165/// A (16 bits), B (15 bits), C (14 bits), D (13 bits), E (12 bits),
166/// F (11 bits), G (10 bits), H (9 bits), I (7 bits), J (6 bits), K (5 bits),
167/// L (4 bits), M (3 bits), N (2 bits), O (1 bit)
168///
169/// These bits can be laid out in a 16-byte array like this:
170///
171/// Byte Offset
172/// 0123456789ABCDEF
173/// Bit
174/// 7 HHHHHHHHHIIIIIII
175/// 6 GGGGGGGGGGJJJJJJ
176/// 5 FFFFFFFFFFFKKKKK
177/// 4 EEEEEEEEEEEELLLL
178/// 3 DDDDDDDDDDDDDMMM
179/// 2 CCCCCCCCCCCCCCNN
180/// 1 BBBBBBBBBBBBBBBO
181/// 0 AAAAAAAAAAAAAAAA
182///
183/// For example, to test bit X of A, we evaluate ((bits[X] & 1) != 0), or to
184/// test bit X of I, we evaluate ((bits[9 + X] & 0x80) != 0). This can be done
185/// in 1-2 machine instructions on x86, or 4-6 instructions on ARM.
186///
187/// This is a byte array, rather than (say) a 2-byte array or a 4-byte array,
188/// because for one thing it gives us better packing (the more bins there are,
189/// the less evenly they will be filled), and for another, the instruction
190/// sequences can be slightly shorter, both on x86 and ARM.
192 /// The byte array built so far.
193 std::vector<uint8_t> Bytes;
194
195 enum { BitsPerByte = 8 };
196
197 /// The number of bytes allocated so far for each of the bits.
199
201 memset(BitAllocs, 0, sizeof(BitAllocs));
202 }
203
204 /// Allocate BitSize bits in the byte array where Bits contains the bits to
205 /// set. AllocByteOffset is set to the offset within the byte array and
206 /// AllocMask is set to the bitmask for those bits. This uses the LPT (Longest
207 /// Processing Time) multiprocessor scheduling algorithm to lay out the bits
208 /// efficiently; the pass allocates bit sets in decreasing size order.
209 LLVM_ABI void allocate(const std::set<uint64_t> &Bits, uint64_t BitSize,
210 uint64_t &AllocByteOffset, uint8_t &AllocMask);
211};
212
214
215/// Returns whether a global or its associated global has attached type
216/// metadata.
218
219/// Finds all functions and aliases in \p M that may need CFI jump table
220/// entries.
222
223/// Finds all 64-bit numeric type identifiers in \p M used for cross-DSO CFI.
225
226/// Creates cfi.functions, aliases, and symvers named metadata in \p DestM
227/// for CFI functions in \p CfiFunctions from source module \p SrcM.
228LLVM_ABI void createCfiMetadata(Module &DestM, const Module &SrcM,
229 ArrayRef<GlobalValue *> CfiFunctions);
230
231/// Specifies how to drop type tests.
232enum class DropTestKind {
233 Assume, /// Drop only llvm.assumes using type test value.
234 All, /// Drop the type test and all uses.
235};
236
237} // end namespace lowertypetests
238
239class LowerTypeTestsPass : public RequiredPassInfoMixin<LowerTypeTestsPass> {
240 bool UseCommandLine = false;
241
242 ModuleSummaryIndex *ExportSummary = nullptr;
243 const ModuleSummaryIndex *ImportSummary = nullptr;
244
245public:
246 LowerTypeTestsPass() : UseCommandLine(true) {}
248 const ModuleSummaryIndex *ImportSummary)
249 : ExportSummary(ExportSummary), ImportSummary(ImportSummary) {}
250
252};
253
266
268 : public OptionalPassInfoMixin<SimplifyTypeTestsPass> {
269public:
271};
272
273} // end namespace llvm
274
275#endif // LLVM_TRANSFORMS_IPO_LOWERTYPETESTS_H
unsigned uint64_t
#define LLVM_ABI
Definition Compiler.h:215
This file provides a collection of function (or more generally, callable) type erasure utilities supp...
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
DropTypeTestsPass(lowertypetests::DropTestKind Kind=lowertypetests::DropTestKind::Assume)
LowerTypeTestsPass(ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
A vector that has set insertion semantics.
Definition SetVector.h:57
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
An efficient, type-erasing, non-owning reference to a callable.
GlobalLayoutBuilder(uint64_t NumObjects, unique_function< bool(uint64_t, uint64_t)> Less=nullptr)
Construct a layout builder for NumObjects objects.
LLVM_ABI const std::vector< uint64_t > & build()
Flatten fragments into a single layout and return it.
LLVM_ABI void addFragment(const std::set< uint64_t > &F)
Add F to the layout while trying to keep its indices contiguous.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unique_function is a type-erasing functor similar to std::function.
LLVM_ABI SetVector< uint64_t > findCfiTypeIds(const Module &M)
Finds all 64-bit numeric type identifiers in M used for cross-DSO CFI.
DropTestKind
Specifies how to drop type tests.
@ All
Drop only llvm.assumes using type test value.
LLVM_ABI void createCfiMetadata(Module &DestM, const Module &SrcM, ArrayRef< GlobalValue * > CfiFunctions)
Creates cfi.functions, aliases, and symvers named metadata in DestM for CFI functions in CfiFunctions...
LLVM_ABI bool isJumpTableCanonical(Function *F)
LLVM_ABI bool hasTypeMetadata(const GlobalObject &GO)
Returns whether a global or its associated global has attached type metadata.
LLVM_ABI SetVector< GlobalValue * > findCfiFunctions(Module &M)
Finds all functions and aliases in M that may need CFI jump table entries.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
A CRTP mix-in for passes that can be skipped.
A CRTP mix-in for passes that should not be skipped.
SmallVector< uint64_t, 16 > Offsets
BitSetBuilder(ArrayRef< uint64_t > Offsets)
LLVM_ABI bool containsGlobalOffset(uint64_t Offset) const
LLVM_ABI void print(raw_ostream &OS) const
uint64_t BitAllocs[BitsPerByte]
The number of bytes allocated so far for each of the bits.
std::vector< uint8_t > Bytes
The byte array built so far.
LLVM_ABI void allocate(const std::set< uint64_t > &Bits, uint64_t BitSize, uint64_t &AllocByteOffset, uint8_t &AllocMask)
Allocate BitSize bits in the byte array where Bits contains the bits to set.