2011-08-01 Paul Pluzhnikov <ppluzhnikov@google.com>
[platform/upstream/binutils.git] / gdb / doublest.c
1 /* Floating point routines for GDB, the GNU debugger.
2
3    Copyright (C) 1986, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
4    1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2007, 2008, 2009, 2010,
5    2011 Free Software Foundation, Inc.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 /* Support for converting target fp numbers into host DOUBLEST format.  */
23
24 /* XXX - This code should really be in libiberty/floatformat.c,
25    however configuration issues with libiberty made this very
26    difficult to do in the available time.  */
27
28 #include "defs.h"
29 #include "doublest.h"
30 #include "floatformat.h"
31 #include "gdb_assert.h"
32 #include "gdb_string.h"
33 #include "gdbtypes.h"
34 #include <math.h>               /* ldexp */
35
36 /* The odds that CHAR_BIT will be anything but 8 are low enough that I'm not
37    going to bother with trying to muck around with whether it is defined in
38    a system header, what we do if not, etc.  */
39 #define FLOATFORMAT_CHAR_BIT 8
40
41 /* The number of bytes that the largest floating-point type that we
42    can convert to doublest will need.  */
43 #define FLOATFORMAT_LARGEST_BYTES 16
44
45 /* Extract a field which starts at START and is LEN bytes long.  DATA and
46    TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER.  */
47 static unsigned long
48 get_field (const bfd_byte *data, enum floatformat_byteorders order,
49            unsigned int total_len, unsigned int start, unsigned int len)
50 {
51   unsigned long result;
52   unsigned int cur_byte;
53   int cur_bitshift;
54
55   /* Caller must byte-swap words before calling this routine.  */
56   gdb_assert (order == floatformat_little || order == floatformat_big);
57
58   /* Start at the least significant part of the field.  */
59   if (order == floatformat_little)
60     {
61       /* We start counting from the other end (i.e, from the high bytes
62          rather than the low bytes).  As such, we need to be concerned
63          with what happens if bit 0 doesn't start on a byte boundary.
64          I.e, we need to properly handle the case where total_len is
65          not evenly divisible by 8.  So we compute ``excess'' which
66          represents the number of bits from the end of our starting
67          byte needed to get to bit 0.  */
68       int excess = FLOATFORMAT_CHAR_BIT - (total_len % FLOATFORMAT_CHAR_BIT);
69
70       cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) 
71                  - ((start + len + excess) / FLOATFORMAT_CHAR_BIT);
72       cur_bitshift = ((start + len + excess) % FLOATFORMAT_CHAR_BIT) 
73                      - FLOATFORMAT_CHAR_BIT;
74     }
75   else
76     {
77       cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
78       cur_bitshift =
79         ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
80     }
81   if (cur_bitshift > -FLOATFORMAT_CHAR_BIT)
82     result = *(data + cur_byte) >> (-cur_bitshift);
83   else
84     result = 0;
85   cur_bitshift += FLOATFORMAT_CHAR_BIT;
86   if (order == floatformat_little)
87     ++cur_byte;
88   else
89     --cur_byte;
90
91   /* Move towards the most significant part of the field.  */
92   while (cur_bitshift < len)
93     {
94       result |= (unsigned long)*(data + cur_byte) << cur_bitshift;
95       cur_bitshift += FLOATFORMAT_CHAR_BIT;
96       switch (order)
97         {
98         case floatformat_little:
99           ++cur_byte;
100           break;
101         case floatformat_big:
102           --cur_byte;
103           break;
104         }
105     }
106   if (len < sizeof(result) * FLOATFORMAT_CHAR_BIT)
107     /* Mask out bits which are not part of the field.  */
108     result &= ((1UL << len) - 1);
109   return result;
110 }
111
112 /* Normalize the byte order of FROM into TO.  If no normalization is
113    needed then FMT->byteorder is returned and TO is not changed;
114    otherwise the format of the normalized form in TO is returned.  */
115
116 static enum floatformat_byteorders
117 floatformat_normalize_byteorder (const struct floatformat *fmt,
118                                  const void *from, void *to)
119 {
120   const unsigned char *swapin;
121   unsigned char *swapout;
122   int words;
123   
124   if (fmt->byteorder == floatformat_little
125       || fmt->byteorder == floatformat_big)
126     return fmt->byteorder;
127
128   words = fmt->totalsize / FLOATFORMAT_CHAR_BIT;
129   words >>= 2;
130
131   swapout = (unsigned char *)to;
132   swapin = (const unsigned char *)from;
133
134   if (fmt->byteorder == floatformat_vax)
135     {
136       while (words-- > 0)
137         {
138           *swapout++ = swapin[1];
139           *swapout++ = swapin[0];
140           *swapout++ = swapin[3];
141           *swapout++ = swapin[2];
142           swapin += 4;
143         }
144       /* This may look weird, since VAX is little-endian, but it is
145          easier to translate to big-endian than to little-endian.  */
146       return floatformat_big;
147     }
148   else
149     {
150       gdb_assert (fmt->byteorder == floatformat_littlebyte_bigword);
151
152       while (words-- > 0)
153         {
154           *swapout++ = swapin[3];
155           *swapout++ = swapin[2];
156           *swapout++ = swapin[1];
157           *swapout++ = swapin[0];
158           swapin += 4;
159         }
160       return floatformat_big;
161     }
162 }
163   
164 /* Convert from FMT to a DOUBLEST.
165    FROM is the address of the extended float.
166    Store the DOUBLEST in *TO.  */
167
168 static void
169 convert_floatformat_to_doublest (const struct floatformat *fmt,
170                                  const void *from,
171                                  DOUBLEST *to)
172 {
173   unsigned char *ufrom = (unsigned char *) from;
174   DOUBLEST dto;
175   long exponent;
176   unsigned long mant;
177   unsigned int mant_bits, mant_off;
178   int mant_bits_left;
179   int special_exponent;         /* It's a NaN, denorm or zero.  */
180   enum floatformat_byteorders order;
181   unsigned char newfrom[FLOATFORMAT_LARGEST_BYTES];
182   enum float_kind kind;
183   
184   gdb_assert (fmt->totalsize
185               <= FLOATFORMAT_LARGEST_BYTES * FLOATFORMAT_CHAR_BIT);
186
187   /* For non-numbers, reuse libiberty's logic to find the correct
188      format.  We do not lose any precision in this case by passing
189      through a double.  */
190   kind = floatformat_classify (fmt, from);
191   if (kind == float_infinite || kind == float_nan)
192     {
193       double dto;
194
195       floatformat_to_double (fmt, from, &dto);
196       *to = (DOUBLEST) dto;
197       return;
198     }
199
200   order = floatformat_normalize_byteorder (fmt, ufrom, newfrom);
201
202   if (order != fmt->byteorder)
203     ufrom = newfrom;
204
205   if (fmt->split_half)
206     {
207       DOUBLEST dtop, dbot;
208
209       floatformat_to_doublest (fmt->split_half, ufrom, &dtop);
210       /* Preserve the sign of 0, which is the sign of the top
211          half.  */
212       if (dtop == 0.0)
213         {
214           *to = dtop;
215           return;
216         }
217       floatformat_to_doublest (fmt->split_half,
218                              ufrom + fmt->totalsize / FLOATFORMAT_CHAR_BIT / 2,
219                              &dbot);
220       *to = dtop + dbot;
221       return;
222     }
223
224   exponent = get_field (ufrom, order, fmt->totalsize, fmt->exp_start,
225                         fmt->exp_len);
226   /* Note that if exponent indicates a NaN, we can't really do anything useful
227      (not knowing if the host has NaN's, or how to build one).  So it will
228      end up as an infinity or something close; that is OK.  */
229
230   mant_bits_left = fmt->man_len;
231   mant_off = fmt->man_start;
232   dto = 0.0;
233
234   special_exponent = exponent == 0 || exponent == fmt->exp_nan;
235
236   /* Don't bias NaNs.  Use minimum exponent for denorms.  For
237      simplicity, we don't check for zero as the exponent doesn't matter.
238      Note the cast to int; exp_bias is unsigned, so it's important to
239      make sure the operation is done in signed arithmetic.  */
240   if (!special_exponent)
241     exponent -= fmt->exp_bias;
242   else if (exponent == 0)
243     exponent = 1 - fmt->exp_bias;
244
245   /* Build the result algebraically.  Might go infinite, underflow, etc;
246      who cares.  */
247
248 /* If this format uses a hidden bit, explicitly add it in now.  Otherwise,
249    increment the exponent by one to account for the integer bit.  */
250
251   if (!special_exponent)
252     {
253       if (fmt->intbit == floatformat_intbit_no)
254         dto = ldexp (1.0, exponent);
255       else
256         exponent++;
257     }
258
259   while (mant_bits_left > 0)
260     {
261       mant_bits = min (mant_bits_left, 32);
262
263       mant = get_field (ufrom, order, fmt->totalsize, mant_off, mant_bits);
264
265       dto += ldexp ((double) mant, exponent - mant_bits);
266       exponent -= mant_bits;
267       mant_off += mant_bits;
268       mant_bits_left -= mant_bits;
269     }
270
271   /* Negate it if negative.  */
272   if (get_field (ufrom, order, fmt->totalsize, fmt->sign_start, 1))
273     dto = -dto;
274   *to = dto;
275 }
276 \f
277 /* Set a field which starts at START and is LEN bytes long.  DATA and
278    TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER.  */
279 static void
280 put_field (unsigned char *data, enum floatformat_byteorders order,
281            unsigned int total_len, unsigned int start, unsigned int len,
282            unsigned long stuff_to_put)
283 {
284   unsigned int cur_byte;
285   int cur_bitshift;
286
287   /* Caller must byte-swap words before calling this routine.  */
288   gdb_assert (order == floatformat_little || order == floatformat_big);
289
290   /* Start at the least significant part of the field.  */
291   if (order == floatformat_little)
292     {
293       int excess = FLOATFORMAT_CHAR_BIT - (total_len % FLOATFORMAT_CHAR_BIT);
294
295       cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) 
296                  - ((start + len + excess) / FLOATFORMAT_CHAR_BIT);
297       cur_bitshift = ((start + len + excess) % FLOATFORMAT_CHAR_BIT) 
298                      - FLOATFORMAT_CHAR_BIT;
299     }
300   else
301     {
302       cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
303       cur_bitshift =
304         ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
305     }
306   if (cur_bitshift > -FLOATFORMAT_CHAR_BIT)
307     {
308       *(data + cur_byte) &=
309         ~(((1 << ((start + len) % FLOATFORMAT_CHAR_BIT)) - 1)
310           << (-cur_bitshift));
311       *(data + cur_byte) |=
312         (stuff_to_put & ((1 << FLOATFORMAT_CHAR_BIT) - 1)) << (-cur_bitshift);
313     }
314   cur_bitshift += FLOATFORMAT_CHAR_BIT;
315   if (order == floatformat_little)
316     ++cur_byte;
317   else
318     --cur_byte;
319
320   /* Move towards the most significant part of the field.  */
321   while (cur_bitshift < len)
322     {
323       if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
324         {
325           /* This is the last byte.  */
326           *(data + cur_byte) &=
327             ~((1 << (len - cur_bitshift)) - 1);
328           *(data + cur_byte) |= (stuff_to_put >> cur_bitshift);
329         }
330       else
331         *(data + cur_byte) = ((stuff_to_put >> cur_bitshift)
332                               & ((1 << FLOATFORMAT_CHAR_BIT) - 1));
333       cur_bitshift += FLOATFORMAT_CHAR_BIT;
334       if (order == floatformat_little)
335         ++cur_byte;
336       else
337         --cur_byte;
338     }
339 }
340
341 #ifdef HAVE_LONG_DOUBLE
342 /* Return the fractional part of VALUE, and put the exponent of VALUE in *EPTR.
343    The range of the returned value is >= 0.5 and < 1.0.  This is equivalent to
344    frexp, but operates on the long double data type.  */
345
346 static long double ldfrexp (long double value, int *eptr);
347
348 static long double
349 ldfrexp (long double value, int *eptr)
350 {
351   long double tmp;
352   int exp;
353
354   /* Unfortunately, there are no portable functions for extracting the
355      exponent of a long double, so we have to do it iteratively by
356      multiplying or dividing by two until the fraction is between 0.5
357      and 1.0.  */
358
359   if (value < 0.0l)
360     value = -value;
361
362   tmp = 1.0l;
363   exp = 0;
364
365   if (value >= tmp)             /* Value >= 1.0 */
366     while (value >= tmp)
367       {
368         tmp *= 2.0l;
369         exp++;
370       }
371   else if (value != 0.0l)       /* Value < 1.0  and > 0.0 */
372     {
373       while (value < tmp)
374         {
375           tmp /= 2.0l;
376           exp--;
377         }
378       tmp *= 2.0l;
379       exp++;
380     }
381
382   *eptr = exp;
383   return value / tmp;
384 }
385 #endif /* HAVE_LONG_DOUBLE */
386
387
388 /* The converse: convert the DOUBLEST *FROM to an extended float and
389    store where TO points.  Neither FROM nor TO have any alignment
390    restrictions.  */
391
392 static void
393 convert_doublest_to_floatformat (CONST struct floatformat *fmt,
394                                  const DOUBLEST *from, void *to)
395 {
396   DOUBLEST dfrom;
397   int exponent;
398   DOUBLEST mant;
399   unsigned int mant_bits, mant_off;
400   int mant_bits_left;
401   unsigned char *uto = (unsigned char *) to;
402   enum floatformat_byteorders order = fmt->byteorder;
403   unsigned char newto[FLOATFORMAT_LARGEST_BYTES];
404
405   if (order != floatformat_little)
406     order = floatformat_big;
407
408   if (order != fmt->byteorder)
409     uto = newto;
410
411   memcpy (&dfrom, from, sizeof (dfrom));
412   memset (uto, 0, (fmt->totalsize + FLOATFORMAT_CHAR_BIT - 1) 
413                     / FLOATFORMAT_CHAR_BIT);
414
415   if (fmt->split_half)
416     {
417       /* Use static volatile to ensure that any excess precision is
418          removed via storing in memory, and so the top half really is
419          the result of converting to double.  */
420       static volatile double dtop, dbot;
421       DOUBLEST dtopnv, dbotnv;
422
423       dtop = (double) dfrom;
424       /* If the rounded top half is Inf, the bottom must be 0 not NaN
425          or Inf.  */
426       if (dtop + dtop == dtop && dtop != 0.0)
427         dbot = 0.0;
428       else
429         dbot = (double) (dfrom - (DOUBLEST) dtop);
430       dtopnv = dtop;
431       dbotnv = dbot;
432       floatformat_from_doublest (fmt->split_half, &dtopnv, uto);
433       floatformat_from_doublest (fmt->split_half, &dbotnv,
434                                (uto
435                                 + fmt->totalsize / FLOATFORMAT_CHAR_BIT / 2));
436       return;
437     }
438
439   if (dfrom == 0)
440     return;                     /* Result is zero */
441   if (dfrom != dfrom)           /* Result is NaN */
442     {
443       /* From is NaN */
444       put_field (uto, order, fmt->totalsize, fmt->exp_start,
445                  fmt->exp_len, fmt->exp_nan);
446       /* Be sure it's not infinity, but NaN value is irrel.  */
447       put_field (uto, order, fmt->totalsize, fmt->man_start,
448                  fmt->man_len, 1);
449       goto finalize_byteorder;
450     }
451
452   /* If negative, set the sign bit.  */
453   if (dfrom < 0)
454     {
455       put_field (uto, order, fmt->totalsize, fmt->sign_start, 1, 1);
456       dfrom = -dfrom;
457     }
458
459   if (dfrom + dfrom == dfrom && dfrom != 0.0)   /* Result is Infinity.  */
460     {
461       /* Infinity exponent is same as NaN's.  */
462       put_field (uto, order, fmt->totalsize, fmt->exp_start,
463                  fmt->exp_len, fmt->exp_nan);
464       /* Infinity mantissa is all zeroes.  */
465       put_field (uto, order, fmt->totalsize, fmt->man_start,
466                  fmt->man_len, 0);
467       goto finalize_byteorder;
468     }
469
470 #ifdef HAVE_LONG_DOUBLE
471   mant = ldfrexp (dfrom, &exponent);
472 #else
473   mant = frexp (dfrom, &exponent);
474 #endif
475
476   put_field (uto, order, fmt->totalsize, fmt->exp_start, fmt->exp_len,
477              exponent + fmt->exp_bias - 1);
478
479   mant_bits_left = fmt->man_len;
480   mant_off = fmt->man_start;
481   while (mant_bits_left > 0)
482     {
483       unsigned long mant_long;
484
485       mant_bits = mant_bits_left < 32 ? mant_bits_left : 32;
486
487       mant *= 4294967296.0;
488       mant_long = ((unsigned long) mant) & 0xffffffffL;
489       mant -= mant_long;
490
491       /* If the integer bit is implicit, then we need to discard it.
492          If we are discarding a zero, we should be (but are not) creating
493          a denormalized number which means adjusting the exponent
494          (I think).  */
495       if (mant_bits_left == fmt->man_len
496           && fmt->intbit == floatformat_intbit_no)
497         {
498           mant_long <<= 1;
499           mant_long &= 0xffffffffL;
500           /* If we are processing the top 32 mantissa bits of a doublest
501              so as to convert to a float value with implied integer bit,
502              we will only be putting 31 of those 32 bits into the
503              final value due to the discarding of the top bit.  In the 
504              case of a small float value where the number of mantissa 
505              bits is less than 32, discarding the top bit does not alter
506              the number of bits we will be adding to the result.  */
507           if (mant_bits == 32)
508             mant_bits -= 1;
509         }
510
511       if (mant_bits < 32)
512         {
513           /* The bits we want are in the most significant MANT_BITS bits of
514              mant_long.  Move them to the least significant.  */
515           mant_long >>= 32 - mant_bits;
516         }
517
518       put_field (uto, order, fmt->totalsize,
519                  mant_off, mant_bits, mant_long);
520       mant_off += mant_bits;
521       mant_bits_left -= mant_bits;
522     }
523
524  finalize_byteorder:
525   /* Do we need to byte-swap the words in the result?  */
526   if (order != fmt->byteorder)
527     floatformat_normalize_byteorder (fmt, newto, to);
528 }
529
530 /* Check if VAL (which is assumed to be a floating point number whose
531    format is described by FMT) is negative.  */
532
533 int
534 floatformat_is_negative (const struct floatformat *fmt,
535                          const bfd_byte *uval)
536 {
537   enum floatformat_byteorders order;
538   unsigned char newfrom[FLOATFORMAT_LARGEST_BYTES];
539   
540   gdb_assert (fmt != NULL);
541   gdb_assert (fmt->totalsize
542               <= FLOATFORMAT_LARGEST_BYTES * FLOATFORMAT_CHAR_BIT);
543
544   order = floatformat_normalize_byteorder (fmt, uval, newfrom);
545
546   if (order != fmt->byteorder)
547     uval = newfrom;
548
549   return get_field (uval, order, fmt->totalsize, fmt->sign_start, 1);
550 }
551
552 /* Check if VAL is "not a number" (NaN) for FMT.  */
553
554 enum float_kind
555 floatformat_classify (const struct floatformat *fmt,
556                       const bfd_byte *uval)
557 {
558   long exponent;
559   unsigned long mant;
560   unsigned int mant_bits, mant_off;
561   int mant_bits_left;
562   enum floatformat_byteorders order;
563   unsigned char newfrom[FLOATFORMAT_LARGEST_BYTES];
564   int mant_zero;
565   
566   gdb_assert (fmt != NULL);
567   gdb_assert (fmt->totalsize
568               <= FLOATFORMAT_LARGEST_BYTES * FLOATFORMAT_CHAR_BIT);
569
570   order = floatformat_normalize_byteorder (fmt, uval, newfrom);
571
572   if (order != fmt->byteorder)
573     uval = newfrom;
574
575   exponent = get_field (uval, order, fmt->totalsize, fmt->exp_start,
576                         fmt->exp_len);
577
578   mant_bits_left = fmt->man_len;
579   mant_off = fmt->man_start;
580
581   mant_zero = 1;
582   while (mant_bits_left > 0)
583     {
584       mant_bits = min (mant_bits_left, 32);
585
586       mant = get_field (uval, order, fmt->totalsize, mant_off, mant_bits);
587
588       /* If there is an explicit integer bit, mask it off.  */
589       if (mant_off == fmt->man_start
590           && fmt->intbit == floatformat_intbit_yes)
591         mant &= ~(1 << (mant_bits - 1));
592
593       if (mant)
594         {
595           mant_zero = 0;
596           break;
597         }
598
599       mant_off += mant_bits;
600       mant_bits_left -= mant_bits;
601     }
602
603   /* If exp_nan is not set, assume that inf, NaN, and subnormals are not
604      supported.  */
605   if (! fmt->exp_nan)
606     {
607       if (mant_zero)
608         return float_zero;
609       else
610         return float_normal;
611     }
612
613   if (exponent == 0 && !mant_zero)
614     return float_subnormal;
615
616   if (exponent == fmt->exp_nan)
617     {
618       if (mant_zero)
619         return float_infinite;
620       else
621         return float_nan;
622     }
623
624   if (mant_zero)
625     return float_zero;
626
627   return float_normal;
628 }
629
630 /* Convert the mantissa of VAL (which is assumed to be a floating
631    point number whose format is described by FMT) into a hexadecimal
632    and store it in a static string.  Return a pointer to that string.  */
633
634 const char *
635 floatformat_mantissa (const struct floatformat *fmt,
636                       const bfd_byte *val)
637 {
638   unsigned char *uval = (unsigned char *) val;
639   unsigned long mant;
640   unsigned int mant_bits, mant_off;
641   int mant_bits_left;
642   static char res[50];
643   char buf[9];
644   int len;
645   enum floatformat_byteorders order;
646   unsigned char newfrom[FLOATFORMAT_LARGEST_BYTES];
647   
648   gdb_assert (fmt != NULL);
649   gdb_assert (fmt->totalsize
650               <= FLOATFORMAT_LARGEST_BYTES * FLOATFORMAT_CHAR_BIT);
651
652   order = floatformat_normalize_byteorder (fmt, uval, newfrom);
653
654   if (order != fmt->byteorder)
655     uval = newfrom;
656
657   if (! fmt->exp_nan)
658     return 0;
659
660   /* Make sure we have enough room to store the mantissa.  */
661   gdb_assert (sizeof res > ((fmt->man_len + 7) / 8) * 2);
662
663   mant_off = fmt->man_start;
664   mant_bits_left = fmt->man_len;
665   mant_bits = (mant_bits_left % 32) > 0 ? mant_bits_left % 32 : 32;
666
667   mant = get_field (uval, order, fmt->totalsize, mant_off, mant_bits);
668
669   len = xsnprintf (res, sizeof res, "%lx", mant);
670
671   mant_off += mant_bits;
672   mant_bits_left -= mant_bits;
673
674   while (mant_bits_left > 0)
675     {
676       mant = get_field (uval, order, fmt->totalsize, mant_off, 32);
677
678       xsnprintf (buf, sizeof buf, "%08lx", mant);
679       gdb_assert (len + strlen (buf) <= sizeof res);
680       strcat (res, buf);
681
682       mant_off += 32;
683       mant_bits_left -= 32;
684     }
685
686   return res;
687 }
688
689 \f
690 /* Convert TO/FROM target to the hosts DOUBLEST floating-point format.
691
692    If the host and target formats agree, we just copy the raw data
693    into the appropriate type of variable and return, letting the host
694    increase precision as necessary.  Otherwise, we call the conversion
695    routine and let it do the dirty work.  */
696
697 static const struct floatformat *host_float_format = GDB_HOST_FLOAT_FORMAT;
698 static const struct floatformat *host_double_format = GDB_HOST_DOUBLE_FORMAT;
699 static const struct floatformat *host_long_double_format
700   = GDB_HOST_LONG_DOUBLE_FORMAT;
701
702 void
703 floatformat_to_doublest (const struct floatformat *fmt,
704                          const void *in, DOUBLEST *out)
705 {
706   gdb_assert (fmt != NULL);
707   if (fmt == host_float_format)
708     {
709       float val;
710
711       memcpy (&val, in, sizeof (val));
712       *out = val;
713     }
714   else if (fmt == host_double_format)
715     {
716       double val;
717
718       memcpy (&val, in, sizeof (val));
719       *out = val;
720     }
721   else if (fmt == host_long_double_format)
722     {
723       long double val;
724
725       memcpy (&val, in, sizeof (val));
726       *out = val;
727     }
728   else
729     convert_floatformat_to_doublest (fmt, in, out);
730 }
731
732 void
733 floatformat_from_doublest (const struct floatformat *fmt,
734                            const DOUBLEST *in, void *out)
735 {
736   gdb_assert (fmt != NULL);
737   if (fmt == host_float_format)
738     {
739       float val = *in;
740
741       memcpy (out, &val, sizeof (val));
742     }
743   else if (fmt == host_double_format)
744     {
745       double val = *in;
746
747       memcpy (out, &val, sizeof (val));
748     }
749   else if (fmt == host_long_double_format)
750     {
751       long double val = *in;
752
753       memcpy (out, &val, sizeof (val));
754     }
755   else
756     convert_doublest_to_floatformat (fmt, in, out);
757 }
758
759 \f
760 /* Return a floating-point format for a floating-point variable of
761    length LEN.  If no suitable floating-point format is found, an
762    error is thrown.
763
764    We need this functionality since information about the
765    floating-point format of a type is not always available to GDB; the
766    debug information typically only tells us the size of a
767    floating-point type.
768
769    FIXME: kettenis/2001-10-28: In many places, particularly in
770    target-dependent code, the format of floating-point types is known,
771    but not passed on by GDB.  This should be fixed.  */
772
773 static const struct floatformat *
774 floatformat_from_length (struct gdbarch *gdbarch, int len)
775 {
776   const struct floatformat *format;
777
778   if (len * TARGET_CHAR_BIT == gdbarch_half_bit (gdbarch))
779     format = gdbarch_half_format (gdbarch)
780                [gdbarch_byte_order (gdbarch)];
781   else if (len * TARGET_CHAR_BIT == gdbarch_float_bit (gdbarch))
782     format = gdbarch_float_format (gdbarch)
783                [gdbarch_byte_order (gdbarch)];
784   else if (len * TARGET_CHAR_BIT == gdbarch_double_bit (gdbarch))
785     format = gdbarch_double_format (gdbarch)
786                [gdbarch_byte_order (gdbarch)];
787   else if (len * TARGET_CHAR_BIT == gdbarch_long_double_bit (gdbarch))
788     format = gdbarch_long_double_format (gdbarch)
789                [gdbarch_byte_order (gdbarch)];
790   /* On i386 the 'long double' type takes 96 bits,
791      while the real number of used bits is only 80,
792      both in processor and in memory.
793      The code below accepts the real bit size.  */ 
794   else if ((gdbarch_long_double_format (gdbarch) != NULL)
795            && (len * TARGET_CHAR_BIT
796                == gdbarch_long_double_format (gdbarch)[0]->totalsize))
797     format = gdbarch_long_double_format (gdbarch)
798                [gdbarch_byte_order (gdbarch)];
799   else
800     format = NULL;
801   if (format == NULL)
802     error (_("Unrecognized %d-bit floating-point type."),
803            len * TARGET_CHAR_BIT);
804   return format;
805 }
806
807 const struct floatformat *
808 floatformat_from_type (const struct type *type)
809 {
810   struct gdbarch *gdbarch = get_type_arch (type);
811
812   gdb_assert (TYPE_CODE (type) == TYPE_CODE_FLT);
813   if (TYPE_FLOATFORMAT (type) != NULL)
814     return TYPE_FLOATFORMAT (type)[gdbarch_byte_order (gdbarch)];
815   else
816     return floatformat_from_length (gdbarch, TYPE_LENGTH (type));
817 }
818
819 /* Extract a floating-point number of type TYPE from a target-order
820    byte-stream at ADDR.  Returns the value as type DOUBLEST.  */
821
822 DOUBLEST
823 extract_typed_floating (const void *addr, const struct type *type)
824 {
825   const struct floatformat *fmt = floatformat_from_type (type);
826   DOUBLEST retval;
827
828   floatformat_to_doublest (fmt, addr, &retval);
829   return retval;
830 }
831
832 /* Store VAL as a floating-point number of type TYPE to a target-order
833    byte-stream at ADDR.  */
834
835 void
836 store_typed_floating (void *addr, const struct type *type, DOUBLEST val)
837 {
838   const struct floatformat *fmt = floatformat_from_type (type);
839
840   /* FIXME: kettenis/2001-10-28: It is debatable whether we should
841      zero out any remaining bytes in the target buffer when TYPE is
842      longer than the actual underlying floating-point format.  Perhaps
843      we should store a fixed bitpattern in those remaining bytes,
844      instead of zero, or perhaps we shouldn't touch those remaining
845      bytes at all.
846
847      NOTE: cagney/2001-10-28: With the way things currently work, it
848      isn't a good idea to leave the end bits undefined.  This is
849      because GDB writes out the entire sizeof(<floating>) bits of the
850      floating-point type even though the value might only be stored
851      in, and the target processor may only refer to, the first N <
852      TYPE_LENGTH (type) bits.  If the end of the buffer wasn't
853      initialized, GDB would write undefined data to the target.  An
854      errant program, refering to that undefined data, would then
855      become non-deterministic.
856
857      See also the function convert_typed_floating below.  */
858   memset (addr, 0, TYPE_LENGTH (type));
859
860   floatformat_from_doublest (fmt, &val, addr);
861 }
862
863 /* Convert a floating-point number of type FROM_TYPE from a
864    target-order byte-stream at FROM to a floating-point number of type
865    TO_TYPE, and store it to a target-order byte-stream at TO.  */
866
867 void
868 convert_typed_floating (const void *from, const struct type *from_type,
869                         void *to, const struct type *to_type)
870 {
871   const struct floatformat *from_fmt = floatformat_from_type (from_type);
872   const struct floatformat *to_fmt = floatformat_from_type (to_type);
873
874   if (from_fmt == NULL || to_fmt == NULL)
875     {
876       /* If we don't know the floating-point format of FROM_TYPE or
877          TO_TYPE, there's not much we can do.  We might make the
878          assumption that if the length of FROM_TYPE and TO_TYPE match,
879          their floating-point format would match too, but that
880          assumption might be wrong on targets that support
881          floating-point types that only differ in endianness for
882          example.  So we warn instead, and zero out the target buffer.  */
883       warning (_("Can't convert floating-point number to desired type."));
884       memset (to, 0, TYPE_LENGTH (to_type));
885     }
886   else if (from_fmt == to_fmt)
887     {
888       /* We're in business.  The floating-point format of FROM_TYPE
889          and TO_TYPE match.  However, even though the floating-point
890          format matches, the length of the type might still be
891          different.  Make sure we don't overrun any buffers.  See
892          comment in store_typed_floating for a discussion about
893          zeroing out remaining bytes in the target buffer.  */
894       memset (to, 0, TYPE_LENGTH (to_type));
895       memcpy (to, from, min (TYPE_LENGTH (from_type), TYPE_LENGTH (to_type)));
896     }
897   else
898     {
899       /* The floating-point types don't match.  The best we can do
900          (apart from simulating the target FPU) is converting to the
901          widest floating-point type supported by the host, and then
902          again to the desired type.  */
903       DOUBLEST d;
904
905       floatformat_to_doublest (from_fmt, from, &d);
906       floatformat_from_doublest (to_fmt, &d, to);
907     }
908 }
909
910 const struct floatformat *floatformat_ieee_single[BFD_ENDIAN_UNKNOWN];
911 const struct floatformat *floatformat_ieee_double[BFD_ENDIAN_UNKNOWN];
912 const struct floatformat *floatformat_ieee_quad[BFD_ENDIAN_UNKNOWN];
913 const struct floatformat *floatformat_arm_ext[BFD_ENDIAN_UNKNOWN];
914 const struct floatformat *floatformat_ia64_spill[BFD_ENDIAN_UNKNOWN];
915
916 extern void _initialize_doublest (void);
917
918 extern void
919 _initialize_doublest (void)
920 {
921   floatformat_ieee_single[BFD_ENDIAN_LITTLE] = &floatformat_ieee_single_little;
922   floatformat_ieee_single[BFD_ENDIAN_BIG] = &floatformat_ieee_single_big;
923   floatformat_ieee_double[BFD_ENDIAN_LITTLE] = &floatformat_ieee_double_little;
924   floatformat_ieee_double[BFD_ENDIAN_BIG] = &floatformat_ieee_double_big;
925   floatformat_arm_ext[BFD_ENDIAN_LITTLE]
926     = &floatformat_arm_ext_littlebyte_bigword;
927   floatformat_arm_ext[BFD_ENDIAN_BIG] = &floatformat_arm_ext_big;
928   floatformat_ia64_spill[BFD_ENDIAN_LITTLE] = &floatformat_ia64_spill_little;
929   floatformat_ia64_spill[BFD_ENDIAN_BIG] = &floatformat_ia64_spill_big;
930   floatformat_ieee_quad[BFD_ENDIAN_LITTLE] = &floatformat_ia64_quad_little;
931   floatformat_ieee_quad[BFD_ENDIAN_BIG] = &floatformat_ia64_quad_big;
932 }