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