P4C
The P4 Compiler
Loading...
Searching...
No Matches
big_int_util.h
1/*
2 * SPDX-FileCopyrightText: 2013 Barefoot Networks, Inc.
3 * Copyright 2013-present Barefoot Networks, Inc.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 */
7
8#ifndef LIB_BIG_INT_UTIL_H_
9#define LIB_BIG_INT_UTIL_H_
10
11#include <boost/version.hpp>
12
13#if BOOST_VERSION < 106700
14#include <boost/functional/hash.hpp>
15#endif
16
17#include "big_int.h"
18#include "hash.h"
19
20namespace P4::Util {
21
22// Useful functions for manipulating GMP values
23// (arbitrary-precision values)
24
25big_int ripBits(big_int &value, int bits);
26
27struct BitRange {
28 unsigned lowIndex;
29 unsigned highIndex;
30 big_int value;
31};
32
33// Find a consecutive scan of 1 bits at the "bottom"
34BitRange findOnes(const big_int &value);
35
36big_int cvtInt(const char *s, unsigned base);
37big_int shift_left(const big_int &v, unsigned bits);
38big_int shift_right(const big_int &v, unsigned bits);
39// Convert a slice [m:l] into a mask
40big_int maskFromSlice(unsigned m, unsigned l);
41big_int mask(unsigned bits);
42
43inline unsigned scan0_positive(const boost::multiprecision::cpp_int &val, unsigned pos) {
44 while (boost::multiprecision::bit_test(val, pos)) ++pos;
45 return pos;
46}
47inline unsigned scan1_positive(const boost::multiprecision::cpp_int &val, unsigned pos) {
48 if (val == 0 || pos > boost::multiprecision::msb(val)) return ~0U;
49 unsigned lsb = boost::multiprecision::lsb(val);
50 if (lsb >= pos) return lsb;
51 while (!boost::multiprecision::bit_test(val, pos)) ++pos;
52 return pos;
53}
54inline unsigned scan0(const boost::multiprecision::cpp_int &val, unsigned pos) {
55 if (val < 0) return scan1_positive(-val - 1, pos);
56 return scan0_positive(val, pos);
57}
58inline unsigned scan1(const boost::multiprecision::cpp_int &val, unsigned pos) {
59 if (val < 0) return scan0_positive(-val - 1, pos);
60 return scan1_positive(val, pos);
61}
62
63} // namespace P4::Util
64
65namespace P4 {
66
67static inline unsigned bitcount(big_int v) {
68 if (v < 0) return ~0U;
69 unsigned rv = 0;
70 while (v != 0) {
71 v &= v - 1;
72 ++rv;
73 }
74 return rv;
75}
76
77static inline int ffs(big_int v) {
78 if (v <= 0) return -1;
79 return boost::multiprecision::lsb(v);
80}
81
82static inline int floor_log2(big_int v) {
83 int rv = -1;
84 while (v > 0) {
85 rv++;
86 v /= 2;
87 }
88 return rv;
89}
90
91static inline int ceil_log2(big_int v) { return v ? floor_log2(v - 1) + 1 : -1; }
92
93template <>
94struct Util::Hasher<big_int> : Detail::StdHasher {};
95
96} // namespace P4
97
98#endif /* LIB_BIG_INT_UTIL_H_ */
Definition hash.h:90
TODO: this is not really specific to BMV2, it should reside somewhere else.
Definition applyOptionsPragmas.cpp:13
Definition big_int_util.h:27
Definition hash.h:123