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
20#include "llvm/IR/PassManager.h"
22#include <cstdint>
23#include <cstring>
24#include <limits>
25#include <set>
26#include <vector>
27
28namespace llvm {
29
30class Module;
32class raw_ostream;
33
34namespace lowertypetests {
35
36struct BitSetInfo {
37 // The indices of the set bits in the bitset.
38 std::set<uint64_t> Bits;
39
40 // The byte offset into the combined global represented by the bitset.
42
43 // The size of the bitset in bits.
45
46 // Log2 alignment of the bit set relative to the combined global.
47 // For example, a log2 alignment of 3 means that bits in the bitset
48 // represent addresses 8 bytes apart.
49 unsigned AlignLog2;
50
51 bool isSingleOffset() const {
52 return Bits.size() == 1;
53 }
54
55 bool isAllOnes() const {
56 return Bits.size() == BitSize;
57 }
58
60
61 LLVM_ABI void print(raw_ostream &OS) const;
62};
63
66 uint64_t Min = std::numeric_limits<uint64_t>::max();
68
70 if (!Offsets.empty()) {
71 auto [MinIt, MaxIt] = std::minmax_element(Offsets.begin(), Offsets.end());
72 Min = *MinIt;
73 Max = *MaxIt;
74 }
75 }
76
78};
79
80/// This class implements a layout algorithm for globals referenced by bit sets
81/// that tries to keep members of small bit sets together. This can
82/// significantly reduce bit set sizes in many cases.
83///
84/// It works by assembling fragments of layout from sets of referenced globals.
85/// Each set of referenced globals causes the algorithm to create a new
86/// fragment, which is assembled by appending each referenced global in the set
87/// into the fragment. If a referenced global has already been referenced by an
88/// fragment created earlier, we instead delete that fragment and append its
89/// contents into the fragment we are assembling.
90///
91/// By starting with the smallest fragments, we minimize the size of the
92/// fragments that are copied into larger fragments. This is most intuitively
93/// thought about when considering the case where the globals are virtual tables
94/// and the bit sets represent their derived classes: in a single inheritance
95/// hierarchy, the optimum layout would involve a depth-first search of the
96/// class hierarchy (and in fact the computed layout ends up looking a lot like
97/// a DFS), but a naive DFS would not work well in the presence of multiple
98/// inheritance. This aspect of the algorithm ends up fitting smaller
99/// hierarchies inside larger ones where that would be beneficial.
100///
101/// For example, consider this class hierarchy:
102///
103/// A B
104/// \ / | \
105/// C D E
106///
107/// We have five bit sets: bsA (A, C), bsB (B, C, D, E), bsC (C), bsD (D) and
108/// bsE (E). If we laid out our objects by DFS traversing B followed by A, our
109/// layout would be {B, C, D, E, A}. This is optimal for bsB as it needs to
110/// cover the only 4 objects in its hierarchy, but not for bsA as it needs to
111/// cover 5 objects, i.e. the entire layout. Our algorithm proceeds as follows:
112///
113/// Add bsC, fragments {{C}}
114/// Add bsD, fragments {{C}, {D}}
115/// Add bsE, fragments {{C}, {D}, {E}}
116/// Add bsA, fragments {{A, C}, {D}, {E}}
117/// Add bsB, fragments {{B, A, C, D, E}}
118///
119/// This layout is optimal for bsA, as it now only needs to cover two (i.e. 3
120/// fewer) objects, at the cost of bsB needing to cover 1 more object.
121///
122/// The bit set lowering pass assigns an object index to each object that needs
123/// to be laid out, and calls addFragment for each bit set passing the object
124/// indices of its referenced globals. It then assembles a layout by calling
125/// build().
127 /// The computed layout. Each element of this vector contains a fragment of
128 /// layout (which may be empty) consisting of object indices.
129 std::vector<std::vector<uint64_t>> Fragments;
130
131 /// Mapping from object index to fragment index.
132 std::vector<uint64_t> FragmentMap;
133
134 /// Optional comparator for object hotness/ordering.
136
137public:
138 /// Construct a layout builder for \p NumObjects objects.
139 /// If \p Less is provided, it is used to sort sub-fragments and root
140 /// fragments by maximum element.
142 unique_function<bool(uint64_t, uint64_t)> Less = nullptr)
143 : Fragments(1), FragmentMap(NumObjects), Less(std::move(Less)) {}
144
145 /// Add F to the layout while trying to keep its indices contiguous.
146 /// If a previously seen fragment uses any of F's indices, that
147 /// fragment will be laid out inside F.
148 LLVM_ABI void addFragment(const std::set<uint64_t> &F);
149
150 /// Flatten fragments into a single layout and return it.
151 LLVM_ABI const std::vector<uint64_t> &build();
152};
153
154/// This class is used to build a byte array containing overlapping bit sets. By
155/// loading from indexed offsets into the byte array and applying a mask, a
156/// program can test bits from the bit set with a relatively short instruction
157/// sequence. For example, suppose we have 15 bit sets to lay out:
158///
159/// A (16 bits), B (15 bits), C (14 bits), D (13 bits), E (12 bits),
160/// F (11 bits), G (10 bits), H (9 bits), I (7 bits), J (6 bits), K (5 bits),
161/// L (4 bits), M (3 bits), N (2 bits), O (1 bit)
162///
163/// These bits can be laid out in a 16-byte array like this:
164///
165/// Byte Offset
166/// 0123456789ABCDEF
167/// Bit
168/// 7 HHHHHHHHHIIIIIII
169/// 6 GGGGGGGGGGJJJJJJ
170/// 5 FFFFFFFFFFFKKKKK
171/// 4 EEEEEEEEEEEELLLL
172/// 3 DDDDDDDDDDDDDMMM
173/// 2 CCCCCCCCCCCCCCNN
174/// 1 BBBBBBBBBBBBBBBO
175/// 0 AAAAAAAAAAAAAAAA
176///
177/// For example, to test bit X of A, we evaluate ((bits[X] & 1) != 0), or to
178/// test bit X of I, we evaluate ((bits[9 + X] & 0x80) != 0). This can be done
179/// in 1-2 machine instructions on x86, or 4-6 instructions on ARM.
180///
181/// This is a byte array, rather than (say) a 2-byte array or a 4-byte array,
182/// because for one thing it gives us better packing (the more bins there are,
183/// the less evenly they will be filled), and for another, the instruction
184/// sequences can be slightly shorter, both on x86 and ARM.
186 /// The byte array built so far.
187 std::vector<uint8_t> Bytes;
188
189 enum { BitsPerByte = 8 };
190
191 /// The number of bytes allocated so far for each of the bits.
193
195 memset(BitAllocs, 0, sizeof(BitAllocs));
196 }
197
198 /// Allocate BitSize bits in the byte array where Bits contains the bits to
199 /// set. AllocByteOffset is set to the offset within the byte array and
200 /// AllocMask is set to the bitmask for those bits. This uses the LPT (Longest
201 /// Processing Time) multiprocessor scheduling algorithm to lay out the bits
202 /// efficiently; the pass allocates bit sets in decreasing size order.
203 LLVM_ABI void allocate(const std::set<uint64_t> &Bits, uint64_t BitSize,
204 uint64_t &AllocByteOffset, uint8_t &AllocMask);
205};
206
208
209/// Specifies how to drop type tests.
210enum class DropTestKind {
211 Assume, /// Drop only llvm.assumes using type test value.
212 All, /// Drop the type test and all uses.
213};
214
215} // end namespace lowertypetests
216
217class LowerTypeTestsPass : public RequiredPassInfoMixin<LowerTypeTestsPass> {
218 bool UseCommandLine = false;
219
220 ModuleSummaryIndex *ExportSummary = nullptr;
221 const ModuleSummaryIndex *ImportSummary = nullptr;
222
223public:
224 LowerTypeTestsPass() : UseCommandLine(true) {}
226 const ModuleSummaryIndex *ImportSummary)
227 : ExportSummary(ExportSummary), ImportSummary(ImportSummary) {}
228
230};
231
244
246 : public OptionalPassInfoMixin<SimplifyTypeTestsPass> {
247public:
249};
250
251} // end namespace llvm
252
253#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 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
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.
DropTestKind
Specifies how to drop type tests.
@ All
Drop only llvm.assumes using type test value.
LLVM_ABI bool isJumpTableCanonical(Function *F)
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.