Debian Codegraph @

Source/Core/Common/BitField.h

raw symbols SCIP
1 // Copyright 2014 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 // Copyright 2014 Tony Wasserka
5 // All rights reserved.
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions are met:
9 //
10 // * Redistributions of source code must retain the above copyright
11 // notice, this list of conditions and the following disclaimer.
12 // * Redistributions in binary form must reproduce the above copyright
13 // notice, this list of conditions and the following disclaimer in the
14 // documentation and/or other materials provided with the distribution.
15 // * Neither the name of the owner nor the names of its contributors may
16 // be used to endorse or promote products derived from this software
17 // without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 #pragma once
32
33 #include <cstddef>
34 #include <fmt/format.h>
35 #include <iterator>
36 #include <limits>
37 #include <type_traits>
38
39 #include "Common/Inline.h"
40
41 /*
42 * Abstract bitfield class
43 *
44 * Allows endianness-independent access to individual bitfields within some raw
45 * integer value. The assembly generated by this class is identical to the
46 * usage of raw bitfields, so it's a perfectly fine replacement.
47 *
48 * For BitField<X,Y,Z>, X is the distance of the bitfield to the LSB of the
49 * raw value, Y is the length in bits of the bitfield. Z is an integer type
50 * which determines the sign of the bitfield. Z must have the same size as the
51 * raw integer.
52 *
53 *
54 * General usage:
55 *
56 * Create a new union with the raw integer value as a member.
57 * Then for each bitfield you want to expose, add a BitField member
58 * in the union. The template parameters are the bit offset and the number
59 * of desired bits.
60 *
61 * Changes in the bitfield members will then get reflected in the raw integer
62 * value and vice-versa.
63 *
64 *
65 * Sample usage:
66 *
67 * union SomeRegister
68 * {
69 * u32 hex;
70 *
71 * BitField<0,7,u32> first_seven_bits; // unsigned
72 * BitField<7,8,u32> next_eight_bits; // unsigned
73 * BitField<3,15,s32> some_signed_fields; // signed
74 * };
75 *
76 * This is equivalent to the little-endian specific code:
77 *
78 * union SomeRegister
79 * {
80 * u32 hex;
81 *
82 * struct
83 * {
84 * u32 first_seven_bits : 7;
85 * u32 next_eight_bits : 8;
86 * };
87 * struct
88 * {
89 * u32 : 3; // padding
90 * s32 some_signed_fields : 15;
91 * };
92 * };
93 *
94 *
95 * Caveats:
96 *
97 * 1)
98 * BitField provides automatic casting from and to the storage type where
99 * appropriate. However, when using non-typesafe functions like printf, an
100 * explicit cast must be performed on the BitField object to make sure it gets
101 * passed correctly, e.g.:
102 * printf("Value: %d", (s32)some_register.some_signed_fields);
103 * Note that this does not apply when using fmt, as a formatter is provided that
104 * handles this conversion automatically.
105 *
106 * 2)
107 * Not really a caveat, but potentially irritating: This class is used in some
108 * packed structures that do not guarantee proper alignment. Therefore we have
109 * to use #pragma pack here not to pack the members of the class, but instead
110 * to break GCC's assumption that the members of the class are aligned on
111 * sizeof(StorageType).
112 * TODO(neobrain): Confirm that this is a proper fix and not just masking
113 * symptoms.
114 */
115 #pragma pack(1)
116 template <std::size_t position, std::size_t bits, typename T,
117 // StorageType is T for non-enum or the underlying-type for an enum.
118 typename StorageType = std::conditional_t<std::is_enum_v<T>, std::underlying_type<T>,
119 std::type_identity<T>>::type>
120 struct BitField
121 {
122 public:
123 // This constructor might be considered ambiguous:
124 // Would it initialize the storage or just the bitfield?
125 // Hence, delete it. Use the assignment operator to set bitfield values!
126 BitField(T val) = delete;
127
128 // Force default constructor to be created
129 // so that we can use this within unions
130 constexpr BitField() = default;
131
132 // Allow copy construction.
133 constexpr BitField(const BitField&) = default;
134
135 // We explicitly delete the copy assignment operator here, because the
136 // default copy assignment would copy the full storage value, rather than
137 // just the bits relevant to this particular bit field.
138 // Ideally, we would just implement the copy assignment to copy only the
139 // relevant bits, but we're prevented from doing that because the savestate
140 // code expects that this class is trivially copyable.
141 BitField& operator=(const BitField&) = delete;
142
143 DOLPHIN_FORCE_INLINE BitField& operator=(T val)
144 {
145 storage = (storage & ~GetMask()) | ((static_cast<StorageType>(val) << position) & GetMask());
146 return *this;
147 }
148
149 constexpr T Value() const { return Value(std::is_signed<T>()); }
150 constexpr operator T() const { return Value(); }
151 static constexpr bool IsSigned() { return std::is_signed<T>(); }
152 static constexpr std::size_t StartBit() { return position; }
153 static constexpr std::size_t NumBits() { return bits; }
154
155 private:
156 // Unsigned version of StorageType
157 using StorageTypeU = std::make_unsigned_t<StorageType>;
158
159 constexpr T Value(std::true_type) const
160 {
161 const size_t shift_amount = 8 * sizeof(StorageType) - bits;
162 return static_cast<T>((storage << (shift_amount - position)) >> shift_amount);
163 }
164
165 constexpr T Value(std::false_type) const
166 {
167 return static_cast<T>((storage & GetMask()) >> position);
168 }
169
170 static constexpr StorageType GetMask()
171 {
172 return (std::numeric_limits<StorageTypeU>::max() >> (8 * sizeof(StorageType) - bits))
173 << position;
174 }
175
176 StorageType storage;
177
178 static_assert(bits + position <= 8 * sizeof(StorageType), "Bitfield out of range");
179 static_assert(sizeof(T) <= sizeof(StorageType), "T must fit in StorageType");
180
181 // And, you know, just in case people specify something stupid like bits=position=0x80000000
182 static_assert(position < 8 * sizeof(StorageType), "Invalid position");
183 static_assert(bits <= 8 * sizeof(T), "Invalid number of bits");
184 static_assert(bits > 0, "Invalid number of bits");
185 };
186 #pragma pack()
187
188 // Use the underlying type's formatter for BitFields, if one exists
189 template <std::size_t position, std::size_t bits, typename T, typename S>
190 struct fmt::formatter<BitField<position, bits, T, S>>
191 {
192 fmt::formatter<T> m_formatter;
193 constexpr auto parse(format_parse_context& ctx) { return m_formatter.parse(ctx); }
194 template <typename FormatContext>
195 auto format(const BitField<position, bits, T, S>& bitfield, FormatContext& ctx) const
196 {
197 return m_formatter.format(bitfield.Value(), ctx);
198 }
199 };
200
201 // Language limitations require the following to make these formattable
202 // (formatter<BitFieldArray<position, bits, size, T>::Ref> is not legal)
203 template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
204 class BitFieldArrayConstRef;
205 template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
206 class BitFieldArrayRef;
207 template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
208 class BitFieldArrayConstIterator;
209 template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
210 class BitFieldArrayIterator;
211
212 #pragma pack(1)
213 template <std::size_t position, std::size_t bits, std::size_t size, typename T,
214 // StorageType is T for non-enum or the underlying-type for an enum.
215 typename StorageType = std::conditional_t<std::is_enum_v<T>, std::underlying_type<T>,
216 std::type_identity<T>>::type>
217 struct BitFieldArray
218 {
219 public:
220 using Ref = BitFieldArrayRef<position, bits, size, T, StorageType>;
221 using ConstRef = BitFieldArrayConstRef<position, bits, size, T, StorageType>;
222 using Iterator = BitFieldArrayIterator<position, bits, size, T, StorageType>;
223 using ConstIterator = BitFieldArrayConstIterator<position, bits, size, T, StorageType>;
224
225 // This constructor might be considered ambiguous:
226 // Would it initialize the storage or just the bitfield?
227 // Hence, delete it. Use the assignment operator to set bitfield values!
228 BitFieldArray(T val) = delete;
229
230 // Force default constructor to be created
231 // so that we can use this within unions
232 constexpr BitFieldArray() = default;
233
234 // We explicitly delete the copy assignment operator here, because the
235 // default copy assignment would copy the full storage value, rather than
236 // just the bits relevant to this particular bit field.
237 // Ideally, we would just implement the copy assignment to copy only the
238 // relevant bits, but we're prevented from doing that because the savestate
239 // code expects that this class is trivially copyable.
240 BitFieldArray& operator=(const BitFieldArray&) = delete;
241
242 constexpr bool IsSigned() const { return std::is_signed<T>(); }
243 constexpr std::size_t StartBit() const { return position; }
244 constexpr std::size_t NumBits() const { return bits; }
245 constexpr std::size_t Size() const { return size; }
246 constexpr std::size_t TotalNumBits() const { return bits * size; }
247
248 constexpr T Value(size_t index) const { return Value(std::is_signed<T>(), index); }
249 void SetValue(size_t index, T value)
250 {
251 const size_t pos = position + bits * index;
252 storage = (storage & ~GetElementMask(index)) |
253 ((static_cast<StorageType>(value) << pos) & GetElementMask(index));
254 }
255 Ref operator[](size_t index) { return Ref(this, index); }
256 constexpr const ConstRef operator[](size_t index) const { return ConstRef(this, index); }
257
258 constexpr Iterator begin() { return Iterator(this, 0); }
259 constexpr Iterator end() { return Iterator(this, size); }
260 constexpr ConstIterator begin() const { return ConstIterator(this, 0); }
261 constexpr ConstIterator end() const { return ConstIterator(this, size); }
262 constexpr ConstIterator cbegin() const { return begin(); }
263 constexpr ConstIterator cend() const { return end(); }
264
265 private:
266 // Unsigned version of StorageType
267 using StorageTypeU = std::make_unsigned_t<StorageType>;
268
269 constexpr T Value(std::true_type, size_t index) const
270 {
271 const size_t pos = position + bits * index;
272 const size_t shift_amount = 8 * sizeof(StorageType) - bits;
273 return static_cast<T>((storage << (shift_amount - pos)) >> shift_amount);
274 }
275
276 constexpr T Value(std::false_type, size_t index) const
277 {
278 const size_t pos = position + bits * index;
279 return static_cast<T>((storage & GetElementMask(index)) >> pos);
280 }
281
282 static constexpr StorageType GetElementMask(size_t index)
283 {
284 const size_t pos = position + bits * index;
285 return (std::numeric_limits<StorageTypeU>::max() >> (8 * sizeof(StorageType) - bits)) << pos;
286 }
287
288 StorageType storage;
289
290 static_assert(bits * size + position <= 8 * sizeof(StorageType), "Bitfield array out of range");
291 static_assert(sizeof(T) <= sizeof(StorageType), "T must fit in StorageType");
292
293 // And, you know, just in case people specify something stupid like bits=position=0x80000000
294 static_assert(position < 8 * sizeof(StorageType), "Invalid position");
295 static_assert(bits <= 8 * sizeof(T), "Invalid number of bits");
296 static_assert(bits > 0, "Invalid number of bits");
297 static_assert(size <= 8 * sizeof(StorageType), "Invalid size");
298 static_assert(size > 0, "Invalid size");
299 };
300 #pragma pack()
301
302 template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
303 class BitFieldArrayConstRef
304 {
305 friend struct BitFieldArray<position, bits, size, T, S>;
306 friend class BitFieldArrayConstIterator<position, bits, size, T, S>;
307
308 public:
309 constexpr T Value() const { return m_array->Value(m_index); }
310 constexpr operator T() const { return Value(); }
311
312 private:
313 constexpr BitFieldArrayConstRef(const BitFieldArray<position, bits, size, T, S>* array,
314 size_t index)
315 : m_array(array), m_index(index)
316 {
317 }
318
319 const BitFieldArray<position, bits, size, T, S>* const m_array;
320 const size_t m_index;
321 };
322
323 template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
324 class BitFieldArrayRef
325 {
326 friend struct BitFieldArray<position, bits, size, T, S>;
327 friend class BitFieldArrayIterator<position, bits, size, T, S>;
328
329 public:
330 constexpr T Value() const { return m_array->Value(m_index); }
331 constexpr operator T() const { return Value(); }
332 T operator=(const BitFieldArrayRef<position, bits, size, T, S>& value) const
333 {
334 m_array->SetValue(m_index, value);
335 return value;
336 }
337 T operator=(T value) const
338 {
339 m_array->SetValue(m_index, value);
340 return value;
341 }
342
343 private:
344 constexpr BitFieldArrayRef(BitFieldArray<position, bits, size, T, S>* array, size_t index)
345 : m_array(array), m_index(index)
346 {
347 }
348
349 BitFieldArray<position, bits, size, T, S>* const m_array;
350 const size_t m_index;
351 };
352
353 // Satisfies LegacyOutputIterator / std::output_iterator.
354 // Does not satisfy LegacyInputIterator / std::input_iterator as std::output_iterator_tag does not
355 // extend std::input_iterator_tag.
356 // Does not satisfy LegacyForwardIterator / std::forward_iterator, as that requires use of real
357 // references instead of proxy objects.
358 // This iterator allows use of BitFieldArray in range-based for loops, and with fmt::join.
359 template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
360 class BitFieldArrayIterator
361 {
362 friend struct BitFieldArray<position, bits, size, T, S>;
363
364 public:
365 using iterator_category = std::output_iterator_tag;
366 using value_type = T;
367 using difference_type = ptrdiff_t;
368 using pointer = void;
369 using reference = BitFieldArrayRef<position, bits, size, T, S>;
370
371 private:
372 constexpr BitFieldArrayIterator(BitFieldArray<position, bits, size, T, S>* array, size_t index)
373 : m_array(array), m_index(index)
374 {
375 }
376
377 public:
378 // Required by std::input_or_output_iterator
379 constexpr BitFieldArrayIterator() = default;
380 // Required by LegacyIterator
381 constexpr BitFieldArrayIterator(const BitFieldArrayIterator& other) = default;
382 // Required by LegacyIterator
383 BitFieldArrayIterator& operator=(const BitFieldArrayIterator& other) = default;
384 // Move constructor and assignment operators, explicitly defined for completeness
385 constexpr BitFieldArrayIterator(BitFieldArrayIterator&& other) = default;
386 BitFieldArrayIterator& operator=(BitFieldArrayIterator&& other) = default;
387
388 BitFieldArrayIterator& operator++()
389 {
390 m_index++;
391 return *this;
392 }
393 BitFieldArrayIterator operator++(int)
394 {
395 BitFieldArrayIterator other(*this);
396 ++*this;
397 return other;
398 }
399 constexpr reference operator*() const { return reference(m_array, m_index); }
400 constexpr bool operator==(BitFieldArrayIterator other) const { return m_index == other.m_index; }
401 constexpr bool operator!=(BitFieldArrayIterator other) const { return m_index != other.m_index; }
402
403 private:
404 BitFieldArray<position, bits, size, T, S>* m_array;
405 size_t m_index;
406 };
407
408 // Satisfies LegacyInputIterator / std::input_iterator.
409 // Does not satisfy LegacyForwardIterator / std::forward_iterator, as that requires use of real
410 // references instead of proxy objects.
411 // This iterator allows use of BitFieldArray in range-based for loops, and with fmt::join.
412 template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
413 class BitFieldArrayConstIterator
414 {
415 friend struct BitFieldArray<position, bits, size, T, S>;
416
417 public:
418 using iterator_category = std::input_iterator_tag;
419 using value_type = T;
420 using difference_type = ptrdiff_t;
421 using pointer = void;
422 using reference = BitFieldArrayConstRef<position, bits, size, T, S>;
423
424 private:
425 constexpr BitFieldArrayConstIterator(const BitFieldArray<position, bits, size, T, S>* array,
426 size_t index)
427 : m_array(array), m_index(index)
428 {
429 }
430
431 public:
432 // Required by std::input_or_output_iterator
433 constexpr BitFieldArrayConstIterator() = default;
434 // Required by LegacyIterator
435 constexpr BitFieldArrayConstIterator(const BitFieldArrayConstIterator& other) = default;
436 // Required by LegacyIterator
437 BitFieldArrayConstIterator& operator=(const BitFieldArrayConstIterator& other) = default;
438 // Move constructor and assignment operators, explicitly defined for completeness
439 constexpr BitFieldArrayConstIterator(BitFieldArrayConstIterator&& other) = default;
440 BitFieldArrayConstIterator& operator=(BitFieldArrayConstIterator&& other) = default;
441
442 public:
443 BitFieldArrayConstIterator& operator++()
444 {
445 m_index++;
446 return *this;
447 }
448 BitFieldArrayConstIterator operator++(int)
449 {
450 BitFieldArrayConstIterator other(*this);
451 ++*this;
452 return other;
453 }
454 constexpr reference operator*() const { return reference(m_array, m_index); }
455 constexpr bool operator==(BitFieldArrayConstIterator other) const
456 {
457 return m_index == other.m_index;
458 }
459 constexpr bool operator!=(BitFieldArrayConstIterator other) const
460 {
461 return m_index != other.m_index;
462 }
463
464 private:
465 const BitFieldArray<position, bits, size, T, S>* m_array;
466 size_t m_index;
467 };
468
469 template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
470 struct fmt::formatter<BitFieldArrayRef<position, bits, size, T, S>>
471 {
472 fmt::formatter<T> m_formatter;
473 constexpr auto parse(format_parse_context& ctx) { return m_formatter.parse(ctx); }
474 template <typename FormatContext>
475 auto format(const BitFieldArrayRef<position, bits, size, T, S>& ref, FormatContext& ctx) const
476 {
477 return m_formatter.format(ref.Value(), ctx);
478 }
479 };
480
481 template <std::size_t position, std::size_t bits, std::size_t size, typename T, typename S>
482 struct fmt::formatter<BitFieldArrayConstRef<position, bits, size, T, S>>
483 {
484 fmt::formatter<T> m_formatter;
485 constexpr auto parse(format_parse_context& ctx) { return m_formatter.parse(ctx); }
486 template <typename FormatContext>
487 auto format(const BitFieldArrayConstRef<position, bits, size, T, S>& ref,
488 FormatContext& ctx) const
489 {
490 return m_formatter.format(ref.Value(), ctx);
491 }
492 };