bitfield.hh revision 4261
1/*
2 * Copyright (c) 2003-2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Steve Reinhardt
29 *          Nathan Binkert
30 */
31
32#ifndef __BASE_BITFIELD_HH__
33#define __BASE_BITFIELD_HH__
34
35#include <inttypes.h>
36
37/**
38 * Generate a 64-bit mask of 'nbits' 1s, right justified.
39 */
40inline uint64_t
41mask(int nbits)
42{
43    return (nbits == 64) ? (uint64_t)-1LL : (1ULL << nbits) - 1;
44}
45
46
47
48/**
49 * Extract the bitfield from position 'first' to 'last' (inclusive)
50 * from 'val' and right justify it.  MSB is numbered 63, LSB is 0.
51 */
52template <class T>
53inline
54T
55bits(T val, int first, int last)
56{
57    int nbits = first - last + 1;
58    return (val >> last) & mask(nbits);
59}
60
61/**
62 * Mask off the given bits in place like bits() but without shifting.
63 * msb = 63, lsb = 0
64 */
65template <class T>
66inline
67T
68mbits(T val, int first, int last)
69{
70    return val & (mask(first+1) & ~mask(last));
71}
72
73inline uint64_t
74mask(int first, int last)
75{
76    return mbits((uint64_t)-1LL, first, last);
77}
78
79/**
80 * Sign-extend an N-bit value to 64 bits.
81 */
82template <int N>
83inline
84int64_t
85sext(uint64_t val)
86{
87    int sign_bit = bits(val, N-1, N-1);
88    return sign_bit ? (val | ~mask(N)) : val;
89}
90
91/**
92 * Return val with bits first to last set to bit_val
93 */
94template <class T, class B>
95inline
96T
97insertBits(T val, int first, int last, B bit_val)
98{
99    T bmask = mask(first - last + 1) << last;
100    return ((bit_val << last) & bmask) | (val & ~bmask);
101}
102
103/**
104 * A convenience function to replace bits first to last of val with bit_val
105 * in place.
106 */
107template <class T, class B>
108inline
109void
110replaceBits(T& val, int first, int last, B bit_val)
111{
112    val = insertBits(val, first, last, bit_val);
113}
114
115/**
116 * Returns the bit position of the MSB that is set in the input
117 */
118inline
119int
120findMsbSet(uint64_t val) {
121    int msb = 0;
122    if (!val)
123        return 0;
124    if (bits(val, 63,32)) { msb += 32; val >>= 32; }
125    if (bits(val, 31,16)) { msb += 16; val >>= 16; }
126    if (bits(val, 15,8))  { msb += 8;  val >>= 8;  }
127    if (bits(val, 7,4))   { msb += 4;  val >>= 4;  }
128    if (bits(val, 3,2))   { msb += 2;  val >>= 2;  }
129    if (bits(val, 1,1))   { msb += 1; }
130    return msb;
131}
132
133//	The following implements the BitUnion system of defining bitfields
134//on top of an underlying class. This is done through the extensive use of
135//both named and unnamed unions which all contain the same actual storage.
136//Since they're unioned with each other, all of these storage locations
137//overlap. This allows all of the bitfields to manipulate the same data
138//without having to know about each other. More details are provided with the
139//individual components.
140
141//This namespace is for classes which implement the backend of the BitUnion
142//stuff. Don't use any of this directly! Use the macros at the end instead.
143namespace BitfieldBackend
144{
145    //A base class for all bitfields. It instantiates the actual storage,
146    //and provides getBits and setBits functions for manipulating it. The
147    //Data template parameter is type of the underlying storage.
148    template<class Data>
149    class BitfieldBase
150    {
151      protected:
152        Data __data;
153
154        //This function returns a range of bits from the underlying storage.
155        //It relies on the "bits" function above. It's the user's
156        //responsibility to make sure that there is a properly overloaded
157        //version of this function for whatever type they want to overlay.
158        inline uint64_t
159        getBits(int first, int last)
160        {
161            return bits(__data, first, last);
162        }
163
164        //Similar to the above, but for settings bits with replaceBits.
165        inline void
166        setBits(int first, int last, uint64_t val)
167        {
168            replaceBits(__data, first, last, val);
169        }
170    };
171
172    //A class which specializes a given base so that it can only be read
173    //from. This is accomplished by only passing through the conversion
174    //operator and explicitly making sure the assignment operator is blocked.
175    template<class Type, class Base>
176    class _BitfieldRO : public Base
177    {
178      private:
179        const Type
180        operator=(const Type & _data);
181
182      public:
183        operator const Type ()
184        {
185            return *((Base *)this);
186        }
187    };
188
189    //Similar to the above, but only allows writing.
190    template<class Type, class Base>
191    class _BitfieldWO : public Base
192    {
193      private:
194        operator const Type ();
195
196      public:
197        const Type operator=(const Type & _data)
198        {
199            *((Base *)this) = _data;
200            return _data;
201        }
202    };
203
204    //This class implements ordinary bitfields, that is a span of bits
205    //who's msb is "first", and who's lsb is "last".
206    template<class Data, int first, int last=first>
207    class _Bitfield : public BitfieldBase<Data>
208    {
209      public:
210        operator const Data ()
211        {
212            return this->getBits(first, last);
213        }
214
215        const Data
216        operator=(const Data & _data)
217        {
218            this->setBits(first, last, _data);
219            return _data;
220        }
221    };
222
223    //When a BitUnion is set up, an underlying class is created which holds
224    //the actual union. This class then inherits from it, and provids the
225    //implementations for various operators. Setting things up this way
226    //prevents having to redefine these functions in every different BitUnion
227    //type. More operators could be implemented in the future, as the need
228    //arises.
229    template <class Type, class Base>
230    class BitUnionOperators : public Base
231    {
232      public:
233        operator const Type ()
234        {
235            return Base::__data;
236        }
237
238        const Type
239        operator=(const Type & _data)
240        {
241            Base::__data = _data;
242        }
243
244        bool
245        operator<(const Base & base)
246        {
247            return Base::__data < base.__data;
248        }
249
250        bool
251        operator==(const Base & base)
252        {
253            return Base::__data == base.__data;
254        }
255    };
256}
257
258//This macro is a backend for other macros that specialize it slightly.
259//First, it creates/extends a namespace "BitfieldUnderlyingClasses" and
260//sticks the class which has the actual union in it, which
261//BitfieldOperators above inherits from. Putting these classes in a special
262//namespace ensures that there will be no collisions with other names as long
263//as the BitUnion names themselves are all distinct and nothing else uses
264//the BitfieldUnderlyingClasses namespace, which is unlikely. The class itself
265//creates a typedef of the "type" parameter called __DataType. This allows
266//the type to propagate outside of the macro itself in a controlled way.
267//Finally, the base storage is defined which BitfieldOperators will refer to
268//in the operators it defines. This macro is intended to be followed by
269//bitfield definitions which will end up inside it's union. As explained
270//above, these is overlayed the __data member in its entirety by each of the
271//bitfields which are defined in the union, creating shared storage with no
272//overhead.
273#define __BitUnion(type, name) \
274    namespace BitfieldUnderlyingClasses \
275    { \
276        class name; \
277    } \
278    class BitfieldUnderlyingClasses::name { \
279      public: \
280        typedef type __DataType; \
281        union { \
282            type __data;\
283
284//This closes off the class and union started by the above macro. It is
285//followed by a typedef which makes "name" refer to a BitfieldOperator
286//class inheriting from the class and union just defined, which completes
287//building up the type for the user.
288#define EndBitUnion(name) \
289        }; \
290    }; \
291    typedef BitfieldBackend::BitUnionOperators< \
292        BitfieldUnderlyingClasses::name::__DataType, \
293        BitfieldUnderlyingClasses::name> name;
294
295//This sets up a bitfield which has other bitfields nested inside of it. The
296//__data member functions like the "underlying storage" of the top level
297//BitUnion. Like everything else, it overlays with the top level storage, so
298//making it a regular bitfield type makes the entire thing function as a
299//regular bitfield when referred to by itself. The operators are defined in
300//the macro itself instead of a class for technical reasons. If someone
301//determines a way to move them to one, please do so.
302#define __SubBitUnion(type, name) \
303        union { \
304            type __data; \
305            inline operator const __DataType () \
306            { return __data; } \
307            \
308            inline const __DataType operator = (const __DataType & _data) \
309            { __data = _data; }
310
311//This closes off the union created above and gives it a name. Unlike the top
312//level BitUnion, we're interested in creating an object instead of a type.
313#define EndSubBitUnion(name) } name;
314
315//The preprocessor will treat everything inside of parenthesis as a single
316//argument even if it has commas in it. This is used to pass in templated
317//classes which typically have commas to seperate their parameters.
318#define wrap(guts) guts
319
320//Read only bitfields
321//This wraps another bitfield class inside a _BitfieldRO class using
322//inheritance. As explained above, the _BitfieldRO class only passes through
323//the conversion operator, so the underlying bitfield can then only be read
324//from.
325#define __BitfieldRO(base) \
326    BitfieldBackend::_BitfieldRO<__DataType, base>
327#define __SubBitUnionRO(name, base) \
328    __SubBitUnion(wrap(_BitfieldRO<__DataType, base>), name)
329
330//Write only bitfields
331//Similar to above, but for making write only versions of bitfields with
332//_BitfieldWO.
333#define __BitfieldWO(base) \
334    BitfieldBackend::_BitfieldWO<__DataType, base>
335#define __SubBitUnionWO(name, base) \
336    __SubBitUnion(wrap(_BitfieldWO<__DataType, base>), name)
337
338//Regular bitfields
339//This uses all of the above to define macros for read/write, read only, and
340//write only versions of regular bitfields.
341#define Bitfield(first, last) \
342    BitfieldBackend::_Bitfield<__DataType, first, last>
343#define SubBitUnion(name, first, last) \
344    __SubBitUnion(Bitfield(first, last), name)
345#define BitfieldRO(first, last) __BitfieldRO(Bitfield(first, last))
346#define SubBitUnionRO(name, first, last) \
347    __SubBitUnionRO(Bitfield(first, last), name)
348#define BitfieldWO(first, last) __BitfieldWO(Bitfield(first, last))
349#define SubBitUnionWO(name, first, last) \
350    __SubBitUnionWO(Bitfield(first, last), name)
351
352//Use this to define an arbitrary type overlayed with bitfields.
353#define BitUnion(type, name) __BitUnion(type, name)
354
355//Use this to define conveniently sized values overlayed with bitfields.
356#define BitUnion64(name) __BitUnion(uint64_t, name)
357#define BitUnion32(name) __BitUnion(uint32_t, name)
358#define BitUnion16(name) __BitUnion(uint16_t, name)
359#define BitUnion8(name) __BitUnion(uint8_t, name)
360
361#endif // __BASE_BITFIELD_HH__
362