1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "absl/numeric/int128.h"
16
17 #include <stddef.h>
18
19 #include <cassert>
20 #include <iomanip>
21 #include <ostream> // NOLINT(readability/streams)
22 #include <sstream>
23 #include <string>
24 #include <type_traits>
25
26 #include "absl/base/optimization.h"
27 #include "absl/numeric/bits.h"
28
29 namespace absl {
30 ABSL_NAMESPACE_BEGIN
31
32 ABSL_DLL const uint128 kuint128max = MakeUint128(
33 std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::max());
34
35 namespace {
36
37 // Returns the 0-based position of the last set bit (i.e., most significant bit)
38 // in the given uint128. The argument is not 0.
39 //
40 // For example:
41 // Given: 5 (decimal) == 101 (binary)
42 // Returns: 2
Fls128(uint128 n)43 inline ABSL_ATTRIBUTE_ALWAYS_INLINE int Fls128(uint128 n) {
44 if (uint64_t hi = Uint128High64(n)) {
45 ABSL_ASSUME(hi != 0);
46 return 127 - countl_zero(hi);
47 }
48 const uint64_t low = Uint128Low64(n);
49 ABSL_ASSUME(low != 0);
50 return 63 - countl_zero(low);
51 }
52
53 // Long division/modulo for uint128 implemented using the shift-subtract
54 // division algorithm adapted from:
55 // https://stackoverflow.com/questions/5386377/division-without-using
DivModImpl(uint128 dividend,uint128 divisor,uint128 * quotient_ret,uint128 * remainder_ret)56 inline void DivModImpl(uint128 dividend, uint128 divisor, uint128* quotient_ret,
57 uint128* remainder_ret) {
58 assert(divisor != 0);
59
60 if (divisor > dividend) {
61 *quotient_ret = 0;
62 *remainder_ret = dividend;
63 return;
64 }
65
66 if (divisor == dividend) {
67 *quotient_ret = 1;
68 *remainder_ret = 0;
69 return;
70 }
71
72 uint128 denominator = divisor;
73 uint128 quotient = 0;
74
75 // Left aligns the MSB of the denominator and the dividend.
76 const int shift = Fls128(dividend) - Fls128(denominator);
77 denominator <<= shift;
78
79 // Uses shift-subtract algorithm to divide dividend by denominator. The
80 // remainder will be left in dividend.
81 for (int i = 0; i <= shift; ++i) {
82 quotient <<= 1;
83 if (dividend >= denominator) {
84 dividend -= denominator;
85 quotient |= 1;
86 }
87 denominator >>= 1;
88 }
89
90 *quotient_ret = quotient;
91 *remainder_ret = dividend;
92 }
93
94 template <typename T>
MakeUint128FromFloat(T v)95 uint128 MakeUint128FromFloat(T v) {
96 static_assert(std::is_floating_point<T>::value, "");
97
98 // Rounding behavior is towards zero, same as for built-in types.
99
100 // Undefined behavior if v is NaN or cannot fit into uint128.
101 assert(std::isfinite(v) && v > -1 &&
102 (std::numeric_limits<T>::max_exponent <= 128 ||
103 v < std::ldexp(static_cast<T>(1), 128)));
104
105 if (v >= std::ldexp(static_cast<T>(1), 64)) {
106 uint64_t hi = static_cast<uint64_t>(std::ldexp(v, -64));
107 uint64_t lo = static_cast<uint64_t>(v - std::ldexp(static_cast<T>(hi), 64));
108 return MakeUint128(hi, lo);
109 }
110
111 return MakeUint128(0, static_cast<uint64_t>(v));
112 }
113
114 #if defined(__clang__) && !defined(__SSE3__)
115 // Workaround for clang bug: https://bugs.llvm.org/show_bug.cgi?id=38289
116 // Casting from long double to uint64_t is miscompiled and drops bits.
117 // It is more work, so only use when we need the workaround.
MakeUint128FromFloat(long double v)118 uint128 MakeUint128FromFloat(long double v) {
119 // Go 50 bits at a time, that fits in a double
120 static_assert(std::numeric_limits<double>::digits >= 50, "");
121 static_assert(std::numeric_limits<long double>::digits <= 150, "");
122 // Undefined behavior if v is not finite or cannot fit into uint128.
123 assert(std::isfinite(v) && v > -1 && v < std::ldexp(1.0L, 128));
124
125 v = std::ldexp(v, -100);
126 uint64_t w0 = static_cast<uint64_t>(static_cast<double>(std::trunc(v)));
127 v = std::ldexp(v - static_cast<double>(w0), 50);
128 uint64_t w1 = static_cast<uint64_t>(static_cast<double>(std::trunc(v)));
129 v = std::ldexp(v - static_cast<double>(w1), 50);
130 uint64_t w2 = static_cast<uint64_t>(static_cast<double>(std::trunc(v)));
131 return (static_cast<uint128>(w0) << 100) | (static_cast<uint128>(w1) << 50) |
132 static_cast<uint128>(w2);
133 }
134 #endif // __clang__ && !__SSE3__
135 } // namespace
136
uint128(float v)137 uint128::uint128(float v) : uint128(MakeUint128FromFloat(v)) {}
uint128(double v)138 uint128::uint128(double v) : uint128(MakeUint128FromFloat(v)) {}
uint128(long double v)139 uint128::uint128(long double v) : uint128(MakeUint128FromFloat(v)) {}
140
141 #if !defined(ABSL_HAVE_INTRINSIC_INT128)
operator /(uint128 lhs,uint128 rhs)142 uint128 operator/(uint128 lhs, uint128 rhs) {
143 uint128 quotient = 0;
144 uint128 remainder = 0;
145 DivModImpl(lhs, rhs, "ient, &remainder);
146 return quotient;
147 }
148
operator %(uint128 lhs,uint128 rhs)149 uint128 operator%(uint128 lhs, uint128 rhs) {
150 uint128 quotient = 0;
151 uint128 remainder = 0;
152 DivModImpl(lhs, rhs, "ient, &remainder);
153 return remainder;
154 }
155 #endif // !defined(ABSL_HAVE_INTRINSIC_INT128)
156
157 namespace {
158
Uint128ToFormattedString(uint128 v,std::ios_base::fmtflags flags)159 std::string Uint128ToFormattedString(uint128 v, std::ios_base::fmtflags flags) {
160 // Select a divisor which is the largest power of the base < 2^64.
161 uint128 div;
162 int div_base_log;
163 switch (flags & std::ios::basefield) {
164 case std::ios::hex:
165 div = 0x1000000000000000; // 16^15
166 div_base_log = 15;
167 break;
168 case std::ios::oct:
169 div = 01000000000000000000000; // 8^21
170 div_base_log = 21;
171 break;
172 default: // std::ios::dec
173 div = 10000000000000000000u; // 10^19
174 div_base_log = 19;
175 break;
176 }
177
178 // Now piece together the uint128 representation from three chunks of the
179 // original value, each less than "div" and therefore representable as a
180 // uint64_t.
181 std::ostringstream os;
182 std::ios_base::fmtflags copy_mask =
183 std::ios::basefield | std::ios::showbase | std::ios::uppercase;
184 os.setf(flags & copy_mask, copy_mask);
185 uint128 high = v;
186 uint128 low;
187 DivModImpl(high, div, &high, &low);
188 uint128 mid;
189 DivModImpl(high, div, &high, &mid);
190 if (Uint128Low64(high) != 0) {
191 os << Uint128Low64(high);
192 os << std::noshowbase << std::setfill('0') << std::setw(div_base_log);
193 os << Uint128Low64(mid);
194 os << std::setw(div_base_log);
195 } else if (Uint128Low64(mid) != 0) {
196 os << Uint128Low64(mid);
197 os << std::noshowbase << std::setfill('0') << std::setw(div_base_log);
198 }
199 os << Uint128Low64(low);
200 return os.str();
201 }
202
203 } // namespace
204
operator <<(std::ostream & os,uint128 v)205 std::ostream& operator<<(std::ostream& os, uint128 v) {
206 std::ios_base::fmtflags flags = os.flags();
207 std::string rep = Uint128ToFormattedString(v, flags);
208
209 // Add the requisite padding.
210 std::streamsize width = os.width(0);
211 if (static_cast<size_t>(width) > rep.size()) {
212 const size_t count = static_cast<size_t>(width) - rep.size();
213 std::ios::fmtflags adjustfield = flags & std::ios::adjustfield;
214 if (adjustfield == std::ios::left) {
215 rep.append(count, os.fill());
216 } else if (adjustfield == std::ios::internal &&
217 (flags & std::ios::showbase) &&
218 (flags & std::ios::basefield) == std::ios::hex && v != 0) {
219 rep.insert(2, count, os.fill());
220 } else {
221 rep.insert(0, count, os.fill());
222 }
223 }
224
225 return os << rep;
226 }
227
228 namespace {
229
UnsignedAbsoluteValue(int128 v)230 uint128 UnsignedAbsoluteValue(int128 v) {
231 // Cast to uint128 before possibly negating because -Int128Min() is undefined.
232 return Int128High64(v) < 0 ? -uint128(v) : uint128(v);
233 }
234
235 } // namespace
236
237 #if !defined(ABSL_HAVE_INTRINSIC_INT128)
238 namespace {
239
240 template <typename T>
MakeInt128FromFloat(T v)241 int128 MakeInt128FromFloat(T v) {
242 // Conversion when v is NaN or cannot fit into int128 would be undefined
243 // behavior if using an intrinsic 128-bit integer.
244 assert(std::isfinite(v) && (std::numeric_limits<T>::max_exponent <= 127 ||
245 (v >= -std::ldexp(static_cast<T>(1), 127) &&
246 v < std::ldexp(static_cast<T>(1), 127))));
247
248 // We must convert the absolute value and then negate as needed, because
249 // floating point types are typically sign-magnitude. Otherwise, the
250 // difference between the high and low 64 bits when interpreted as two's
251 // complement overwhelms the precision of the mantissa.
252 uint128 result = v < 0 ? -MakeUint128FromFloat(-v) : MakeUint128FromFloat(v);
253 return MakeInt128(int128_internal::BitCastToSigned(Uint128High64(result)),
254 Uint128Low64(result));
255 }
256
257 } // namespace
258
int128(float v)259 int128::int128(float v) : int128(MakeInt128FromFloat(v)) {}
int128(double v)260 int128::int128(double v) : int128(MakeInt128FromFloat(v)) {}
int128(long double v)261 int128::int128(long double v) : int128(MakeInt128FromFloat(v)) {}
262
operator /(int128 lhs,int128 rhs)263 int128 operator/(int128 lhs, int128 rhs) {
264 assert(lhs != Int128Min() || rhs != -1); // UB on two's complement.
265
266 uint128 quotient = 0;
267 uint128 remainder = 0;
268 DivModImpl(UnsignedAbsoluteValue(lhs), UnsignedAbsoluteValue(rhs),
269 "ient, &remainder);
270 if ((Int128High64(lhs) < 0) != (Int128High64(rhs) < 0)) quotient = -quotient;
271 return MakeInt128(int128_internal::BitCastToSigned(Uint128High64(quotient)),
272 Uint128Low64(quotient));
273 }
274
operator %(int128 lhs,int128 rhs)275 int128 operator%(int128 lhs, int128 rhs) {
276 assert(lhs != Int128Min() || rhs != -1); // UB on two's complement.
277
278 uint128 quotient = 0;
279 uint128 remainder = 0;
280 DivModImpl(UnsignedAbsoluteValue(lhs), UnsignedAbsoluteValue(rhs),
281 "ient, &remainder);
282 if (Int128High64(lhs) < 0) remainder = -remainder;
283 return MakeInt128(int128_internal::BitCastToSigned(Uint128High64(remainder)),
284 Uint128Low64(remainder));
285 }
286 #endif // ABSL_HAVE_INTRINSIC_INT128
287
operator <<(std::ostream & os,int128 v)288 std::ostream& operator<<(std::ostream& os, int128 v) {
289 std::ios_base::fmtflags flags = os.flags();
290 std::string rep;
291
292 // Add the sign if needed.
293 bool print_as_decimal =
294 (flags & std::ios::basefield) == std::ios::dec ||
295 (flags & std::ios::basefield) == std::ios_base::fmtflags();
296 if (print_as_decimal) {
297 if (Int128High64(v) < 0) {
298 rep = "-";
299 } else if (flags & std::ios::showpos) {
300 rep = "+";
301 }
302 }
303
304 rep.append(Uint128ToFormattedString(
305 print_as_decimal ? UnsignedAbsoluteValue(v) : uint128(v), os.flags()));
306
307 // Add the requisite padding.
308 std::streamsize width = os.width(0);
309 if (static_cast<size_t>(width) > rep.size()) {
310 const size_t count = static_cast<size_t>(width) - rep.size();
311 switch (flags & std::ios::adjustfield) {
312 case std::ios::left:
313 rep.append(count, os.fill());
314 break;
315 case std::ios::internal:
316 if (print_as_decimal && (rep[0] == '+' || rep[0] == '-')) {
317 rep.insert(1, count, os.fill());
318 } else if ((flags & std::ios::basefield) == std::ios::hex &&
319 (flags & std::ios::showbase) && v != 0) {
320 rep.insert(2, count, os.fill());
321 } else {
322 rep.insert(0, count, os.fill());
323 }
324 break;
325 default: // std::ios::right
326 rep.insert(0, count, os.fill());
327 break;
328 }
329 }
330
331 return os << rep;
332 }
333
334 ABSL_NAMESPACE_END
335 } // namespace absl
336
337 #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
338 namespace std {
339 constexpr bool numeric_limits<absl::uint128>::is_specialized;
340 constexpr bool numeric_limits<absl::uint128>::is_signed;
341 constexpr bool numeric_limits<absl::uint128>::is_integer;
342 constexpr bool numeric_limits<absl::uint128>::is_exact;
343 constexpr bool numeric_limits<absl::uint128>::has_infinity;
344 constexpr bool numeric_limits<absl::uint128>::has_quiet_NaN;
345 constexpr bool numeric_limits<absl::uint128>::has_signaling_NaN;
346 constexpr float_denorm_style numeric_limits<absl::uint128>::has_denorm;
347 constexpr bool numeric_limits<absl::uint128>::has_denorm_loss;
348 constexpr float_round_style numeric_limits<absl::uint128>::round_style;
349 constexpr bool numeric_limits<absl::uint128>::is_iec559;
350 constexpr bool numeric_limits<absl::uint128>::is_bounded;
351 constexpr bool numeric_limits<absl::uint128>::is_modulo;
352 constexpr int numeric_limits<absl::uint128>::digits;
353 constexpr int numeric_limits<absl::uint128>::digits10;
354 constexpr int numeric_limits<absl::uint128>::max_digits10;
355 constexpr int numeric_limits<absl::uint128>::radix;
356 constexpr int numeric_limits<absl::uint128>::min_exponent;
357 constexpr int numeric_limits<absl::uint128>::min_exponent10;
358 constexpr int numeric_limits<absl::uint128>::max_exponent;
359 constexpr int numeric_limits<absl::uint128>::max_exponent10;
360 constexpr bool numeric_limits<absl::uint128>::traps;
361 constexpr bool numeric_limits<absl::uint128>::tinyness_before;
362
363 constexpr bool numeric_limits<absl::int128>::is_specialized;
364 constexpr bool numeric_limits<absl::int128>::is_signed;
365 constexpr bool numeric_limits<absl::int128>::is_integer;
366 constexpr bool numeric_limits<absl::int128>::is_exact;
367 constexpr bool numeric_limits<absl::int128>::has_infinity;
368 constexpr bool numeric_limits<absl::int128>::has_quiet_NaN;
369 constexpr bool numeric_limits<absl::int128>::has_signaling_NaN;
370 constexpr float_denorm_style numeric_limits<absl::int128>::has_denorm;
371 constexpr bool numeric_limits<absl::int128>::has_denorm_loss;
372 constexpr float_round_style numeric_limits<absl::int128>::round_style;
373 constexpr bool numeric_limits<absl::int128>::is_iec559;
374 constexpr bool numeric_limits<absl::int128>::is_bounded;
375 constexpr bool numeric_limits<absl::int128>::is_modulo;
376 constexpr int numeric_limits<absl::int128>::digits;
377 constexpr int numeric_limits<absl::int128>::digits10;
378 constexpr int numeric_limits<absl::int128>::max_digits10;
379 constexpr int numeric_limits<absl::int128>::radix;
380 constexpr int numeric_limits<absl::int128>::min_exponent;
381 constexpr int numeric_limits<absl::int128>::min_exponent10;
382 constexpr int numeric_limits<absl::int128>::max_exponent;
383 constexpr int numeric_limits<absl::int128>::max_exponent10;
384 constexpr bool numeric_limits<absl::int128>::traps;
385 constexpr bool numeric_limits<absl::int128>::tinyness_before;
386 } // namespace std
387 #endif
388