Fix null pointer dereference in process_debug_info()
[binutils-gdb.git] / gdb / target-float.c
blob9b1b6b781d98241f22c11d57dcd83407f593c5e7
1 /* Floating point routines for GDB, the GNU debugger.
3 Copyright (C) 2017-2024 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #include "gdbtypes.h"
21 #include "floatformat.h"
22 #include "target-float.h"
23 #include "gdbarch.h"
25 /* Target floating-point operations.
27 We provide multiple implementations of those operations, which differ
28 by the host-side intermediate format they perform computations in.
30 Those multiple implementations all derive from the following abstract
31 base class, which specifies the set of operations to be implemented. */
33 class target_float_ops
35 public:
36 virtual std::string to_string (const gdb_byte *addr, const struct type *type,
37 const char *format) const = 0;
38 virtual bool from_string (gdb_byte *addr, const struct type *type,
39 const std::string &string) const = 0;
41 virtual LONGEST to_longest (const gdb_byte *addr,
42 const struct type *type) const = 0;
43 virtual void from_longest (gdb_byte *addr, const struct type *type,
44 LONGEST val) const = 0;
45 virtual void from_ulongest (gdb_byte *addr, const struct type *type,
46 ULONGEST val) const = 0;
47 virtual double to_host_double (const gdb_byte *addr,
48 const struct type *type) const = 0;
49 virtual void from_host_double (gdb_byte *addr, const struct type *type,
50 double val) const = 0;
51 virtual void convert (const gdb_byte *from, const struct type *from_type,
52 gdb_byte *to, const struct type *to_type) const = 0;
54 virtual void binop (enum exp_opcode opcode,
55 const gdb_byte *x, const struct type *type_x,
56 const gdb_byte *y, const struct type *type_y,
57 gdb_byte *res, const struct type *type_res) const = 0;
58 virtual int compare (const gdb_byte *x, const struct type *type_x,
59 const gdb_byte *y, const struct type *type_y) const = 0;
63 /* Helper routines operating on binary floating-point data. */
65 #include <cmath>
66 #include <limits>
68 /* Different kinds of floatformat numbers recognized by
69 floatformat_classify. To avoid portability issues, we use local
70 values instead of the C99 macros (FP_NAN et cetera). */
71 enum float_kind {
72 float_nan,
73 float_infinite,
74 float_zero,
75 float_normal,
76 float_subnormal
79 /* The odds that CHAR_BIT will be anything but 8 are low enough that I'm not
80 going to bother with trying to muck around with whether it is defined in
81 a system header, what we do if not, etc. */
82 #define FLOATFORMAT_CHAR_BIT 8
84 /* The number of bytes that the largest floating-point type that we
85 can convert to doublest will need. */
86 #define FLOATFORMAT_LARGEST_BYTES 16
88 /* Return the floatformat's total size in host bytes. */
89 static size_t
90 floatformat_totalsize_bytes (const struct floatformat *fmt)
92 return ((fmt->totalsize + FLOATFORMAT_CHAR_BIT - 1)
93 / FLOATFORMAT_CHAR_BIT);
96 /* Return the precision of the floating point format FMT. */
97 static int
98 floatformat_precision (const struct floatformat *fmt)
100 /* Assume the precision of and IBM long double is twice the precision
101 of the underlying double. This matches what GCC does. */
102 if (fmt->split_half)
103 return 2 * floatformat_precision (fmt->split_half);
105 /* Otherwise, the precision is the size of mantissa in bits,
106 including the implicit bit if present. */
107 int prec = fmt->man_len;
108 if (fmt->intbit == floatformat_intbit_no)
109 prec++;
111 return prec;
114 /* Normalize the byte order of FROM into TO. If no normalization is
115 needed then FMT->byteorder is returned and TO is not changed;
116 otherwise the format of the normalized form in TO is returned. */
117 static enum floatformat_byteorders
118 floatformat_normalize_byteorder (const struct floatformat *fmt,
119 const void *from, void *to)
121 const unsigned char *swapin;
122 unsigned char *swapout;
123 int words;
125 if (fmt->byteorder == floatformat_little
126 || fmt->byteorder == floatformat_big)
127 return fmt->byteorder;
129 words = fmt->totalsize / FLOATFORMAT_CHAR_BIT;
130 words >>= 2;
132 swapout = (unsigned char *)to;
133 swapin = (const unsigned char *)from;
135 if (fmt->byteorder == floatformat_vax)
137 while (words-- > 0)
139 *swapout++ = swapin[1];
140 *swapout++ = swapin[0];
141 *swapout++ = swapin[3];
142 *swapout++ = swapin[2];
143 swapin += 4;
145 /* This may look weird, since VAX is little-endian, but it is
146 easier to translate to big-endian than to little-endian. */
147 return floatformat_big;
149 else
151 gdb_assert (fmt->byteorder == floatformat_littlebyte_bigword);
153 while (words-- > 0)
155 *swapout++ = swapin[3];
156 *swapout++ = swapin[2];
157 *swapout++ = swapin[1];
158 *swapout++ = swapin[0];
159 swapin += 4;
161 return floatformat_big;
165 /* Extract a field which starts at START and is LEN bytes long. DATA and
166 TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
167 static unsigned long
168 get_field (const bfd_byte *data, enum floatformat_byteorders order,
169 unsigned int total_len, unsigned int start, unsigned int len)
171 unsigned long result;
172 unsigned int cur_byte;
173 int cur_bitshift;
175 /* Caller must byte-swap words before calling this routine. */
176 gdb_assert (order == floatformat_little || order == floatformat_big);
178 /* Start at the least significant part of the field. */
179 if (order == floatformat_little)
181 /* We start counting from the other end (i.e, from the high bytes
182 rather than the low bytes). As such, we need to be concerned
183 with what happens if bit 0 doesn't start on a byte boundary.
184 I.e, we need to properly handle the case where total_len is
185 not evenly divisible by 8. So we compute ``excess'' which
186 represents the number of bits from the end of our starting
187 byte needed to get to bit 0. */
188 int excess = FLOATFORMAT_CHAR_BIT - (total_len % FLOATFORMAT_CHAR_BIT);
190 cur_byte = (total_len / FLOATFORMAT_CHAR_BIT)
191 - ((start + len + excess) / FLOATFORMAT_CHAR_BIT);
192 cur_bitshift = ((start + len + excess) % FLOATFORMAT_CHAR_BIT)
193 - FLOATFORMAT_CHAR_BIT;
195 else
197 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
198 cur_bitshift =
199 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
201 if (cur_bitshift > -FLOATFORMAT_CHAR_BIT)
202 result = *(data + cur_byte) >> (-cur_bitshift);
203 else
204 result = 0;
205 cur_bitshift += FLOATFORMAT_CHAR_BIT;
206 if (order == floatformat_little)
207 ++cur_byte;
208 else
209 --cur_byte;
211 /* Move towards the most significant part of the field. */
212 while (cur_bitshift < len)
214 result |= (unsigned long)*(data + cur_byte) << cur_bitshift;
215 cur_bitshift += FLOATFORMAT_CHAR_BIT;
216 switch (order)
218 case floatformat_little:
219 ++cur_byte;
220 break;
221 case floatformat_big:
222 --cur_byte;
223 break;
226 if (len < sizeof(result) * FLOATFORMAT_CHAR_BIT)
227 /* Mask out bits which are not part of the field. */
228 result &= ((1UL << len) - 1);
229 return result;
232 /* Set a field which starts at START and is LEN bytes long. DATA and
233 TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER. */
234 static void
235 put_field (unsigned char *data, enum floatformat_byteorders order,
236 unsigned int total_len, unsigned int start, unsigned int len,
237 unsigned long stuff_to_put)
239 unsigned int cur_byte;
240 int cur_bitshift;
242 /* Caller must byte-swap words before calling this routine. */
243 gdb_assert (order == floatformat_little || order == floatformat_big);
245 /* Start at the least significant part of the field. */
246 if (order == floatformat_little)
248 int excess = FLOATFORMAT_CHAR_BIT - (total_len % FLOATFORMAT_CHAR_BIT);
250 cur_byte = (total_len / FLOATFORMAT_CHAR_BIT)
251 - ((start + len + excess) / FLOATFORMAT_CHAR_BIT);
252 cur_bitshift = ((start + len + excess) % FLOATFORMAT_CHAR_BIT)
253 - FLOATFORMAT_CHAR_BIT;
255 else
257 cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
258 cur_bitshift =
259 ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
261 if (cur_bitshift > -FLOATFORMAT_CHAR_BIT)
263 *(data + cur_byte) &=
264 ~(((1 << ((start + len) % FLOATFORMAT_CHAR_BIT)) - 1)
265 << (-cur_bitshift));
266 *(data + cur_byte) |=
267 (stuff_to_put & ((1 << FLOATFORMAT_CHAR_BIT) - 1)) << (-cur_bitshift);
269 cur_bitshift += FLOATFORMAT_CHAR_BIT;
270 if (order == floatformat_little)
271 ++cur_byte;
272 else
273 --cur_byte;
275 /* Move towards the most significant part of the field. */
276 while (cur_bitshift < len)
278 if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
280 /* This is the last byte. */
281 *(data + cur_byte) &=
282 ~((1 << (len - cur_bitshift)) - 1);
283 *(data + cur_byte) |= (stuff_to_put >> cur_bitshift);
285 else
286 *(data + cur_byte) = ((stuff_to_put >> cur_bitshift)
287 & ((1 << FLOATFORMAT_CHAR_BIT) - 1));
288 cur_bitshift += FLOATFORMAT_CHAR_BIT;
289 if (order == floatformat_little)
290 ++cur_byte;
291 else
292 --cur_byte;
296 /* Check if VAL (which is assumed to be a floating point number whose
297 format is described by FMT) is negative. */
298 static int
299 floatformat_is_negative (const struct floatformat *fmt,
300 const bfd_byte *uval)
302 enum floatformat_byteorders order;
303 unsigned char newfrom[FLOATFORMAT_LARGEST_BYTES];
305 gdb_assert (fmt != NULL);
306 gdb_assert (fmt->totalsize
307 <= FLOATFORMAT_LARGEST_BYTES * FLOATFORMAT_CHAR_BIT);
309 /* An IBM long double (a two element array of double) always takes the
310 sign of the first double. */
311 if (fmt->split_half)
312 fmt = fmt->split_half;
314 order = floatformat_normalize_byteorder (fmt, uval, newfrom);
316 if (order != fmt->byteorder)
317 uval = newfrom;
319 return get_field (uval, order, fmt->totalsize, fmt->sign_start, 1);
322 /* Check if VAL is "not a number" (NaN) for FMT. */
323 static enum float_kind
324 floatformat_classify (const struct floatformat *fmt,
325 const bfd_byte *uval)
327 long exponent;
328 unsigned long mant;
329 unsigned int mant_bits, mant_off;
330 int mant_bits_left;
331 enum floatformat_byteorders order;
332 unsigned char newfrom[FLOATFORMAT_LARGEST_BYTES];
333 int mant_zero;
335 gdb_assert (fmt != NULL);
336 gdb_assert (fmt->totalsize
337 <= FLOATFORMAT_LARGEST_BYTES * FLOATFORMAT_CHAR_BIT);
339 /* An IBM long double (a two element array of double) can be classified
340 by looking at the first double. inf and nan are specified as
341 ignoring the second double. zero and subnormal will always have
342 the second double 0.0 if the long double is correctly rounded. */
343 if (fmt->split_half)
344 fmt = fmt->split_half;
346 order = floatformat_normalize_byteorder (fmt, uval, newfrom);
348 if (order != fmt->byteorder)
349 uval = newfrom;
351 exponent = get_field (uval, order, fmt->totalsize, fmt->exp_start,
352 fmt->exp_len);
354 mant_bits_left = fmt->man_len;
355 mant_off = fmt->man_start;
357 mant_zero = 1;
358 while (mant_bits_left > 0)
360 mant_bits = std::min (mant_bits_left, 32);
362 mant = get_field (uval, order, fmt->totalsize, mant_off, mant_bits);
364 /* If there is an explicit integer bit, mask it off. */
365 if (mant_off == fmt->man_start
366 && fmt->intbit == floatformat_intbit_yes)
367 mant &= ~(1 << (mant_bits - 1));
369 if (mant)
371 mant_zero = 0;
372 break;
375 mant_off += mant_bits;
376 mant_bits_left -= mant_bits;
379 /* If exp_nan is not set, assume that inf, NaN, and subnormals are not
380 supported. */
381 if (! fmt->exp_nan)
383 if (mant_zero)
384 return float_zero;
385 else
386 return float_normal;
389 if (exponent == 0)
391 if (mant_zero)
392 return float_zero;
393 else
394 return float_subnormal;
397 if (exponent == fmt->exp_nan)
399 if (mant_zero)
400 return float_infinite;
401 else
402 return float_nan;
405 return float_normal;
408 /* Convert the mantissa of VAL (which is assumed to be a floating
409 point number whose format is described by FMT) into a hexadecimal
410 and store it in a static string. Return a pointer to that string. */
411 static const char *
412 floatformat_mantissa (const struct floatformat *fmt,
413 const bfd_byte *val)
415 unsigned char *uval = (unsigned char *) val;
416 unsigned long mant;
417 unsigned int mant_bits, mant_off;
418 int mant_bits_left;
419 static char res[50];
420 char buf[9];
421 int len;
422 enum floatformat_byteorders order;
423 unsigned char newfrom[FLOATFORMAT_LARGEST_BYTES];
425 gdb_assert (fmt != NULL);
426 gdb_assert (fmt->totalsize
427 <= FLOATFORMAT_LARGEST_BYTES * FLOATFORMAT_CHAR_BIT);
429 /* For IBM long double (a two element array of double), return the
430 mantissa of the first double. The problem with returning the
431 actual mantissa from both doubles is that there can be an
432 arbitrary number of implied 0's or 1's between the mantissas
433 of the first and second double. In any case, this function
434 is only used for dumping out nans, and a nan is specified to
435 ignore the value in the second double. */
436 if (fmt->split_half)
437 fmt = fmt->split_half;
439 order = floatformat_normalize_byteorder (fmt, uval, newfrom);
441 if (order != fmt->byteorder)
442 uval = newfrom;
444 if (! fmt->exp_nan)
445 return 0;
447 /* Make sure we have enough room to store the mantissa. */
448 gdb_assert (sizeof res > ((fmt->man_len + 7) / 8) * 2);
450 mant_off = fmt->man_start;
451 mant_bits_left = fmt->man_len;
452 mant_bits = (mant_bits_left % 32) > 0 ? mant_bits_left % 32 : 32;
454 mant = get_field (uval, order, fmt->totalsize, mant_off, mant_bits);
456 len = xsnprintf (res, sizeof res, "%lx", mant);
458 mant_off += mant_bits;
459 mant_bits_left -= mant_bits;
461 while (mant_bits_left > 0)
463 mant = get_field (uval, order, fmt->totalsize, mant_off, 32);
465 xsnprintf (buf, sizeof buf, "%08lx", mant);
466 gdb_assert (len + strlen (buf) <= sizeof res);
467 strcat (res, buf);
469 mant_off += 32;
470 mant_bits_left -= 32;
473 return res;
476 /* Convert printf format string FORMAT to the otherwise equivalent string
477 which may be used to print a host floating-point number using the length
478 modifier LENGTH (which may be 0 if none is needed). If FORMAT is null,
479 return a format appropriate to print the full precision of a target
480 floating-point number of format FMT. */
481 static std::string
482 floatformat_printf_format (const struct floatformat *fmt,
483 const char *format, char length)
485 std::string host_format;
486 char conversion;
488 if (format == nullptr)
490 /* If no format was specified, print the number using a format string
491 where the precision is set to the DECIMAL_DIG value for the given
492 floating-point format. This value is computed as
494 ceil(1 + p * log10(b)),
496 where p is the precision of the floating-point format in bits, and
497 b is the base (which is always 2 for the formats we support). */
498 const double log10_2 = .30102999566398119521;
499 double d_decimal_dig = 1 + floatformat_precision (fmt) * log10_2;
500 int decimal_dig = d_decimal_dig;
501 if (decimal_dig < d_decimal_dig)
502 decimal_dig++;
504 host_format = string_printf ("%%.%d", decimal_dig);
505 conversion = 'g';
507 else
509 /* Use the specified format, stripping out the conversion character
510 and length modifier, if present. */
511 size_t len = strlen (format);
512 gdb_assert (len > 1);
513 conversion = format[--len];
514 gdb_assert (conversion == 'e' || conversion == 'f' || conversion == 'g'
515 || conversion == 'E' || conversion == 'G');
516 if (format[len - 1] == 'L')
517 len--;
519 host_format = std::string (format, len);
522 /* Add the length modifier and conversion character appropriate for
523 handling the appropriate host floating-point type. */
524 if (length)
525 host_format += length;
526 host_format += conversion;
528 return host_format;
531 /* Implementation of target_float_ops using the host floating-point type T
532 as intermediate type. */
534 template<typename T> class host_float_ops : public target_float_ops
536 public:
537 std::string to_string (const gdb_byte *addr, const struct type *type,
538 const char *format) const override;
539 bool from_string (gdb_byte *addr, const struct type *type,
540 const std::string &string) const override;
542 LONGEST to_longest (const gdb_byte *addr,
543 const struct type *type) const override;
544 void from_longest (gdb_byte *addr, const struct type *type,
545 LONGEST val) const override;
546 void from_ulongest (gdb_byte *addr, const struct type *type,
547 ULONGEST val) const override;
548 double to_host_double (const gdb_byte *addr,
549 const struct type *type) const override;
550 void from_host_double (gdb_byte *addr, const struct type *type,
551 double val) const override;
552 void convert (const gdb_byte *from, const struct type *from_type,
553 gdb_byte *to, const struct type *to_type) const override;
555 void binop (enum exp_opcode opcode,
556 const gdb_byte *x, const struct type *type_x,
557 const gdb_byte *y, const struct type *type_y,
558 gdb_byte *res, const struct type *type_res) const override;
559 int compare (const gdb_byte *x, const struct type *type_x,
560 const gdb_byte *y, const struct type *type_y) const override;
562 private:
563 void from_target (const struct floatformat *fmt,
564 const gdb_byte *from, T *to) const;
565 void from_target (const struct type *type,
566 const gdb_byte *from, T *to) const;
568 void to_target (const struct type *type,
569 const T *from, gdb_byte *to) const;
570 void to_target (const struct floatformat *fmt,
571 const T *from, gdb_byte *to) const;
575 /* Convert TO/FROM target to the host floating-point format T.
577 If the host and target formats agree, we just copy the raw data
578 into the appropriate type of variable and return, letting the host
579 increase precision as necessary. Otherwise, we call the conversion
580 routine and let it do the dirty work. Note that even if the target
581 and host floating-point formats match, the length of the types
582 might still be different, so the conversion routines must make sure
583 to not overrun any buffers. For example, on x86, long double is
584 the 80-bit extended precision type on both 32-bit and 64-bit ABIs,
585 but by default it is stored as 12 bytes on 32-bit, and 16 bytes on
586 64-bit, for alignment reasons. See comment in store_typed_floating
587 for a discussion about zeroing out remaining bytes in the target
588 buffer. */
590 static const struct floatformat *host_float_format = GDB_HOST_FLOAT_FORMAT;
591 static const struct floatformat *host_double_format = GDB_HOST_DOUBLE_FORMAT;
592 static const struct floatformat *host_long_double_format
593 = GDB_HOST_LONG_DOUBLE_FORMAT;
595 /* Convert target floating-point value at FROM in format FMT to host
596 floating-point format of type T. */
597 template<typename T> void
598 host_float_ops<T>::from_target (const struct floatformat *fmt,
599 const gdb_byte *from, T *to) const
601 gdb_assert (fmt != NULL);
603 if (fmt == host_float_format)
605 float val = 0;
607 memcpy (&val, from, floatformat_totalsize_bytes (fmt));
608 *to = val;
609 return;
611 else if (fmt == host_double_format)
613 double val = 0;
615 memcpy (&val, from, floatformat_totalsize_bytes (fmt));
616 *to = val;
617 return;
619 else if (fmt == host_long_double_format)
621 long double val = 0;
623 memcpy (&val, from, floatformat_totalsize_bytes (fmt));
624 *to = val;
625 return;
628 unsigned char *ufrom = (unsigned char *) from;
629 long exponent;
630 unsigned long mant;
631 unsigned int mant_bits, mant_off;
632 int mant_bits_left;
633 int special_exponent; /* It's a NaN, denorm or zero. */
634 enum floatformat_byteorders order;
635 unsigned char newfrom[FLOATFORMAT_LARGEST_BYTES];
636 enum float_kind kind;
638 gdb_assert (fmt->totalsize
639 <= FLOATFORMAT_LARGEST_BYTES * FLOATFORMAT_CHAR_BIT);
641 /* For non-numbers, reuse libiberty's logic to find the correct
642 format. We do not lose any precision in this case by passing
643 through a double. */
644 kind = floatformat_classify (fmt, (const bfd_byte *) from);
645 if (kind == float_infinite || kind == float_nan)
647 double dto;
649 floatformat_to_double /* ARI: floatformat_to_double */
650 (fmt->split_half ? fmt->split_half : fmt, from, &dto);
651 *to = (T) dto;
652 return;
655 order = floatformat_normalize_byteorder (fmt, ufrom, newfrom);
657 if (order != fmt->byteorder)
658 ufrom = newfrom;
660 if (fmt->split_half)
662 T dtop, dbot;
664 from_target (fmt->split_half, ufrom, &dtop);
665 /* Preserve the sign of 0, which is the sign of the top
666 half. */
667 if (dtop == 0.0)
669 *to = dtop;
670 return;
672 from_target (fmt->split_half,
673 ufrom + fmt->totalsize / FLOATFORMAT_CHAR_BIT / 2, &dbot);
674 *to = dtop + dbot;
675 return;
678 exponent = get_field (ufrom, order, fmt->totalsize, fmt->exp_start,
679 fmt->exp_len);
680 /* Note that if exponent indicates a NaN, we can't really do anything useful
681 (not knowing if the host has NaN's, or how to build one). So it will
682 end up as an infinity or something close; that is OK. */
684 mant_bits_left = fmt->man_len;
685 mant_off = fmt->man_start;
686 T dto = 0.0;
688 special_exponent = exponent == 0 || exponent == fmt->exp_nan;
690 /* Don't bias NaNs. Use minimum exponent for denorms. For
691 simplicity, we don't check for zero as the exponent doesn't matter.
692 Note the cast to int; exp_bias is unsigned, so it's important to
693 make sure the operation is done in signed arithmetic. */
694 if (!special_exponent)
695 exponent -= fmt->exp_bias;
696 else if (exponent == 0)
697 exponent = 1 - fmt->exp_bias;
699 /* Build the result algebraically. Might go infinite, underflow, etc;
700 who cares. */
702 /* If this format uses a hidden bit, explicitly add it in now. Otherwise,
703 increment the exponent by one to account for the integer bit. */
705 if (!special_exponent)
707 if (fmt->intbit == floatformat_intbit_no)
708 dto = ldexp (1.0, exponent);
709 else
710 exponent++;
713 while (mant_bits_left > 0)
715 mant_bits = std::min (mant_bits_left, 32);
717 mant = get_field (ufrom, order, fmt->totalsize, mant_off, mant_bits);
719 dto += ldexp ((T) mant, exponent - mant_bits);
720 exponent -= mant_bits;
721 mant_off += mant_bits;
722 mant_bits_left -= mant_bits;
725 /* Negate it if negative. */
726 if (get_field (ufrom, order, fmt->totalsize, fmt->sign_start, 1))
727 dto = -dto;
728 *to = dto;
731 template<typename T> void
732 host_float_ops<T>::from_target (const struct type *type,
733 const gdb_byte *from, T *to) const
735 from_target (floatformat_from_type (type), from, to);
738 /* Convert host floating-point value of type T to target floating-point
739 value in format FMT and store at TO. */
740 template<typename T> void
741 host_float_ops<T>::to_target (const struct floatformat *fmt,
742 const T *from, gdb_byte *to) const
744 gdb_assert (fmt != NULL);
746 if (fmt == host_float_format)
748 float val = *from;
750 memcpy (to, &val, floatformat_totalsize_bytes (fmt));
751 return;
753 else if (fmt == host_double_format)
755 double val = *from;
757 memcpy (to, &val, floatformat_totalsize_bytes (fmt));
758 return;
760 else if (fmt == host_long_double_format)
762 long double val = *from;
764 memcpy (to, &val, floatformat_totalsize_bytes (fmt));
765 return;
768 T dfrom;
769 int exponent;
770 T mant;
771 unsigned int mant_bits, mant_off;
772 int mant_bits_left;
773 unsigned char *uto = (unsigned char *) to;
774 enum floatformat_byteorders order = fmt->byteorder;
775 unsigned char newto[FLOATFORMAT_LARGEST_BYTES];
777 if (order != floatformat_little)
778 order = floatformat_big;
780 if (order != fmt->byteorder)
781 uto = newto;
783 memcpy (&dfrom, from, sizeof (dfrom));
784 memset (uto, 0, floatformat_totalsize_bytes (fmt));
786 if (fmt->split_half)
788 /* Use static volatile to ensure that any excess precision is
789 removed via storing in memory, and so the top half really is
790 the result of converting to double. */
791 static volatile double dtop, dbot;
792 T dtopnv, dbotnv;
794 dtop = (double) dfrom;
795 /* If the rounded top half is Inf, the bottom must be 0 not NaN
796 or Inf. */
797 if (dtop + dtop == dtop && dtop != 0.0)
798 dbot = 0.0;
799 else
800 dbot = (double) (dfrom - (T) dtop);
801 dtopnv = dtop;
802 dbotnv = dbot;
803 to_target (fmt->split_half, &dtopnv, uto);
804 to_target (fmt->split_half, &dbotnv,
805 uto + fmt->totalsize / FLOATFORMAT_CHAR_BIT / 2);
806 return;
809 if (dfrom == 0)
810 goto finalize_byteorder; /* Result is zero */
811 if (dfrom != dfrom) /* Result is NaN */
813 /* From is NaN */
814 put_field (uto, order, fmt->totalsize, fmt->exp_start,
815 fmt->exp_len, fmt->exp_nan);
816 /* Be sure it's not infinity, but NaN value is irrel. */
817 put_field (uto, order, fmt->totalsize, fmt->man_start,
818 fmt->man_len, 1);
819 goto finalize_byteorder;
822 /* If negative, set the sign bit. */
823 if (dfrom < 0)
825 put_field (uto, order, fmt->totalsize, fmt->sign_start, 1, 1);
826 dfrom = -dfrom;
829 if (dfrom + dfrom == dfrom && dfrom != 0.0) /* Result is Infinity. */
831 /* Infinity exponent is same as NaN's. */
832 put_field (uto, order, fmt->totalsize, fmt->exp_start,
833 fmt->exp_len, fmt->exp_nan);
834 /* Infinity mantissa is all zeroes. */
835 put_field (uto, order, fmt->totalsize, fmt->man_start,
836 fmt->man_len, 0);
837 goto finalize_byteorder;
840 mant = frexp (dfrom, &exponent);
842 if (exponent + fmt->exp_bias <= 0)
844 /* The value is too small to be expressed in the destination
845 type (not enough bits in the exponent. Treat as 0. */
846 put_field (uto, order, fmt->totalsize, fmt->exp_start,
847 fmt->exp_len, 0);
848 put_field (uto, order, fmt->totalsize, fmt->man_start,
849 fmt->man_len, 0);
850 goto finalize_byteorder;
853 if (exponent + fmt->exp_bias >= (1 << fmt->exp_len))
855 /* The value is too large to fit into the destination.
856 Treat as infinity. */
857 put_field (uto, order, fmt->totalsize, fmt->exp_start,
858 fmt->exp_len, fmt->exp_nan);
859 put_field (uto, order, fmt->totalsize, fmt->man_start,
860 fmt->man_len, 0);
861 goto finalize_byteorder;
864 put_field (uto, order, fmt->totalsize, fmt->exp_start, fmt->exp_len,
865 exponent + fmt->exp_bias - 1);
867 mant_bits_left = fmt->man_len;
868 mant_off = fmt->man_start;
869 while (mant_bits_left > 0)
871 unsigned long mant_long;
873 mant_bits = mant_bits_left < 32 ? mant_bits_left : 32;
875 mant *= 4294967296.0;
876 mant_long = ((unsigned long) mant) & 0xffffffffL;
877 mant -= mant_long;
879 /* If the integer bit is implicit, then we need to discard it.
880 If we are discarding a zero, we should be (but are not) creating
881 a denormalized number which means adjusting the exponent
882 (I think). */
883 if (mant_bits_left == fmt->man_len
884 && fmt->intbit == floatformat_intbit_no)
886 mant_long <<= 1;
887 mant_long &= 0xffffffffL;
888 /* If we are processing the top 32 mantissa bits of a doublest
889 so as to convert to a float value with implied integer bit,
890 we will only be putting 31 of those 32 bits into the
891 final value due to the discarding of the top bit. In the
892 case of a small float value where the number of mantissa
893 bits is less than 32, discarding the top bit does not alter
894 the number of bits we will be adding to the result. */
895 if (mant_bits == 32)
896 mant_bits -= 1;
899 if (mant_bits < 32)
901 /* The bits we want are in the most significant MANT_BITS bits of
902 mant_long. Move them to the least significant. */
903 mant_long >>= 32 - mant_bits;
906 put_field (uto, order, fmt->totalsize,
907 mant_off, mant_bits, mant_long);
908 mant_off += mant_bits;
909 mant_bits_left -= mant_bits;
912 finalize_byteorder:
913 /* Do we need to byte-swap the words in the result? */
914 if (order != fmt->byteorder)
915 floatformat_normalize_byteorder (fmt, newto, to);
918 template<typename T> void
919 host_float_ops<T>::to_target (const struct type *type,
920 const T *from, gdb_byte *to) const
922 /* Ensure possible padding bytes in the target buffer are zeroed out. */
923 memset (to, 0, type->length ());
925 to_target (floatformat_from_type (type), from, to);
928 /* Convert the byte-stream ADDR, interpreted as floating-point type TYPE,
929 to a string, optionally using the print format FORMAT. */
930 template<typename T> struct printf_length_modifier
932 static constexpr char value = 0;
934 template<> struct printf_length_modifier<long double>
936 static constexpr char value = 'L';
938 template<typename T> std::string
939 host_float_ops<T>::to_string (const gdb_byte *addr, const struct type *type,
940 const char *format) const
942 /* Determine the format string to use on the host side. */
943 constexpr char length = printf_length_modifier<T>::value;
944 const struct floatformat *fmt = floatformat_from_type (type);
945 std::string host_format = floatformat_printf_format (fmt, format, length);
947 T host_float;
948 from_target (type, addr, &host_float);
950 DIAGNOSTIC_PUSH
951 DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
952 return string_printf (host_format.c_str (), host_float);
953 DIAGNOSTIC_POP
956 /* Parse string IN into a target floating-number of type TYPE and
957 store it as byte-stream ADDR. Return whether parsing succeeded. */
958 template<typename T> struct scanf_length_modifier
960 static constexpr char value = 0;
962 template<> struct scanf_length_modifier<double>
964 static constexpr char value = 'l';
966 template<> struct scanf_length_modifier<long double>
968 static constexpr char value = 'L';
970 template<typename T> bool
971 host_float_ops<T>::from_string (gdb_byte *addr, const struct type *type,
972 const std::string &in) const
974 T host_float;
975 int n, num;
977 std::string scan_format = "%";
978 if (scanf_length_modifier<T>::value)
979 scan_format += scanf_length_modifier<T>::value;
980 scan_format += "g%n";
982 DIAGNOSTIC_PUSH
983 DIAGNOSTIC_IGNORE_FORMAT_NONLITERAL
984 num = sscanf (in.c_str (), scan_format.c_str(), &host_float, &n);
985 DIAGNOSTIC_POP
987 /* The sscanf man page suggests not making any assumptions on the effect
988 of %n on the result, so we don't.
989 That is why we simply test num == 0. */
990 if (num == 0)
991 return false;
993 /* We only accept the whole string. */
994 if (in[n])
995 return false;
997 to_target (type, &host_float, addr);
998 return true;
1001 /* Convert the byte-stream ADDR, interpreted as floating-point type TYPE,
1002 to an integer value (rounding towards zero). */
1003 template<typename T> LONGEST
1004 host_float_ops<T>::to_longest (const gdb_byte *addr,
1005 const struct type *type) const
1007 T host_float;
1008 from_target (type, addr, &host_float);
1009 T min_possible_range = static_cast<T>(std::numeric_limits<LONGEST>::min());
1010 T max_possible_range = -min_possible_range;
1011 /* host_float can be converted to an integer as long as it's in
1012 the range [min_possible_range, max_possible_range). If not, it is either
1013 too large, or too small, or is NaN; in this case return the maximum or
1014 minimum possible value. */
1015 if (host_float < max_possible_range && host_float >= min_possible_range)
1016 return static_cast<LONGEST> (host_float);
1017 if (host_float < min_possible_range)
1018 return std::numeric_limits<LONGEST>::min();
1019 /* This line will be executed if host_float is NaN. */
1020 return std::numeric_limits<LONGEST>::max();
1023 /* Convert signed integer VAL to a target floating-number of type TYPE
1024 and store it as byte-stream ADDR. */
1025 template<typename T> void
1026 host_float_ops<T>::from_longest (gdb_byte *addr, const struct type *type,
1027 LONGEST val) const
1029 T host_float = (T) val;
1030 to_target (type, &host_float, addr);
1033 /* Convert unsigned integer VAL to a target floating-number of type TYPE
1034 and store it as byte-stream ADDR. */
1035 template<typename T> void
1036 host_float_ops<T>::from_ulongest (gdb_byte *addr, const struct type *type,
1037 ULONGEST val) const
1039 T host_float = (T) val;
1040 to_target (type, &host_float, addr);
1043 /* Convert the byte-stream ADDR, interpreted as floating-point type TYPE,
1044 to a floating-point value in the host "double" format. */
1045 template<typename T> double
1046 host_float_ops<T>::to_host_double (const gdb_byte *addr,
1047 const struct type *type) const
1049 T host_float;
1050 from_target (type, addr, &host_float);
1051 return (double) host_float;
1054 /* Convert floating-point value VAL in the host "double" format to a target
1055 floating-number of type TYPE and store it as byte-stream ADDR. */
1056 template<typename T> void
1057 host_float_ops<T>::from_host_double (gdb_byte *addr, const struct type *type,
1058 double val) const
1060 T host_float = (T) val;
1061 to_target (type, &host_float, addr);
1064 /* Convert a floating-point number of type FROM_TYPE from the target
1065 byte-stream FROM to a floating-point number of type TO_TYPE, and
1066 store it to the target byte-stream TO. */
1067 template<typename T> void
1068 host_float_ops<T>::convert (const gdb_byte *from,
1069 const struct type *from_type,
1070 gdb_byte *to,
1071 const struct type *to_type) const
1073 T host_float;
1074 from_target (from_type, from, &host_float);
1075 to_target (to_type, &host_float, to);
1078 /* Perform the binary operation indicated by OPCODE, using as operands the
1079 target byte streams X and Y, interpreted as floating-point numbers of
1080 types TYPE_X and TYPE_Y, respectively. Convert the result to format
1081 TYPE_RES and store it into the byte-stream RES. */
1082 template<typename T> void
1083 host_float_ops<T>::binop (enum exp_opcode op,
1084 const gdb_byte *x, const struct type *type_x,
1085 const gdb_byte *y, const struct type *type_y,
1086 gdb_byte *res, const struct type *type_res) const
1088 T v1, v2, v = 0;
1090 from_target (type_x, x, &v1);
1091 from_target (type_y, y, &v2);
1093 switch (op)
1095 case BINOP_ADD:
1096 v = v1 + v2;
1097 break;
1099 case BINOP_SUB:
1100 v = v1 - v2;
1101 break;
1103 case BINOP_MUL:
1104 v = v1 * v2;
1105 break;
1107 case BINOP_DIV:
1108 v = v1 / v2;
1109 break;
1111 case BINOP_EXP:
1112 errno = 0;
1113 v = pow (v1, v2);
1114 if (errno)
1115 error (_("Cannot perform exponentiation: %s"),
1116 safe_strerror (errno));
1117 break;
1119 case BINOP_MIN:
1120 v = v1 < v2 ? v1 : v2;
1121 break;
1123 case BINOP_MAX:
1124 v = v1 > v2 ? v1 : v2;
1125 break;
1127 default:
1128 error (_("Integer-only operation on floating point number."));
1129 break;
1132 to_target (type_res, &v, res);
1135 /* Compare the two target byte streams X and Y, interpreted as floating-point
1136 numbers of types TYPE_X and TYPE_Y, respectively. Return zero if X and Y
1137 are equal, -1 if X is less than Y, and 1 otherwise. */
1138 template<typename T> int
1139 host_float_ops<T>::compare (const gdb_byte *x, const struct type *type_x,
1140 const gdb_byte *y, const struct type *type_y) const
1142 T v1, v2;
1144 from_target (type_x, x, &v1);
1145 from_target (type_y, y, &v2);
1147 if (v1 == v2)
1148 return 0;
1149 if (v1 < v2)
1150 return -1;
1151 return 1;
1155 /* Implementation of target_float_ops using the MPFR library
1156 mpfr_t as intermediate type. */
1158 #define MPFR_USE_INTMAX_T
1160 #include <mpfr.h>
1162 class mpfr_float_ops : public target_float_ops
1164 public:
1165 std::string to_string (const gdb_byte *addr, const struct type *type,
1166 const char *format) const override;
1167 bool from_string (gdb_byte *addr, const struct type *type,
1168 const std::string &string) const override;
1170 LONGEST to_longest (const gdb_byte *addr,
1171 const struct type *type) const override;
1172 void from_longest (gdb_byte *addr, const struct type *type,
1173 LONGEST val) const override;
1174 void from_ulongest (gdb_byte *addr, const struct type *type,
1175 ULONGEST val) const override;
1176 double to_host_double (const gdb_byte *addr,
1177 const struct type *type) const override;
1178 void from_host_double (gdb_byte *addr, const struct type *type,
1179 double val) const override;
1180 void convert (const gdb_byte *from, const struct type *from_type,
1181 gdb_byte *to, const struct type *to_type) const override;
1183 void binop (enum exp_opcode opcode,
1184 const gdb_byte *x, const struct type *type_x,
1185 const gdb_byte *y, const struct type *type_y,
1186 gdb_byte *res, const struct type *type_res) const override;
1187 int compare (const gdb_byte *x, const struct type *type_x,
1188 const gdb_byte *y, const struct type *type_y) const override;
1190 private:
1191 /* Local wrapper class to handle mpfr_t initialization and cleanup. */
1192 class gdb_mpfr
1194 public:
1195 mpfr_t val;
1197 gdb_mpfr (const struct type *type)
1199 const struct floatformat *fmt = floatformat_from_type (type);
1200 mpfr_init2 (val, floatformat_precision (fmt));
1203 gdb_mpfr (const gdb_mpfr &source)
1205 mpfr_init2 (val, mpfr_get_prec (source.val));
1208 ~gdb_mpfr ()
1210 mpfr_clear (val);
1214 void from_target (const struct floatformat *fmt,
1215 const gdb_byte *from, gdb_mpfr &to) const;
1216 void from_target (const struct type *type,
1217 const gdb_byte *from, gdb_mpfr &to) const;
1219 void to_target (const struct type *type,
1220 const gdb_mpfr &from, gdb_byte *to) const;
1221 void to_target (const struct floatformat *fmt,
1222 const gdb_mpfr &from, gdb_byte *to) const;
1226 /* Convert TO/FROM target floating-point format to mpfr_t. */
1228 void
1229 mpfr_float_ops::from_target (const struct floatformat *fmt,
1230 const gdb_byte *orig_from, gdb_mpfr &to) const
1232 const gdb_byte *from = orig_from;
1233 mpfr_exp_t exponent;
1234 unsigned long mant;
1235 unsigned int mant_bits, mant_off;
1236 int mant_bits_left;
1237 int special_exponent; /* It's a NaN, denorm or zero. */
1238 enum floatformat_byteorders order;
1239 unsigned char newfrom[FLOATFORMAT_LARGEST_BYTES];
1240 enum float_kind kind;
1242 gdb_assert (fmt->totalsize
1243 <= FLOATFORMAT_LARGEST_BYTES * FLOATFORMAT_CHAR_BIT);
1245 /* Handle non-numbers. */
1246 kind = floatformat_classify (fmt, from);
1247 if (kind == float_infinite)
1249 mpfr_set_inf (to.val, floatformat_is_negative (fmt, from) ? -1 : 1);
1250 return;
1252 if (kind == float_nan)
1254 mpfr_set_nan (to.val);
1255 return;
1258 order = floatformat_normalize_byteorder (fmt, from, newfrom);
1260 if (order != fmt->byteorder)
1261 from = newfrom;
1263 if (fmt->split_half)
1265 gdb_mpfr top (to), bot (to);
1267 from_target (fmt->split_half, from, top);
1268 /* Preserve the sign of 0, which is the sign of the top half. */
1269 if (mpfr_zero_p (top.val))
1271 mpfr_set (to.val, top.val, MPFR_RNDN);
1272 return;
1274 from_target (fmt->split_half,
1275 from + fmt->totalsize / FLOATFORMAT_CHAR_BIT / 2, bot);
1276 mpfr_add (to.val, top.val, bot.val, MPFR_RNDN);
1277 return;
1280 exponent = get_field (from, order, fmt->totalsize, fmt->exp_start,
1281 fmt->exp_len);
1282 /* Note that if exponent indicates a NaN, we can't really do anything useful
1283 (not knowing if the host has NaN's, or how to build one). So it will
1284 end up as an infinity or something close; that is OK. */
1286 mant_bits_left = fmt->man_len;
1287 mant_off = fmt->man_start;
1288 mpfr_set_zero (to.val, 0);
1290 special_exponent = exponent == 0 || exponent == fmt->exp_nan;
1292 /* Don't bias NaNs. Use minimum exponent for denorms. For
1293 simplicity, we don't check for zero as the exponent doesn't matter.
1294 Note the cast to int; exp_bias is unsigned, so it's important to
1295 make sure the operation is done in signed arithmetic. */
1296 if (!special_exponent)
1297 exponent -= fmt->exp_bias;
1298 else if (exponent == 0)
1299 exponent = 1 - fmt->exp_bias;
1301 /* Build the result algebraically. Might go infinite, underflow, etc;
1302 who cares. */
1304 /* If this format uses a hidden bit, explicitly add it in now. Otherwise,
1305 increment the exponent by one to account for the integer bit. */
1307 if (!special_exponent)
1309 if (fmt->intbit == floatformat_intbit_no)
1310 mpfr_set_ui_2exp (to.val, 1, exponent, MPFR_RNDN);
1311 else
1312 exponent++;
1315 gdb_mpfr tmp (to);
1317 while (mant_bits_left > 0)
1319 mant_bits = std::min (mant_bits_left, 32);
1321 mant = get_field (from, order, fmt->totalsize, mant_off, mant_bits);
1323 mpfr_set_ui (tmp.val, mant, MPFR_RNDN);
1324 mpfr_mul_2si (tmp.val, tmp.val, exponent - mant_bits, MPFR_RNDN);
1325 mpfr_add (to.val, to.val, tmp.val, MPFR_RNDN);
1326 exponent -= mant_bits;
1327 mant_off += mant_bits;
1328 mant_bits_left -= mant_bits;
1331 /* Negate it if negative. */
1332 if (get_field (from, order, fmt->totalsize, fmt->sign_start, 1))
1333 mpfr_neg (to.val, to.val, MPFR_RNDN);
1336 void
1337 mpfr_float_ops::from_target (const struct type *type,
1338 const gdb_byte *from, gdb_mpfr &to) const
1340 from_target (floatformat_from_type (type), from, to);
1343 void
1344 mpfr_float_ops::to_target (const struct floatformat *fmt,
1345 const gdb_mpfr &from, gdb_byte *orig_to) const
1347 unsigned char *to = orig_to;
1348 mpfr_exp_t exponent;
1349 unsigned int mant_bits, mant_off;
1350 int mant_bits_left;
1351 enum floatformat_byteorders order = fmt->byteorder;
1352 unsigned char newto[FLOATFORMAT_LARGEST_BYTES];
1354 if (order != floatformat_little)
1355 order = floatformat_big;
1357 if (order != fmt->byteorder)
1358 to = newto;
1360 memset (to, 0, floatformat_totalsize_bytes (fmt));
1362 if (fmt->split_half)
1364 gdb_mpfr top (from), bot (from);
1366 mpfr_set (top.val, from.val, MPFR_RNDN);
1367 /* If the rounded top half is Inf, the bottom must be 0 not NaN
1368 or Inf. */
1369 if (mpfr_inf_p (top.val))
1370 mpfr_set_zero (bot.val, 0);
1371 else
1372 mpfr_sub (bot.val, from.val, top.val, MPFR_RNDN);
1374 to_target (fmt->split_half, top, to);
1375 to_target (fmt->split_half, bot,
1376 to + fmt->totalsize / FLOATFORMAT_CHAR_BIT / 2);
1377 return;
1380 gdb_mpfr tmp (from);
1382 if (mpfr_zero_p (from.val))
1383 goto finalize_byteorder; /* Result is zero */
1385 mpfr_set (tmp.val, from.val, MPFR_RNDN);
1387 if (mpfr_nan_p (tmp.val)) /* Result is NaN */
1389 /* From is NaN */
1390 put_field (to, order, fmt->totalsize, fmt->exp_start,
1391 fmt->exp_len, fmt->exp_nan);
1392 /* Be sure it's not infinity, but NaN value is irrel. */
1393 put_field (to, order, fmt->totalsize, fmt->man_start,
1394 fmt->man_len, 1);
1395 goto finalize_byteorder;
1398 /* If negative, set the sign bit. */
1399 if (mpfr_sgn (tmp.val) < 0)
1401 put_field (to, order, fmt->totalsize, fmt->sign_start, 1, 1);
1402 mpfr_neg (tmp.val, tmp.val, MPFR_RNDN);
1405 if (mpfr_inf_p (tmp.val)) /* Result is Infinity. */
1407 /* Infinity exponent is same as NaN's. */
1408 put_field (to, order, fmt->totalsize, fmt->exp_start,
1409 fmt->exp_len, fmt->exp_nan);
1410 /* Infinity mantissa is all zeroes. */
1411 put_field (to, order, fmt->totalsize, fmt->man_start,
1412 fmt->man_len, 0);
1413 goto finalize_byteorder;
1416 mpfr_frexp (&exponent, tmp.val, tmp.val, MPFR_RNDN);
1418 if (exponent + fmt->exp_bias <= 0)
1420 /* The value is too small to be expressed in the destination
1421 type (not enough bits in the exponent. Treat as 0. */
1422 put_field (to, order, fmt->totalsize, fmt->exp_start,
1423 fmt->exp_len, 0);
1424 put_field (to, order, fmt->totalsize, fmt->man_start,
1425 fmt->man_len, 0);
1426 goto finalize_byteorder;
1429 if (exponent + fmt->exp_bias >= (1 << fmt->exp_len))
1431 /* The value is too large to fit into the destination.
1432 Treat as infinity. */
1433 put_field (to, order, fmt->totalsize, fmt->exp_start,
1434 fmt->exp_len, fmt->exp_nan);
1435 put_field (to, order, fmt->totalsize, fmt->man_start,
1436 fmt->man_len, 0);
1437 goto finalize_byteorder;
1440 put_field (to, order, fmt->totalsize, fmt->exp_start, fmt->exp_len,
1441 exponent + fmt->exp_bias - 1);
1443 mant_bits_left = fmt->man_len;
1444 mant_off = fmt->man_start;
1445 while (mant_bits_left > 0)
1447 unsigned long mant_long;
1449 mant_bits = mant_bits_left < 32 ? mant_bits_left : 32;
1451 mpfr_mul_2ui (tmp.val, tmp.val, 32, MPFR_RNDN);
1452 mant_long = mpfr_get_ui (tmp.val, MPFR_RNDZ) & 0xffffffffL;
1453 mpfr_sub_ui (tmp.val, tmp.val, mant_long, MPFR_RNDZ);
1455 /* If the integer bit is implicit, then we need to discard it.
1456 If we are discarding a zero, we should be (but are not) creating
1457 a denormalized number which means adjusting the exponent
1458 (I think). */
1459 if (mant_bits_left == fmt->man_len
1460 && fmt->intbit == floatformat_intbit_no)
1462 mant_long <<= 1;
1463 mant_long &= 0xffffffffL;
1464 /* If we are processing the top 32 mantissa bits of a doublest
1465 so as to convert to a float value with implied integer bit,
1466 we will only be putting 31 of those 32 bits into the
1467 final value due to the discarding of the top bit. In the
1468 case of a small float value where the number of mantissa
1469 bits is less than 32, discarding the top bit does not alter
1470 the number of bits we will be adding to the result. */
1471 if (mant_bits == 32)
1472 mant_bits -= 1;
1475 if (mant_bits < 32)
1477 /* The bits we want are in the most significant MANT_BITS bits of
1478 mant_long. Move them to the least significant. */
1479 mant_long >>= 32 - mant_bits;
1482 put_field (to, order, fmt->totalsize,
1483 mant_off, mant_bits, mant_long);
1484 mant_off += mant_bits;
1485 mant_bits_left -= mant_bits;
1488 finalize_byteorder:
1489 /* Do we need to byte-swap the words in the result? */
1490 if (order != fmt->byteorder)
1491 floatformat_normalize_byteorder (fmt, newto, orig_to);
1494 void
1495 mpfr_float_ops::to_target (const struct type *type,
1496 const gdb_mpfr &from, gdb_byte *to) const
1498 /* Ensure possible padding bytes in the target buffer are zeroed out. */
1499 memset (to, 0, type->length ());
1501 to_target (floatformat_from_type (type), from, to);
1504 /* Convert the byte-stream ADDR, interpreted as floating-point type TYPE,
1505 to a string, optionally using the print format FORMAT. */
1506 std::string
1507 mpfr_float_ops::to_string (const gdb_byte *addr,
1508 const struct type *type,
1509 const char *format) const
1511 const struct floatformat *fmt = floatformat_from_type (type);
1513 /* Unless we need to adhere to a specific format, provide special
1514 output for certain cases. */
1515 if (format == nullptr)
1517 /* Detect invalid representations. */
1518 if (!floatformat_is_valid (fmt, addr))
1519 return "<invalid float value>";
1521 /* Handle NaN and Inf. */
1522 enum float_kind kind = floatformat_classify (fmt, addr);
1523 if (kind == float_nan)
1525 const char *sign = floatformat_is_negative (fmt, addr)? "-" : "";
1526 const char *mantissa = floatformat_mantissa (fmt, addr);
1527 return string_printf ("%snan(0x%s)", sign, mantissa);
1529 else if (kind == float_infinite)
1531 const char *sign = floatformat_is_negative (fmt, addr)? "-" : "";
1532 return string_printf ("%sinf", sign);
1536 /* Determine the format string to use on the host side. */
1537 std::string host_format = floatformat_printf_format (fmt, format, 'R');
1539 gdb_mpfr tmp (type);
1540 from_target (type, addr, tmp);
1542 int size = mpfr_snprintf (NULL, 0, host_format.c_str (), tmp.val);
1543 std::string str (size, '\0');
1544 mpfr_sprintf (&str[0], host_format.c_str (), tmp.val);
1546 return str;
1549 /* Parse string STRING into a target floating-number of type TYPE and
1550 store it as byte-stream ADDR. Return whether parsing succeeded. */
1551 bool
1552 mpfr_float_ops::from_string (gdb_byte *addr,
1553 const struct type *type,
1554 const std::string &in) const
1556 gdb_mpfr tmp (type);
1558 char *endptr;
1559 mpfr_strtofr (tmp.val, in.c_str (), &endptr, 0, MPFR_RNDN);
1561 /* We only accept the whole string. */
1562 if (*endptr)
1563 return false;
1565 to_target (type, tmp, addr);
1566 return true;
1569 /* Convert the byte-stream ADDR, interpreted as floating-point type TYPE,
1570 to an integer value (rounding towards zero). */
1571 LONGEST
1572 mpfr_float_ops::to_longest (const gdb_byte *addr,
1573 const struct type *type) const
1575 gdb_mpfr tmp (type);
1576 from_target (type, addr, tmp);
1577 return mpfr_get_sj (tmp.val, MPFR_RNDZ);
1580 /* Convert signed integer VAL to a target floating-number of type TYPE
1581 and store it as byte-stream ADDR. */
1582 void
1583 mpfr_float_ops::from_longest (gdb_byte *addr,
1584 const struct type *type,
1585 LONGEST val) const
1587 gdb_mpfr tmp (type);
1588 mpfr_set_sj (tmp.val, val, MPFR_RNDN);
1589 to_target (type, tmp, addr);
1592 /* Convert unsigned integer VAL to a target floating-number of type TYPE
1593 and store it as byte-stream ADDR. */
1594 void
1595 mpfr_float_ops::from_ulongest (gdb_byte *addr,
1596 const struct type *type,
1597 ULONGEST val) const
1599 gdb_mpfr tmp (type);
1600 mpfr_set_uj (tmp.val, val, MPFR_RNDN);
1601 to_target (type, tmp, addr);
1604 /* Convert the byte-stream ADDR, interpreted as floating-point type TYPE,
1605 to a floating-point value in the host "double" format. */
1606 double
1607 mpfr_float_ops::to_host_double (const gdb_byte *addr,
1608 const struct type *type) const
1610 gdb_mpfr tmp (type);
1611 from_target (type, addr, tmp);
1612 return mpfr_get_d (tmp.val, MPFR_RNDN);
1615 /* Convert floating-point value VAL in the host "double" format to a target
1616 floating-number of type TYPE and store it as byte-stream ADDR. */
1617 void
1618 mpfr_float_ops::from_host_double (gdb_byte *addr,
1619 const struct type *type,
1620 double val) const
1622 gdb_mpfr tmp (type);
1623 mpfr_set_d (tmp.val, val, MPFR_RNDN);
1624 to_target (type, tmp, addr);
1627 /* Convert a floating-point number of type FROM_TYPE from the target
1628 byte-stream FROM to a floating-point number of type TO_TYPE, and
1629 store it to the target byte-stream TO. */
1630 void
1631 mpfr_float_ops::convert (const gdb_byte *from,
1632 const struct type *from_type,
1633 gdb_byte *to,
1634 const struct type *to_type) const
1636 gdb_mpfr from_tmp (from_type), to_tmp (to_type);
1637 from_target (from_type, from, from_tmp);
1638 mpfr_set (to_tmp.val, from_tmp.val, MPFR_RNDN);
1639 to_target (to_type, to_tmp, to);
1642 /* Perform the binary operation indicated by OPCODE, using as operands the
1643 target byte streams X and Y, interpreted as floating-point numbers of
1644 types TYPE_X and TYPE_Y, respectively. Convert the result to type
1645 TYPE_RES and store it into the byte-stream RES. */
1646 void
1647 mpfr_float_ops::binop (enum exp_opcode op,
1648 const gdb_byte *x, const struct type *type_x,
1649 const gdb_byte *y, const struct type *type_y,
1650 gdb_byte *res, const struct type *type_res) const
1652 gdb_mpfr x_tmp (type_x), y_tmp (type_y), tmp (type_res);
1654 from_target (type_x, x, x_tmp);
1655 from_target (type_y, y, y_tmp);
1657 switch (op)
1659 case BINOP_ADD:
1660 mpfr_add (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
1661 break;
1663 case BINOP_SUB:
1664 mpfr_sub (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
1665 break;
1667 case BINOP_MUL:
1668 mpfr_mul (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
1669 break;
1671 case BINOP_DIV:
1672 mpfr_div (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
1673 break;
1675 case BINOP_EXP:
1676 mpfr_pow (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
1677 break;
1679 case BINOP_MIN:
1680 mpfr_min (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
1681 break;
1683 case BINOP_MAX:
1684 mpfr_max (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
1685 break;
1687 default:
1688 error (_("Integer-only operation on floating point number."));
1689 break;
1692 to_target (type_res, tmp, res);
1695 /* Compare the two target byte streams X and Y, interpreted as floating-point
1696 numbers of types TYPE_X and TYPE_Y, respectively. Return zero if X and Y
1697 are equal, -1 if X is less than Y, and 1 otherwise. */
1699 mpfr_float_ops::compare (const gdb_byte *x, const struct type *type_x,
1700 const gdb_byte *y, const struct type *type_y) const
1702 gdb_mpfr x_tmp (type_x), y_tmp (type_y);
1704 from_target (type_x, x, x_tmp);
1705 from_target (type_y, y, y_tmp);
1707 if (mpfr_equal_p (x_tmp.val, y_tmp.val))
1708 return 0;
1709 else if (mpfr_less_p (x_tmp.val, y_tmp.val))
1710 return -1;
1711 else
1712 return 1;
1716 /* Helper routines operating on decimal floating-point data. */
1718 /* Decimal floating point is one of the extension to IEEE 754, which is
1719 described in http://grouper.ieee.org/groups/754/revision.html and
1720 http://www2.hursley.ibm.com/decimal/. It completes binary floating
1721 point by representing floating point more exactly. */
1723 /* The order of the following headers is important for making sure
1724 decNumber structure is large enough to hold decimal128 digits. */
1726 #include "dpd/decimal128.h"
1727 #include "dpd/decimal64.h"
1728 #include "dpd/decimal32.h"
1730 /* When using decimal128, this is the maximum string length + 1
1731 (value comes from libdecnumber's DECIMAL128_String constant). */
1732 #define MAX_DECIMAL_STRING 43
1734 /* In GDB, we are using an array of gdb_byte to represent decimal values.
1735 They are stored in host byte order. This routine does the conversion if
1736 the target byte order is different. */
1737 static void
1738 match_endianness (const gdb_byte *from, const struct type *type, gdb_byte *to)
1740 gdb_assert (type->code () == TYPE_CODE_DECFLOAT);
1742 int len = type->length ();
1743 int i;
1745 #if WORDS_BIGENDIAN
1746 #define OPPOSITE_BYTE_ORDER BFD_ENDIAN_LITTLE
1747 #else
1748 #define OPPOSITE_BYTE_ORDER BFD_ENDIAN_BIG
1749 #endif
1751 if (type_byte_order (type) == OPPOSITE_BYTE_ORDER)
1752 for (i = 0; i < len; i++)
1753 to[i] = from[len - i - 1];
1754 else
1755 for (i = 0; i < len; i++)
1756 to[i] = from[i];
1758 return;
1761 /* Helper function to get the appropriate libdecnumber context for each size
1762 of decimal float. */
1763 static void
1764 set_decnumber_context (decContext *ctx, const struct type *type)
1766 gdb_assert (type->code () == TYPE_CODE_DECFLOAT);
1768 switch (type->length ())
1770 case 4:
1771 decContextDefault (ctx, DEC_INIT_DECIMAL32);
1772 break;
1773 case 8:
1774 decContextDefault (ctx, DEC_INIT_DECIMAL64);
1775 break;
1776 case 16:
1777 decContextDefault (ctx, DEC_INIT_DECIMAL128);
1778 break;
1781 ctx->traps = 0;
1784 /* Check for errors signaled in the decimal context structure. */
1785 static void
1786 decimal_check_errors (decContext *ctx)
1788 /* An error here could be a division by zero, an overflow, an underflow or
1789 an invalid operation (from the DEC_Errors constant in decContext.h).
1790 Since GDB doesn't complain about division by zero, overflow or underflow
1791 errors for binary floating, we won't complain about them for decimal
1792 floating either. */
1793 if (ctx->status & DEC_IEEE_854_Invalid_operation)
1795 /* Leave only the error bits in the status flags. */
1796 ctx->status &= DEC_IEEE_854_Invalid_operation;
1797 error (_("Cannot perform operation: %s"),
1798 decContextStatusToString (ctx));
1802 /* Helper function to convert from libdecnumber's appropriate representation
1803 for computation to each size of decimal float. */
1804 static void
1805 decimal_from_number (const decNumber *from,
1806 gdb_byte *to, const struct type *type)
1808 gdb_byte dec[16];
1810 decContext set;
1812 set_decnumber_context (&set, type);
1814 switch (type->length ())
1816 case 4:
1817 decimal32FromNumber ((decimal32 *) dec, from, &set);
1818 break;
1819 case 8:
1820 decimal64FromNumber ((decimal64 *) dec, from, &set);
1821 break;
1822 case 16:
1823 decimal128FromNumber ((decimal128 *) dec, from, &set);
1824 break;
1825 default:
1826 error (_("Unknown decimal floating point type."));
1827 break;
1830 match_endianness (dec, type, to);
1833 /* Helper function to convert each size of decimal float to libdecnumber's
1834 appropriate representation for computation. */
1835 static void
1836 decimal_to_number (const gdb_byte *addr, const struct type *type,
1837 decNumber *to)
1839 gdb_byte dec[16];
1840 match_endianness (addr, type, dec);
1842 switch (type->length ())
1844 case 4:
1845 decimal32ToNumber ((decimal32 *) dec, to);
1846 break;
1847 case 8:
1848 decimal64ToNumber ((decimal64 *) dec, to);
1849 break;
1850 case 16:
1851 decimal128ToNumber ((decimal128 *) dec, to);
1852 break;
1853 default:
1854 error (_("Unknown decimal floating point type."));
1855 break;
1859 /* Returns true if ADDR (which is of type TYPE) is the number zero. */
1860 static bool
1861 decimal_is_zero (const gdb_byte *addr, const struct type *type)
1863 decNumber number;
1865 decimal_to_number (addr, type, &number);
1867 return decNumberIsZero (&number);
1871 /* Implementation of target_float_ops using the libdecnumber decNumber type
1872 as intermediate format. */
1874 class decimal_float_ops : public target_float_ops
1876 public:
1877 std::string to_string (const gdb_byte *addr, const struct type *type,
1878 const char *format) const override;
1879 bool from_string (gdb_byte *addr, const struct type *type,
1880 const std::string &string) const override;
1882 LONGEST to_longest (const gdb_byte *addr,
1883 const struct type *type) const override;
1884 void from_longest (gdb_byte *addr, const struct type *type,
1885 LONGEST val) const override;
1886 void from_ulongest (gdb_byte *addr, const struct type *type,
1887 ULONGEST val) const override;
1888 double to_host_double (const gdb_byte *addr,
1889 const struct type *type) const override
1891 /* We don't support conversions between target decimal floating-point
1892 types and the host double type. */
1893 gdb_assert_not_reached ("invalid operation on decimal float");
1895 void from_host_double (gdb_byte *addr, const struct type *type,
1896 double val) const override
1898 /* We don't support conversions between target decimal floating-point
1899 types and the host double type. */
1900 gdb_assert_not_reached ("invalid operation on decimal float");
1902 void convert (const gdb_byte *from, const struct type *from_type,
1903 gdb_byte *to, const struct type *to_type) const override;
1905 void binop (enum exp_opcode opcode,
1906 const gdb_byte *x, const struct type *type_x,
1907 const gdb_byte *y, const struct type *type_y,
1908 gdb_byte *res, const struct type *type_res) const override;
1909 int compare (const gdb_byte *x, const struct type *type_x,
1910 const gdb_byte *y, const struct type *type_y) const override;
1913 /* Convert decimal type to its string representation. LEN is the length
1914 of the decimal type, 4 bytes for decimal32, 8 bytes for decimal64 and
1915 16 bytes for decimal128. */
1916 std::string
1917 decimal_float_ops::to_string (const gdb_byte *addr, const struct type *type,
1918 const char *format = nullptr) const
1920 gdb_byte dec[16];
1922 match_endianness (addr, type, dec);
1924 if (format != nullptr)
1926 /* We don't handle format strings (yet). If the host printf supports
1927 decimal floating point types, just use this. Otherwise, fall back
1928 to printing the number while ignoring the format string. */
1929 #if defined (PRINTF_HAS_DECFLOAT)
1930 /* FIXME: This makes unwarranted assumptions about the host ABI! */
1931 return string_printf (format, dec);
1932 #endif
1935 std::string result;
1936 result.resize (MAX_DECIMAL_STRING);
1938 switch (type->length ())
1940 case 4:
1941 decimal32ToString ((decimal32 *) dec, &result[0]);
1942 break;
1943 case 8:
1944 decimal64ToString ((decimal64 *) dec, &result[0]);
1945 break;
1946 case 16:
1947 decimal128ToString ((decimal128 *) dec, &result[0]);
1948 break;
1949 default:
1950 error (_("Unknown decimal floating point type."));
1951 break;
1954 return result;
1957 /* Convert the string form of a decimal value to its decimal representation.
1958 LEN is the length of the decimal type, 4 bytes for decimal32, 8 bytes for
1959 decimal64 and 16 bytes for decimal128. */
1960 bool
1961 decimal_float_ops::from_string (gdb_byte *addr, const struct type *type,
1962 const std::string &string) const
1964 decContext set;
1965 gdb_byte dec[16];
1967 set_decnumber_context (&set, type);
1969 switch (type->length ())
1971 case 4:
1972 decimal32FromString ((decimal32 *) dec, string.c_str (), &set);
1973 break;
1974 case 8:
1975 decimal64FromString ((decimal64 *) dec, string.c_str (), &set);
1976 break;
1977 case 16:
1978 decimal128FromString ((decimal128 *) dec, string.c_str (), &set);
1979 break;
1980 default:
1981 error (_("Unknown decimal floating point type."));
1982 break;
1985 match_endianness (dec, type, addr);
1987 /* Check for errors in the DFP operation. */
1988 decimal_check_errors (&set);
1990 return true;
1993 /* Converts a LONGEST to a decimal float of specified LEN bytes. */
1994 void
1995 decimal_float_ops::from_longest (gdb_byte *addr, const struct type *type,
1996 LONGEST from) const
1998 decNumber number;
2000 if ((int32_t) from != from)
2001 /* libdecnumber can convert only 32-bit integers. */
2002 error (_("Conversion of large integer to a "
2003 "decimal floating type is not supported."));
2005 decNumberFromInt32 (&number, (int32_t) from);
2007 decimal_from_number (&number, addr, type);
2010 /* Converts a ULONGEST to a decimal float of specified LEN bytes. */
2011 void
2012 decimal_float_ops::from_ulongest (gdb_byte *addr, const struct type *type,
2013 ULONGEST from) const
2015 decNumber number;
2017 if ((uint32_t) from != from)
2018 /* libdecnumber can convert only 32-bit integers. */
2019 error (_("Conversion of large integer to a "
2020 "decimal floating type is not supported."));
2022 decNumberFromUInt32 (&number, (uint32_t) from);
2024 decimal_from_number (&number, addr, type);
2027 /* Converts a decimal float of LEN bytes to a LONGEST. */
2028 LONGEST
2029 decimal_float_ops::to_longest (const gdb_byte *addr,
2030 const struct type *type) const
2032 /* libdecnumber has a function to convert from decimal to integer, but
2033 it doesn't work when the decimal number has a fractional part. */
2034 std::string str = to_string (addr, type);
2035 return strtoll (str.c_str (), NULL, 10);
2038 /* Perform operation OP with operands X and Y with sizes LEN_X and LEN_Y
2039 and byte orders BYTE_ORDER_X and BYTE_ORDER_Y, and store value in
2040 RESULT with size LEN_RESULT and byte order BYTE_ORDER_RESULT. */
2041 void
2042 decimal_float_ops::binop (enum exp_opcode op,
2043 const gdb_byte *x, const struct type *type_x,
2044 const gdb_byte *y, const struct type *type_y,
2045 gdb_byte *res, const struct type *type_res) const
2047 decContext set;
2048 decNumber number1, number2, number3;
2050 decimal_to_number (x, type_x, &number1);
2051 decimal_to_number (y, type_y, &number2);
2053 set_decnumber_context (&set, type_res);
2055 switch (op)
2057 case BINOP_ADD:
2058 decNumberAdd (&number3, &number1, &number2, &set);
2059 break;
2060 case BINOP_SUB:
2061 decNumberSubtract (&number3, &number1, &number2, &set);
2062 break;
2063 case BINOP_MUL:
2064 decNumberMultiply (&number3, &number1, &number2, &set);
2065 break;
2066 case BINOP_DIV:
2067 decNumberDivide (&number3, &number1, &number2, &set);
2068 break;
2069 case BINOP_EXP:
2070 decNumberPower (&number3, &number1, &number2, &set);
2071 break;
2072 default:
2073 error (_("Operation not valid for decimal floating point number."));
2074 break;
2077 /* Check for errors in the DFP operation. */
2078 decimal_check_errors (&set);
2080 decimal_from_number (&number3, res, type_res);
2083 /* Compares two numbers numerically. If X is less than Y then the return value
2084 will be -1. If they are equal, then the return value will be 0. If X is
2085 greater than the Y then the return value will be 1. */
2087 decimal_float_ops::compare (const gdb_byte *x, const struct type *type_x,
2088 const gdb_byte *y, const struct type *type_y) const
2090 decNumber number1, number2, result;
2091 decContext set;
2092 const struct type *type_result;
2094 decimal_to_number (x, type_x, &number1);
2095 decimal_to_number (y, type_y, &number2);
2097 /* Perform the comparison in the larger of the two sizes. */
2098 type_result = type_x->length () > type_y->length () ? type_x : type_y;
2099 set_decnumber_context (&set, type_result);
2101 decNumberCompare (&result, &number1, &number2, &set);
2103 /* Check for errors in the DFP operation. */
2104 decimal_check_errors (&set);
2106 if (decNumberIsNaN (&result))
2107 error (_("Comparison with an invalid number (NaN)."));
2108 else if (decNumberIsZero (&result))
2109 return 0;
2110 else if (decNumberIsNegative (&result))
2111 return -1;
2112 else
2113 return 1;
2116 /* Convert a decimal value from a decimal type with LEN_FROM bytes to a
2117 decimal type with LEN_TO bytes. */
2118 void
2119 decimal_float_ops::convert (const gdb_byte *from, const struct type *from_type,
2120 gdb_byte *to, const struct type *to_type) const
2122 decNumber number;
2124 decimal_to_number (from, from_type, &number);
2125 decimal_from_number (&number, to, to_type);
2129 /* Typed floating-point routines. These routines operate on floating-point
2130 values in target format, represented by a byte buffer interpreted as a
2131 "struct type", which may be either a binary or decimal floating-point
2132 type (TYPE_CODE_FLT or TYPE_CODE_DECFLOAT). */
2134 /* Return whether TYPE1 and TYPE2 are of the same category (binary or
2135 decimal floating-point). */
2136 static bool
2137 target_float_same_category_p (const struct type *type1,
2138 const struct type *type2)
2140 return type1->code () == type2->code ();
2143 /* Return whether TYPE1 and TYPE2 use the same floating-point format. */
2144 static bool
2145 target_float_same_format_p (const struct type *type1,
2146 const struct type *type2)
2148 if (!target_float_same_category_p (type1, type2))
2149 return false;
2151 switch (type1->code ())
2153 case TYPE_CODE_FLT:
2154 return floatformat_from_type (type1) == floatformat_from_type (type2);
2156 case TYPE_CODE_DECFLOAT:
2157 return (type1->length () == type2->length ()
2158 && (type_byte_order (type1)
2159 == type_byte_order (type2)));
2161 default:
2162 gdb_assert_not_reached ("unexpected type code");
2166 /* Return the size (without padding) of the target floating-point
2167 format used by TYPE. */
2168 static int
2169 target_float_format_length (const struct type *type)
2171 switch (type->code ())
2173 case TYPE_CODE_FLT:
2174 return floatformat_totalsize_bytes (floatformat_from_type (type));
2176 case TYPE_CODE_DECFLOAT:
2177 return type->length ();
2179 default:
2180 gdb_assert_not_reached ("unexpected type code");
2184 /* Identifiers of available host-side intermediate formats. These must
2185 be sorted so the that the more "general" kinds come later. */
2186 enum target_float_ops_kind
2188 /* Target binary floating-point formats that match a host format. */
2189 host_float = 0,
2190 host_double,
2191 host_long_double,
2192 /* Any other target binary floating-point format. */
2193 binary,
2194 /* Any target decimal floating-point format. */
2195 decimal
2198 /* Given a target type TYPE, choose the best host-side intermediate format
2199 to perform operations on TYPE in. */
2200 static enum target_float_ops_kind
2201 get_target_float_ops_kind (const struct type *type)
2203 switch (type->code ())
2205 case TYPE_CODE_FLT:
2207 const struct floatformat *fmt = floatformat_from_type (type);
2209 /* Binary floating-point formats matching a host format. */
2210 if (fmt == host_float_format)
2211 return target_float_ops_kind::host_float;
2212 if (fmt == host_double_format)
2213 return target_float_ops_kind::host_double;
2214 if (fmt == host_long_double_format)
2215 return target_float_ops_kind::host_long_double;
2217 /* Any other binary floating-point format. */
2218 return target_float_ops_kind::binary;
2221 case TYPE_CODE_DECFLOAT:
2223 /* Any decimal floating-point format. */
2224 return target_float_ops_kind::decimal;
2227 default:
2228 gdb_assert_not_reached ("unexpected type code");
2232 /* Return target_float_ops to perform operations for KIND. */
2233 static const target_float_ops *
2234 get_target_float_ops (enum target_float_ops_kind kind)
2236 switch (kind)
2238 /* If the type format matches one of the host floating-point
2239 types, use that type as intermediate format. */
2240 case target_float_ops_kind::host_float:
2242 static host_float_ops<float> host_float_ops_float;
2243 return &host_float_ops_float;
2246 case target_float_ops_kind::host_double:
2248 static host_float_ops<double> host_float_ops_double;
2249 return &host_float_ops_double;
2252 case target_float_ops_kind::host_long_double:
2254 static host_float_ops<long double> host_float_ops_long_double;
2255 return &host_float_ops_long_double;
2258 /* For binary floating-point formats that do not match any host format,
2259 use mpfr_t as intermediate format to provide precise target-floating
2260 point emulation. However, if the MPFR library is not available,
2261 use the largest host floating-point type as intermediate format. */
2262 case target_float_ops_kind::binary:
2264 static mpfr_float_ops binary_float_ops;
2265 return &binary_float_ops;
2268 /* For decimal floating-point types, always use the libdecnumber
2269 decNumber type as intermediate format. */
2270 case target_float_ops_kind::decimal:
2272 static decimal_float_ops decimal_float_ops;
2273 return &decimal_float_ops;
2276 default:
2277 gdb_assert_not_reached ("unexpected target_float_ops_kind");
2281 /* Given a target type TYPE, determine the best host-side intermediate format
2282 to perform operations on TYPE in. */
2283 static const target_float_ops *
2284 get_target_float_ops (const struct type *type)
2286 enum target_float_ops_kind kind = get_target_float_ops_kind (type);
2287 return get_target_float_ops (kind);
2290 /* The same for operations involving two target types TYPE1 and TYPE2. */
2291 static const target_float_ops *
2292 get_target_float_ops (const struct type *type1, const struct type *type2)
2294 gdb_assert (type1->code () == type2->code ());
2296 enum target_float_ops_kind kind1 = get_target_float_ops_kind (type1);
2297 enum target_float_ops_kind kind2 = get_target_float_ops_kind (type2);
2299 /* Given the way the kinds are sorted, we simply choose the larger one;
2300 this will be able to hold values of either type. */
2301 return get_target_float_ops (std::max (kind1, kind2));
2304 /* Return whether the byte-stream ADDR holds a valid value of
2305 floating-point type TYPE. */
2306 bool
2307 target_float_is_valid (const gdb_byte *addr, const struct type *type)
2309 if (type->code () == TYPE_CODE_FLT)
2310 return floatformat_is_valid (floatformat_from_type (type), addr);
2312 if (type->code () == TYPE_CODE_DECFLOAT)
2313 return true;
2315 gdb_assert_not_reached ("unexpected type code");
2318 /* Return whether the byte-stream ADDR, interpreted as floating-point
2319 type TYPE, is numerically equal to zero (of either sign). */
2320 bool
2321 target_float_is_zero (const gdb_byte *addr, const struct type *type)
2323 if (type->code () == TYPE_CODE_FLT)
2324 return (floatformat_classify (floatformat_from_type (type), addr)
2325 == float_zero);
2327 if (type->code () == TYPE_CODE_DECFLOAT)
2328 return decimal_is_zero (addr, type);
2330 gdb_assert_not_reached ("unexpected type code");
2333 /* Convert the byte-stream ADDR, interpreted as floating-point type TYPE,
2334 to a string, optionally using the print format FORMAT. */
2335 std::string
2336 target_float_to_string (const gdb_byte *addr, const struct type *type,
2337 const char *format)
2339 /* Unless we need to adhere to a specific format, provide special
2340 output for special cases of binary floating-point numbers. */
2341 if (format == nullptr && type->code () == TYPE_CODE_FLT)
2343 const struct floatformat *fmt = floatformat_from_type (type);
2345 /* Detect invalid representations. */
2346 if (!floatformat_is_valid (fmt, addr))
2347 return "<invalid float value>";
2349 /* Handle NaN and Inf. */
2350 enum float_kind kind = floatformat_classify (fmt, addr);
2351 if (kind == float_nan)
2353 const char *sign = floatformat_is_negative (fmt, addr)? "-" : "";
2354 const char *mantissa = floatformat_mantissa (fmt, addr);
2355 return string_printf ("%snan(0x%s)", sign, mantissa);
2357 else if (kind == float_infinite)
2359 const char *sign = floatformat_is_negative (fmt, addr)? "-" : "";
2360 return string_printf ("%sinf", sign);
2364 const target_float_ops *ops = get_target_float_ops (type);
2365 return ops->to_string (addr, type, format);
2368 /* Parse string STRING into a target floating-number of type TYPE and
2369 store it as byte-stream ADDR. Return whether parsing succeeded. */
2370 bool
2371 target_float_from_string (gdb_byte *addr, const struct type *type,
2372 const std::string &string)
2374 const target_float_ops *ops = get_target_float_ops (type);
2375 return ops->from_string (addr, type, string);
2378 /* Convert the byte-stream ADDR, interpreted as floating-point type TYPE,
2379 to an integer value (rounding towards zero). */
2380 LONGEST
2381 target_float_to_longest (const gdb_byte *addr, const struct type *type)
2383 const target_float_ops *ops = get_target_float_ops (type);
2384 return ops->to_longest (addr, type);
2387 /* Convert signed integer VAL to a target floating-number of type TYPE
2388 and store it as byte-stream ADDR. */
2389 void
2390 target_float_from_longest (gdb_byte *addr, const struct type *type,
2391 LONGEST val)
2393 const target_float_ops *ops = get_target_float_ops (type);
2394 ops->from_longest (addr, type, val);
2397 /* Convert unsigned integer VAL to a target floating-number of type TYPE
2398 and store it as byte-stream ADDR. */
2399 void
2400 target_float_from_ulongest (gdb_byte *addr, const struct type *type,
2401 ULONGEST val)
2403 const target_float_ops *ops = get_target_float_ops (type);
2404 ops->from_ulongest (addr, type, val);
2407 /* Convert the byte-stream ADDR, interpreted as floating-point type TYPE,
2408 to a floating-point value in the host "double" format. */
2409 double
2410 target_float_to_host_double (const gdb_byte *addr,
2411 const struct type *type)
2413 const target_float_ops *ops = get_target_float_ops (type);
2414 return ops->to_host_double (addr, type);
2417 /* Convert floating-point value VAL in the host "double" format to a target
2418 floating-number of type TYPE and store it as byte-stream ADDR. */
2419 void
2420 target_float_from_host_double (gdb_byte *addr, const struct type *type,
2421 double val)
2423 const target_float_ops *ops = get_target_float_ops (type);
2424 ops->from_host_double (addr, type, val);
2427 /* Convert a floating-point number of type FROM_TYPE from the target
2428 byte-stream FROM to a floating-point number of type TO_TYPE, and
2429 store it to the target byte-stream TO. */
2430 void
2431 target_float_convert (const gdb_byte *from, const struct type *from_type,
2432 gdb_byte *to, const struct type *to_type)
2434 /* We cannot directly convert between binary and decimal floating-point
2435 types, so go via an intermediary string. */
2436 if (!target_float_same_category_p (from_type, to_type))
2438 std::string str = target_float_to_string (from, from_type);
2439 target_float_from_string (to, to_type, str);
2440 return;
2443 /* Convert between two different formats in the same category. */
2444 if (!target_float_same_format_p (from_type, to_type))
2446 const target_float_ops *ops = get_target_float_ops (from_type, to_type);
2447 ops->convert (from, from_type, to, to_type);
2448 return;
2451 /* The floating-point formats match, so we simply copy the data, ensuring
2452 possible padding bytes in the target buffer are zeroed out. */
2453 memset (to, 0, to_type->length ());
2454 memcpy (to, from, target_float_format_length (to_type));
2457 /* Perform the binary operation indicated by OPCODE, using as operands the
2458 target byte streams X and Y, interpreted as floating-point numbers of
2459 types TYPE_X and TYPE_Y, respectively. Convert the result to type
2460 TYPE_RES and store it into the byte-stream RES.
2462 The three types must either be all binary floating-point types, or else
2463 all decimal floating-point types. Binary and decimal floating-point
2464 types cannot be mixed within a single operation. */
2465 void
2466 target_float_binop (enum exp_opcode opcode,
2467 const gdb_byte *x, const struct type *type_x,
2468 const gdb_byte *y, const struct type *type_y,
2469 gdb_byte *res, const struct type *type_res)
2471 gdb_assert (target_float_same_category_p (type_x, type_res));
2472 gdb_assert (target_float_same_category_p (type_y, type_res));
2474 const target_float_ops *ops = get_target_float_ops (type_x, type_y);
2475 ops->binop (opcode, x, type_x, y, type_y, res, type_res);
2478 /* Compare the two target byte streams X and Y, interpreted as floating-point
2479 numbers of types TYPE_X and TYPE_Y, respectively. Return zero if X and Y
2480 are equal, -1 if X is less than Y, and 1 otherwise.
2482 The two types must either both be binary floating-point types, or else
2483 both be decimal floating-point types. Binary and decimal floating-point
2484 types cannot compared directly against each other. */
2486 target_float_compare (const gdb_byte *x, const struct type *type_x,
2487 const gdb_byte *y, const struct type *type_y)
2489 gdb_assert (target_float_same_category_p (type_x, type_y));
2491 const target_float_ops *ops = get_target_float_ops (type_x, type_y);
2492 return ops->compare (x, type_x, y, type_y);