Unconditionally include stdlib.h.
[libfirm] / ir / tv / fltcalc.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief    tarval floating point calculations
23  * @date     2003
24  * @author   Mathias Heil
25  * @version  $Id$
26  */
27
28 #include "config.h"
29
30 #include "fltcalc.h"
31 #include "strcalc.h"
32
33 #include <math.h>    /* need isnan() and isinf() (will be changed)*/
34 /* undef some reused constants defined by math.h */
35 #ifdef NAN
36 #  undef NAN
37 #endif
38
39 #ifdef HAVE_INTTYPES_H
40 # include <inttypes.h>
41 #endif
42 #ifdef HAVE_STRING_H
43 # include <string.h>
44 #endif
45 #include <stdlib.h>
46 #include <stdio.h>
47 #include <assert.h>
48
49 #include "xmalloc.h"
50
51 /** The number of extra precision rounding bits */
52 #define ROUNDING_BITS 2
53
54 typedef uint32_t UINT32;
55
56 #ifdef HAVE_LONG_DOUBLE
57 #ifdef WORDS_BIGENDIAN
58 typedef union {
59         struct {
60                 UINT32 high;
61                 UINT32 mid;
62                 UINT32 low;
63         } val;
64         volatile long double d;
65 } value_t;
66 #else
67 typedef union {
68         struct {
69                 UINT32 low;
70                 UINT32 mid;
71                 UINT32 high;
72         } val;
73         volatile long double d;
74 } value_t;
75 #endif
76 #else
77 #ifdef WORDS_BIGENDIAN
78 typedef union {
79         struct {
80                 UINT32 high;
81                 UINT32 low;
82         } val;
83         volatile double d;
84 } value_t;
85 #else
86 typedef union {
87         struct {
88                 UINT32 low;
89                 UINT32 high;
90         } val;
91         volatile double d;
92 } value_t;
93 #endif
94 #endif
95
96 #define CLEAR_BUFFER(buffer) memset(buffer, 0, calc_buffer_size)
97
98 /* our floating point value */
99 struct _fp_value {
100         ieee_descriptor_t desc;
101         char sign;
102         char value[1];                  /* exp[value_size] + mant[value_size] */
103 };
104
105 #define _exp(a)  &((a)->value[0])
106 #define _mant(a) &((a)->value[value_size])
107
108 #define _save_result(x) memcpy((x), sc_get_buffer(), value_size)
109 #define _shift_right(x, y, res) sc_shr((x), (y), value_size*4, 0, (res))
110 #define _shift_left(x, y, res) sc_shl((x), (y), value_size*4, 0, (res))
111
112
113 #ifdef FLTCALC_DEBUG
114 #  define DEBUGPRINTF(x) printf x
115 #else
116 #  define DEBUGPRINTF(x) ((void)0)
117 #endif
118
119 #ifdef FLTCALC_TRACE_CALC
120 #  define TRACEPRINTF(x) printf x
121 #else
122 #  define TRACEPRINTF(x) ((void)0)
123 #endif
124
125 /** The immediate precision. */
126 static unsigned immediate_prec = 0;
127
128 /** A temporal buffer. */
129 static fp_value *calc_buffer = NULL;
130
131 /** Current rounding mode.*/
132 static fc_rounding_mode_t rounding_mode;
133
134 static int calc_buffer_size;
135 static int value_size;
136 static int max_precision;
137
138 /** Exact flag. */
139 static int fc_exact = 1;
140
141 #if 0
142 static void fail_char(const char *str, unsigned int len, int pos) {
143         if (*(str+pos))
144                 printf("ERROR: Unexpected character '%c'\n", *(str + pos));
145         else
146                 printf("ERROR: Unexpected end of string\n");
147         while (len-- && *str) printf("%c", *str++); printf("\n");
148         while (pos--) printf(" "); printf("^\n");
149         /* the front end has to to check constant strings */
150         exit(-1);
151 }
152 #endif
153
154 /** pack machine-like */
155 static void *pack(const fp_value *int_float, void *packed) {
156         char     *shift_val;
157         char     *temp;
158         fp_value *val_buffer;
159         int      pos;
160
161         temp      = alloca(value_size);
162         shift_val = alloca(value_size);
163
164         switch ((value_class_t)int_float->desc.clss) {
165         case NAN:
166                 val_buffer = alloca(calc_buffer_size);
167                 fc_get_qnan(&int_float->desc, val_buffer);
168                 int_float = val_buffer;
169                 break;
170
171         case INF:
172                 val_buffer = alloca(calc_buffer_size);
173                 fc_get_plusinf(&int_float->desc, val_buffer);
174                 val_buffer->sign = int_float->sign;
175                 int_float = val_buffer;
176                 break;
177
178         default:
179                 break;
180         }
181         assert(int_float->desc.explicit_one <= 1);
182
183         /* pack sign: move it to the left after exponent AND mantissa */
184         sc_val_from_ulong(int_float->sign, temp);
185
186         pos = int_float->desc.exponent_size + int_float->desc.mantissa_size + int_float->desc.explicit_one;
187         sc_val_from_ulong(pos, NULL);
188         _shift_left(temp, sc_get_buffer(), packed);
189
190         /* pack exponent: move it to the left after mantissa */
191         pos = int_float->desc.mantissa_size + int_float->desc.explicit_one;
192         sc_val_from_ulong(pos, shift_val);
193         _shift_left(_exp(int_float), shift_val, temp);
194
195         /* combine sign|exponent */
196         sc_or(temp, packed, packed);
197
198         /* extract mantissa */
199         /* remove rounding bits */
200         sc_val_from_ulong(ROUNDING_BITS, shift_val);
201         _shift_right(_mant(int_float), shift_val, temp);
202
203         /* remove leading 1 (or 0 if denormalized) */
204         sc_max_from_bits(pos, 0, shift_val); /* all mantissa bits are 1's */
205         sc_and(temp, shift_val, temp);
206
207         /* combine sign|exponent|mantissa */
208         sc_or(temp, packed, packed);
209
210         return packed;
211 }
212
213 /**
214  * Normalize a fp_value.
215  *
216  * @return non-zero if result is exact
217  */
218 static int normalize(const fp_value *in_val, fp_value *out_val, int sticky) {
219         int exact = 1;
220         int hsb;
221         char lsb, guard, round, round_dir = 0;
222         char *temp = alloca(value_size);
223
224         /* save rounding bits at the end */
225         hsb = ROUNDING_BITS + in_val->desc.mantissa_size - sc_get_highest_set_bit(_mant(in_val)) - 1;
226
227         if (in_val != out_val)   {
228                 out_val->sign = in_val->sign;
229                 memcpy(&out_val->desc, &in_val->desc, sizeof(out_val->desc));
230         }
231
232         out_val->desc.clss = NORMAL;
233
234         /* mantissa all zeros, so zero exponent (because of explicit one) */
235         if (hsb == ROUNDING_BITS + in_val->desc.mantissa_size)   {
236                 sc_val_from_ulong(0, _exp(out_val));
237                 hsb = -1;
238         }
239
240         /* shift the first 1 into the left of the radix point (i.e. hsb == -1) */
241         if (hsb < -1)   {
242                 /* shift right */
243                 sc_val_from_ulong(-hsb-1, temp);
244
245                 _shift_right(_mant(in_val), temp, _mant(out_val));
246
247                 /* remember if some bits were shifted away */
248                 if (sc_had_carry()) {
249                         exact = 0;
250                         sticky = 1;
251                 }
252                 sc_add(_exp(in_val), temp, _exp(out_val));
253         } else if (hsb > -1) {
254                 /* shift left */
255                 sc_val_from_ulong(hsb+1, temp);
256
257                 _shift_left(_mant(in_val), temp, _mant(out_val));
258
259                 sc_sub(_exp(in_val), temp, _exp(out_val));
260         }
261
262         /* check for exponent underflow */
263         if (sc_is_negative(_exp(out_val)) || sc_is_zero(_exp(out_val))) {
264                 DEBUGPRINTF(("Exponent underflow!\n"));
265                 /* exponent underflow */
266                 /* shift the mantissa right to have a zero exponent */
267                 sc_val_from_ulong(1, temp);
268                 sc_sub(temp, _exp(out_val), NULL);
269
270                 _shift_right(_mant(out_val), sc_get_buffer(), _mant(out_val));
271                 if (sc_had_carry()) {
272                         exact  = 0;
273                         sticky = 1;
274                 }
275                 /* denormalized means exponent of zero */
276                 sc_val_from_ulong(0, _exp(out_val));
277
278                 out_val->desc.clss = SUBNORMAL;
279         }
280
281         /* perform rounding by adding a value that clears the guard bit and the round bit
282          * and either causes a carry to round up or not */
283         /* get the last 3 bits of the value */
284         lsb = sc_sub_bits(_mant(out_val), out_val->desc.mantissa_size + ROUNDING_BITS, 0) & 0x7;
285         guard = (lsb&0x2)>>1;
286         round = lsb&0x1;
287
288         switch (rounding_mode) {
289         case FC_TONEAREST:
290                 /* round to nearest representable value, if in doubt choose the version
291                  * with lsb == 0 */
292                 round_dir = guard && (sticky || round || lsb>>2);
293                 break;
294         case FC_TOPOSITIVE:
295                 /* if positive: round to one if the exact value is bigger, else to zero */
296                 round_dir = (!out_val->sign && (guard || round || sticky));
297                 break;
298         case FC_TONEGATIVE:
299                 /* if negative: round to one if the exact value is bigger, else to zero */
300                 round_dir = (out_val->sign && (guard || round || sticky));
301                 break;
302         case FC_TOZERO:
303                 /* always round to 0 (chopping mode) */
304                 round_dir = 0;
305                 break;
306         }
307         DEBUGPRINTF(("Rounding (s%d, l%d, g%d, r%d, s%d) %s\n", out_val->sign, lsb>>2, guard, round, sticky, (round_dir)?"up":"down"));
308
309         if (round_dir == 1) {
310                 guard = (round^guard)<<1;
311                 lsb = !(round || guard)<<2 | guard | round;
312         } else {
313                 lsb = -((guard<<1) | round);
314         }
315
316         /* add the rounded value */
317         if (lsb != 0) {
318                 sc_val_from_long(lsb, temp);
319                 sc_add(_mant(out_val), temp, _mant(out_val));
320                 exact = 0;
321         }
322
323         /* could have rounded down to zero */
324         if (sc_is_zero(_mant(out_val)) && (out_val->desc.clss == SUBNORMAL))
325                 out_val->desc.clss = ZERO;
326
327         /* check for rounding overflow */
328         hsb = ROUNDING_BITS + out_val->desc.mantissa_size - sc_get_highest_set_bit(_mant(out_val)) - 1;
329         if ((out_val->desc.clss != SUBNORMAL) && (hsb < -1)) {
330                 sc_val_from_ulong(1, temp);
331                 _shift_right(_mant(out_val), temp, _mant(out_val));
332                 if (exact && sc_had_carry())
333                         exact = 0;
334                 sc_add(_exp(out_val), temp, _exp(out_val));
335         } else if ((out_val->desc.clss == SUBNORMAL) && (hsb == -1)) {
336                 /* overflow caused the mantissa to be normal again,
337                  * so adapt the exponent accordingly */
338                 sc_val_from_ulong(1, temp);
339                 sc_add(_exp(out_val), temp, _exp(out_val));
340
341                 out_val->desc.clss = NORMAL;
342         }
343         /* no further rounding is needed, because rounding overflow means
344          * the carry of the original rounding was propagated all the way
345          * up to the bit left of the radix point. This implies the bits
346          * to the right are all zeros (rounding is +1) */
347
348         /* check for exponent overflow */
349         sc_val_from_ulong((1 << out_val->desc.exponent_size) - 1, temp);
350         if (sc_comp(_exp(out_val), temp) != -1) {
351                 DEBUGPRINTF(("Exponent overflow!\n"));
352                 /* exponent overflow, reaction depends on rounding method:
353                  *
354                  * mode        | sign of value |  result
355                  *--------------------------------------------------------------
356                  * TO_NEAREST  |      +        |   +inf
357                  *             |      -        |   -inf
358                  *--------------------------------------------------------------
359                  * TO_POSITIVE |      +        |   +inf
360                  *             |      -        |   smallest representable value
361                  *--------------------------------------------------------------
362                  * TO_NEAGTIVE |      +        |   largest representable value
363                  *             |      -        |   -inf
364                  *--------------------------------------------------------------
365                  * TO_ZERO     |      +        |   largest representable value
366                  *             |      -        |   smallest representable value
367                  *--------------------------------------------------------------*/
368                 if (out_val->sign == 0) {
369                         /* value is positive */
370                         switch (rounding_mode) {
371                         case FC_TONEAREST:
372                         case FC_TOPOSITIVE:
373                                 out_val->desc.clss = INF;
374                                 break;
375
376                         case FC_TONEGATIVE:
377                         case FC_TOZERO:
378                                 fc_get_max(&out_val->desc, out_val);
379                         }
380                 } else {
381                         /* value is negative */
382                         switch (rounding_mode) {
383                         case FC_TONEAREST:
384                         case FC_TONEGATIVE:
385                                 out_val->desc.clss = INF;
386                                 break;
387
388                         case FC_TOPOSITIVE:
389                         case FC_TOZERO:
390                                 fc_get_min(&out_val->desc, out_val);
391                         }
392                 }
393         }
394         return exact;
395 }
396
397 /**
398  * Operations involving NaN's must return NaN.
399  * They are NOT exact.
400  */
401 #define handle_NAN(a, b, result) \
402 do {                                                      \
403   if (a->desc.clss == NAN) {                              \
404     if (a != result) memcpy(result, a, calc_buffer_size); \
405     fc_exact = 0;                                         \
406     return;                                               \
407   }                                                       \
408   if (b->desc.clss == NAN) {                              \
409     if (b != result) memcpy(result, b, calc_buffer_size); \
410     fc_exact = 0;                                         \
411     return;                                               \
412   }                                                       \
413 }while (0)
414
415
416 /**
417  * calculate a + b, where a is the value with the bigger exponent
418  */
419 static void _fadd(const fp_value *a, const fp_value *b, fp_value *result) {
420         char *temp;
421         char *exp_diff;
422
423         char sign, res_sign;
424         char sticky;
425
426         fc_exact = 1;
427
428         handle_NAN(a, b, result);
429
430         /* make sure result has a descriptor */
431         if (result != a && result != b)
432                 result->desc = a->desc;
433
434         /* determine if this is an addition or subtraction */
435         sign = a->sign ^ b->sign;
436
437         /* produce NaN on inf - inf */
438         if (sign && (a->desc.clss == INF) && (b->desc.clss == INF)) {
439                 fc_exact = 0;
440                 fc_get_qnan(&a->desc, result);
441                 return;
442         }
443
444         temp     = alloca(value_size);
445         exp_diff = alloca(value_size);
446
447         /* get exponent difference */
448         sc_sub(_exp(a), _exp(b), exp_diff);
449
450         /* initially set sign to be the sign of a, special treatment of subtraction
451          * when exponents are equal is required though.
452          * Also special care about the sign is needed when the mantissas are equal
453          * (+/- 0 ?) */
454         if (sign && sc_val_to_long(exp_diff) == 0) {
455                 switch (sc_comp(_mant(a), _mant(b))) {
456                 case 1:  /* a > b */
457                         res_sign = a->sign;  /* abs(a) is bigger and a is negative */
458                         break;
459                 case 0:  /* a == b */
460                         res_sign = (rounding_mode == FC_TONEGATIVE);
461                         break;
462                 case -1: /* a < b */
463                         res_sign = b->sign; /* abs(b) is bigger and b is negative */
464                         break;
465                 default:
466                         /* can't be reached */
467                         res_sign = 0;
468                         break;
469                 }
470         }
471         else
472                 res_sign = a->sign;
473         result->sign = res_sign;
474
475         /* sign has been taken care of, check for special cases */
476         if (a->desc.clss == ZERO || b->desc.clss == INF) {
477                 if (b != result)
478                         memcpy(result, b, calc_buffer_size);
479                 fc_exact = b->desc.clss == NORMAL;
480                 result->sign = res_sign;
481                 return;
482         }
483         if (b->desc.clss == ZERO || a->desc.clss == INF) {
484                 if (a != result)
485                         memcpy(result, a, calc_buffer_size);
486                 fc_exact = a->desc.clss == NORMAL;
487                 result->sign = res_sign;
488                 return;
489         }
490
491         /* shift the smaller value to the right to align the radix point */
492         /* subnormals have their radix point shifted to the right,
493          * take care of this first */
494         if ((b->desc.clss == SUBNORMAL) && (a->desc.clss != SUBNORMAL)) {
495                 sc_val_from_ulong(1, temp);
496                 sc_sub(exp_diff, temp, exp_diff);
497         }
498
499         _shift_right(_mant(b), exp_diff, temp);
500         sticky = sc_had_carry();
501         fc_exact &= !sticky;
502
503         if (sticky && sign) {
504                 /* if subtracting a little more than the represented value or adding a little
505                  * more than the represented value to a negative value this, in addition to the
506                  * still set sticky bit, takes account of the 'little more' */
507                 char *temp1 = alloca(calc_buffer_size);
508                 sc_val_from_ulong(1, temp1);
509                 sc_add(temp, temp1, temp);
510         }
511
512         if (sign) {
513                 if (sc_comp(_mant(a), temp) == -1)
514                         sc_sub(temp, _mant(a), _mant(result));
515                 else
516                         sc_sub(_mant(a), temp, _mant(result));
517         } else {
518                 sc_add(_mant(a), temp, _mant(result));
519         }
520
521         /* _normalize expects a 'normal' radix point, adding two subnormals
522          * results in a subnormal radix point -> shifting before normalizing */
523         if ((a->desc.clss == SUBNORMAL) && (b->desc.clss == SUBNORMAL)) {
524                 sc_val_from_ulong(1, NULL);
525                 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
526         }
527
528         /* resulting exponent is the bigger one */
529         memmove(_exp(result), _exp(a), value_size);
530
531         fc_exact &= normalize(result, result, sticky);
532 }
533
534 /**
535  * calculate a * b
536  */
537 static void _fmul(const fp_value *a, const fp_value *b, fp_value *result) {
538         int sticky;
539         char *temp;
540         char res_sign;
541
542         fc_exact = 1;
543
544         handle_NAN(a, b, result);
545
546         temp = alloca(value_size);
547
548         if (result != a && result != b)
549                 result->desc = a->desc;
550
551         result->sign = res_sign = a->sign ^ b->sign;
552
553         /* produce NaN on 0 * inf */
554         if (a->desc.clss == ZERO) {
555                 if (b->desc.clss == INF) {
556                         fc_get_qnan(&a->desc, result);
557                         fc_exact = 0;
558                 } else {
559                         if (a != result)
560                                 memcpy(result, a, calc_buffer_size);
561                         result->sign = res_sign;
562                 }
563                 return;
564         }
565         if (b->desc.clss == ZERO) {
566                 if (a->desc.clss == INF) {
567                         fc_get_qnan(&a->desc, result);
568                         fc_exact = 0;
569                 } else {
570                         if (b != result)
571                                 memcpy(result, b, calc_buffer_size);
572                         result->sign = res_sign;
573                 }
574                 return;
575         }
576
577         if (a->desc.clss == INF) {
578                 fc_exact = 0;
579                 if (a != result)
580                         memcpy(result, a, calc_buffer_size);
581                 result->sign = res_sign;
582                 return;
583         }
584         if (b->desc.clss == INF) {
585                 fc_exact = 0;
586                 if (b != result)
587                         memcpy(result, b, calc_buffer_size);
588                 result->sign = res_sign;
589                 return;
590         }
591
592         /* exp = exp(a) + exp(b) - excess */
593         sc_add(_exp(a), _exp(b), _exp(result));
594
595         sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 1, temp);
596         sc_sub(_exp(result), temp, _exp(result));
597
598         /* mixed normal, subnormal values introduce an error of 1, correct it */
599         if ((a->desc.clss == SUBNORMAL) ^ (b->desc.clss == SUBNORMAL)) {
600                 sc_val_from_ulong(1, temp);
601                 sc_add(_exp(result), temp, _exp(result));
602         }
603
604         sc_mul(_mant(a), _mant(b), _mant(result));
605
606         /* realign result: after a multiplication the digits right of the radix
607          * point are the sum of the factors' digits after the radix point. As all
608          * values are normalized they both have the same amount of these digits,
609          * which has to be restored by proper shifting
610          * because of the rounding bits */
611         sc_val_from_ulong(ROUNDING_BITS + result->desc.mantissa_size, temp);
612
613         _shift_right(_mant(result), temp, _mant(result));
614         sticky = sc_had_carry();
615         fc_exact &= !sticky;
616
617         fc_exact &= normalize(result, result, sticky);
618 }
619
620 /**
621  * calculate a / b
622  */
623 static void _fdiv(const fp_value *a, const fp_value *b, fp_value *result) {
624         int sticky;
625         char *temp, *dividend;
626         char res_sign;
627
628         fc_exact = 1;
629
630         handle_NAN(a, b, result);
631
632         temp = alloca(value_size);
633         dividend = alloca(value_size);
634
635         if (result != a && result != b)
636                 result->desc = a->desc;
637
638         result->sign = res_sign = a->sign ^ b->sign;
639
640         /* produce NAN on 0/0 and inf/inf */
641         if (a->desc.clss == ZERO) {
642                 if (b->desc.clss == ZERO) {
643                         /* 0/0 -> NaN */
644                         fc_get_qnan(&a->desc, result);
645                         fc_exact = 0;
646                 } else {
647                         /* 0/x -> a */
648                         if (a != result)
649                                 memcpy(result, a, calc_buffer_size);
650                         result->sign = res_sign;
651                 }
652                 return;
653         }
654
655         if (b->desc.clss == INF) {
656                 fc_exact = 0;
657                 if (a->desc.clss == INF) {
658                         /* inf/inf -> NaN */
659                         fc_get_qnan(&a->desc, result);
660                 } else {
661                         /* x/inf -> 0 */
662                         sc_val_from_ulong(0, NULL);
663                         _save_result(_exp(result));
664                         _save_result(_mant(result));
665                         result->desc.clss = ZERO;
666                 }
667                 return;
668         }
669
670         if (a->desc.clss == INF) {
671                 fc_exact = 0;
672                 /* inf/x -> inf */
673                 if (a != result)
674                         memcpy(result, a, calc_buffer_size);
675                 result->sign = res_sign;
676                 return;
677         }
678         if (b->desc.clss == ZERO) {
679                 fc_exact = 0;
680                 /* division by zero */
681                 if (result->sign)
682                         fc_get_minusinf(&a->desc, result);
683                 else
684                         fc_get_plusinf(&a->desc, result);
685                 return;
686         }
687
688         /* exp = exp(a) - exp(b) + excess - 1*/
689         sc_sub(_exp(a), _exp(b), _exp(result));
690         sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 2, temp);
691         sc_add(_exp(result), temp, _exp(result));
692
693         /* mixed normal, subnormal values introduce an error of 1, correct it */
694         if ((a->desc.clss == SUBNORMAL) ^ (b->desc.clss == SUBNORMAL)) {
695                 sc_val_from_ulong(1, temp);
696                 sc_add(_exp(result), temp, _exp(result));
697         }
698
699         /* mant(res) = mant(a) / 1/2mant(b) */
700         /* to gain more bits of precision in the result the dividend could be
701          * shifted left, as this operation does not loose bits. This would not
702          * fit into the integer precision, but due to the rounding bits (which
703          * are always zero because the values are all normalized) the divisor
704          * can be shifted right instead to achieve the same result */
705         sc_val_from_ulong(ROUNDING_BITS + result->desc.mantissa_size, temp);
706
707         _shift_left(_mant(a), temp, dividend);
708
709         {
710                 char *divisor = alloca(calc_buffer_size);
711                 sc_val_from_ulong(1, divisor);
712                 _shift_right(_mant(b), divisor, divisor);
713                 sc_div(dividend, divisor, _mant(result));
714                 sticky = sc_had_carry();
715                 fc_exact &= !sticky;
716         }
717
718         fc_exact &= normalize(result, result, sticky);
719 }
720
721 #if 0
722 static void _power_of_ten(int exp, ieee_descriptor_t *desc, char *result) {
723         char *build;
724         char *temp;
725
726         /* positive sign */
727         result->sign = 0;
728
729         /* set new descriptor (else result is supposed to already have one) */
730         if (desc != NULL)
731                 result->desc = *desc;
732
733         build = alloca(value_size);
734         temp = alloca(value_size);
735
736         sc_val_from_ulong((1 << (result->desc.exponent_size - 1)) - 1, _exp(result));
737
738         if (exp > 0) {
739                 /* temp is value of ten now */
740                 sc_val_from_ulong(10, NULL);
741                 _save_result(temp);
742
743                 for (exp--; exp > 0; exp--) {
744                         _save_result(build);
745                         sc_mul(build, temp, NULL);
746                 }
747                 _save_result(build);
748
749                 /* temp is amount of left shift needed to put the value left of the radix point */
750                 sc_val_from_ulong(result->desc.mantissa_size + ROUNDING_BITS, temp);
751
752                 _shift_left(build, temp, _mant(result));
753
754                 _normalize(result, result, 0);
755         }
756 }
757 #endif
758
759 /**
760  * Truncate the fractional part away.
761  *
762  * This does not clip to any integer range.
763  */
764 static void _trunc(const fp_value *a, fp_value *result) {
765         /*
766          * When exponent == 0 all bits left of the radix point
767          * are the integral part of the value. For 15bit exp_size
768          * this would require a left shift of max. 16383 bits which
769          * is too much.
770          * But it is enough to ensure that no bit right of the radix
771          * point remains set. This restricts the interesting
772          * exponents to the interval [0, mant_size-1].
773          * Outside this interval the truncated value is either 0 or
774          * it does not have fractional parts.
775          */
776
777         int exp_bias, exp_val;
778         char *temp;
779
780         /* fixme: can be exact */
781         fc_exact = 0;
782
783         temp = alloca(value_size);
784
785         if (a != result)
786                 result->desc = a->desc;
787
788         exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
789         exp_val  = sc_val_to_long(_exp(a)) - exp_bias;
790
791         if (exp_val < 0) {
792                 sc_val_from_ulong(0, NULL);
793                 _save_result(_exp(result));
794                 _save_result(_mant(result));
795                 result->desc.clss = ZERO;
796
797                 return;
798         }
799
800         if (exp_val > a->desc.mantissa_size) {
801                 if (a != result)
802                         memcpy(result, a, calc_buffer_size);
803
804                 return;
805         }
806
807         /* set up a proper mask to delete all bits right of the
808          * radix point if the mantissa had been shifted until exp == 0 */
809         sc_max_from_bits(1 + exp_val, 0, temp);
810         sc_val_from_long(a->desc.mantissa_size - exp_val + 2, NULL);
811         _shift_left(temp, sc_get_buffer(), temp);
812
813         /* and the mask and return the result */
814         sc_and(_mant(a), temp, _mant(result));
815
816         if (a != result) memcpy(_exp(result), _exp(a), value_size);
817 }
818
819 /********
820  * functions defined in fltcalc.h
821  ********/
822 const void *fc_get_buffer(void) {
823         return calc_buffer;
824 }
825
826 int fc_get_buffer_length(void) {
827         return calc_buffer_size;
828 }
829
830 void *fc_val_from_str(const char *str, unsigned int len, const ieee_descriptor_t *desc, void *result) {
831 #if 0
832         enum {
833                 START,
834                 LEFT_OF_DOT,
835                 RIGHT_OF_DOT,
836                 EXP_START,
837                 EXPONENT,
838                 END
839         };
840
841         char exp_sign;
842         int exp_int, hsb, state;
843
844         const char *old_str;
845
846         int pos;
847         char *mant_str, *exp_val, *power_val;
848
849         (void) len;
850         if (result == NULL) result = calc_buffer;
851
852         exp_val = alloca(value_size);
853         power_val = alloca(calc_buffer_size);
854         mant_str = alloca((len)?(len):(strlen(str)));
855
856         result->desc.exponent_size = desc->exponent_size;
857         result->desc.mantissa_size = desc->mantissa_size;
858         result->desc.explicit_one  = desc->explicit_one;
859         result->desc.clss          = NORMAL;
860
861         old_str = str;
862         pos = 0;
863         exp_int = 0;
864         state = START;
865
866         while (len == 0 || str-old_str < len) {
867                 switch (state) {
868                 case START:
869                         switch (*str) {
870                         case '+':
871                                 result->sign = 0;
872                                 state = LEFT_OF_DOT;
873                                 str++;
874                                 break;
875
876                         case '-':
877                                 result->sign = 1;
878                                 state = LEFT_OF_DOT;
879                                 str++;
880                                 break;
881
882                         case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
883                                 result->sign = 0;
884                                 state = LEFT_OF_DOT;
885                                 break;
886
887                         case '.':
888                                 result->sign = 0;
889                                 state = RIGHT_OF_DOT;
890                                 str++;
891                                 break;
892
893                         case 'n':
894                         case 'N':
895                         case 'i':
896                         case 'I':
897                                 break;
898
899                         default:
900                                 fail_char(old_str, len, str - old_str);
901                         }
902                         break;
903
904                 case LEFT_OF_DOT:
905                         switch (*str) {
906                         case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
907                                 mant_str[pos++] = *(str++);
908                                 break;
909
910                         case '.':
911                                 state = RIGHT_OF_DOT;
912                                 str++;
913                                 break;
914
915                         case 'e':
916                         case 'E':
917                                 state = EXP_START;
918                                 str++;
919                                 break;
920
921                         case '\0':
922                                 mant_str[pos] = '\0';
923                                 goto done;
924
925                         default:
926                                 fail_char(old_str, len, str - old_str);
927                         }
928                         break;
929
930                 case RIGHT_OF_DOT:
931                         switch (*str) {
932                         case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
933                                 mant_str[pos++] = *(str++);
934                                 exp_int++;
935                                 break;
936
937                         case 'e':
938                         case 'E':
939                                 state = EXP_START;
940                                 str++;
941                                 break;
942
943                         case '\0':
944                                 mant_str[pos] = '\0';
945                                 goto done;
946
947                         default:
948                                 fail_char(old_str, len, str - old_str);
949                         }
950                         break;
951
952                 case EXP_START:
953                         switch (*str) {
954                         case '-':
955                                 exp_sign = 1;
956                                 /* fall through */
957                         case '+':
958                                 if (*(str-1) != 'e' && *(str-1) != 'E') fail_char(old_str, len, str - old_str);
959                                 str++;
960                                 break;
961
962                         case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
963                                 mant_str[pos] = '\0';
964                                 pos = 1;
965                                 str++;
966                                 state = EXPONENT;
967                                 break;
968
969                         default:
970                                 fail_char(old_str, len, str - old_str);
971                         }
972                         break;
973
974                 case EXPONENT:
975                         switch (*str) {
976                         case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
977                                 pos++;
978                                 str++;
979                                 break;
980
981                         case '\0': goto done;
982
983                         default:
984                                 fail_char(old_str, len, str - old_str);
985                         }
986                 }
987         } /*  switch(state) */
988
989 done:
990         sc_val_from_str(mant_str, strlen(mant_str), _mant(result));
991
992         /* shift to put value left of radix point */
993         sc_val_from_ulong(mant_size + ROUNDING_BITS, exp_val);
994
995         _shift_left(_mant(result), exp_val, _mant(result));
996
997         sc_val_from_ulong((1 << (exp_size - 1)) - 1, _exp(result));
998
999         _normalize(result, result, 0);
1000
1001         if (state == EXPONENT) {
1002                 exp_int -= atoi(str-pos);
1003         }
1004
1005         _power_of_ten(exp_int, &result->desc, power_val);
1006
1007         _fdiv(result, power_val, result);
1008
1009         return result;
1010 #else
1011         /* XXX excuse of an implementation to make things work */
1012         LLDBL             val;
1013         fp_value          *tmp = alloca(calc_buffer_size);
1014         ieee_descriptor_t tmp_desc;
1015         (void) len;
1016
1017 #ifdef HAVE_LONG_DOUBLE
1018         val = strtold(str, NULL);
1019         DEBUGPRINTF(("val_from_str(%s)\n", str));
1020         tmp_desc.exponent_size = 15;
1021         tmp_desc.mantissa_size = 63;
1022         tmp_desc.explicit_one  = 1;
1023         tmp_desc.clss          = NORMAL;
1024         fc_val_from_ieee754(val, &tmp_desc, tmp);
1025 #else
1026         val = strtod(str, NULL);
1027         DEBUGPRINTF(("val_from_str(%s)\n", str));
1028         tmp_desc.exponent_size = 11;
1029         tmp_desc.mantissa_size = 52;
1030         tmp_desc.explicit_one  = 0;
1031         tmp_desc.clss          = NORMAL;
1032         fc_val_from_ieee754(val, &tmp_desc, tmp);
1033 #endif /* HAVE_LONG_DOUBLE */
1034         return fc_cast(tmp, desc, result);
1035 #endif
1036 }
1037
1038 fp_value *fc_val_from_ieee754(LLDBL l, const ieee_descriptor_t *desc, fp_value *result) {
1039         char *temp;
1040         int bias_res, bias_val, mant_val;
1041         value_t srcval;
1042         UINT32 sign, exponent, mantissa0, mantissa1;
1043
1044         srcval.d = l;
1045         bias_res = ((1 << (desc->exponent_size - 1)) - 1);
1046
1047 #ifdef HAVE_LONG_DOUBLE
1048         mant_val  = 63;
1049         bias_val  = 0x3fff;
1050         sign      = (srcval.val.high & 0x00008000) != 0;
1051         exponent  = (srcval.val.high & 0x00007FFF) ;
1052         mantissa0 = srcval.val.mid;
1053         mantissa1 = srcval.val.low;
1054 #else /* no long double */
1055         mant_val  = 52;
1056         bias_val  = 0x3ff;
1057         sign      = (srcval.val.high & 0x80000000) != 0;
1058         exponent  = (srcval.val.high & 0x7FF00000) >> 20;
1059         mantissa0 = srcval.val.high & 0x000FFFFF;
1060         mantissa1 = srcval.val.low;
1061 #endif
1062
1063 #ifdef HAVE_LONG_DOUBLE
1064         TRACEPRINTF(("val_from_float(%.8X%.8X%.8X)\n", ((int*)&l)[2], ((int*)&l)[1], ((int*)&l)[0]));/* srcval.val.high, srcval.val.mid, srcval.val.low)); */
1065         DEBUGPRINTF(("(%d-%.4X-%.8X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1066 #else
1067         TRACEPRINTF(("val_from_float(%.8X%.8X)\n", srcval.val.high, srcval.val.low));
1068         DEBUGPRINTF(("(%d-%.3X-%.5X%.8X)\n", sign, exponent, mantissa0, mantissa1));
1069 #endif
1070
1071         if (result == NULL) result = calc_buffer;
1072         temp = alloca(value_size);
1073
1074         /* CLEAR the buffer, else some bits might be uninitialized */
1075         memset(result, 0, fc_get_buffer_length());
1076
1077         result->desc.exponent_size = desc->exponent_size;
1078         result->desc.mantissa_size = desc->mantissa_size;
1079         result->desc.explicit_one  = desc->explicit_one;
1080
1081         /* extract sign */
1082         result->sign = sign;
1083
1084         /* sign and flag suffice to identify NaN or inf, no exponent/mantissa
1085          * encoding is needed. the function can return immediately in these cases */
1086         if (isnan(l)) {
1087                 result->desc.clss = NAN;
1088                 TRACEPRINTF(("val_from_float resulted in NAN\n"));
1089                 return result;
1090         }
1091         else if (isinf(l)) {
1092                 result->desc.clss = INF;
1093                 TRACEPRINTF(("val_from_float resulted in %sINF\n", (result->sign == 1) ? "-" : ""));
1094                 return result;
1095         }
1096
1097         /* build exponent, because input and output exponent and mantissa sizes may differ
1098          * this looks more complicated than it is: unbiased input exponent + output bias,
1099          * minus the mantissa difference which is added again later when the output float
1100          * becomes normalized */
1101         sc_val_from_long((exponent - bias_val + bias_res) - (mant_val - desc->mantissa_size), _exp(result));
1102
1103         /* build mantissa representation */
1104         if (exponent != 0) {
1105                 /* insert the hidden bit */
1106                 sc_val_from_ulong(1, temp);
1107                 sc_val_from_ulong(mant_val + ROUNDING_BITS, NULL);
1108                 _shift_left(temp, sc_get_buffer(), NULL);
1109         }
1110         else {
1111                 sc_val_from_ulong(0, NULL);
1112         }
1113
1114         _save_result(_mant(result));
1115
1116         /* bits from the upper word */
1117         sc_val_from_ulong(mantissa0, temp);
1118         sc_val_from_ulong(34, NULL);
1119         _shift_left(temp, sc_get_buffer(), temp);
1120         sc_or(_mant(result), temp, _mant(result));
1121
1122         /* bits from the lower word */
1123         sc_val_from_ulong(mantissa1, temp);
1124         sc_val_from_ulong(ROUNDING_BITS, NULL);
1125         _shift_left(temp, sc_get_buffer(), temp);
1126         sc_or(_mant(result), temp, _mant(result));
1127
1128         /* _normalize expects the radix point to be normal, so shift mantissa of subnormal
1129          * origin one to the left */
1130         if (exponent == 0) {
1131                 sc_val_from_ulong(1, NULL);
1132                 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1133         }
1134
1135         normalize(result, result, 0);
1136
1137         TRACEPRINTF(("val_from_float results in %s\n", fc_print(result, temp, calc_buffer_size, FC_PACKED)));
1138
1139         return result;
1140 }
1141
1142 LLDBL fc_val_to_ieee754(const fp_value *val) {
1143         fp_value *value;
1144         fp_value *temp = NULL;
1145
1146         int byte_offset;
1147
1148         UINT32 sign;
1149         UINT32 exponent;
1150         UINT32 mantissa0;
1151         UINT32 mantissa1;
1152
1153         value_t           buildval;
1154         ieee_descriptor_t desc;
1155         unsigned          mantissa_size;
1156
1157 #ifdef HAVE_LONG_DOUBLE
1158         desc.exponent_size = 15;
1159         desc.mantissa_size = 63;
1160         desc.explicit_one  = 1;
1161         desc.clss          = NORMAL;
1162 #else
1163         desc.exponent_size = 11;
1164         desc.mantissa_size = 52;
1165         desc.explicit_one  = 0;
1166         desc.clss          = NORMAL;
1167 #endif
1168         mantissa_size = desc.mantissa_size + desc.explicit_one;
1169
1170         temp = alloca(calc_buffer_size);
1171         value = fc_cast(val, &desc, temp);
1172
1173         sign = value->sign;
1174
1175         /* @@@ long double exponent is 15bit, so the use of sc_val_to_long should not
1176          * lead to wrong results */
1177         exponent = sc_val_to_long(_exp(value)) ;
1178
1179         sc_val_from_ulong(ROUNDING_BITS, NULL);
1180         _shift_right(_mant(value), sc_get_buffer(), _mant(value));
1181
1182         mantissa0 = 0;
1183         mantissa1 = 0;
1184
1185         for (byte_offset = 0; byte_offset < 4; byte_offset++)
1186                 mantissa1 |= sc_sub_bits(_mant(value), mantissa_size, byte_offset) << (byte_offset << 3);
1187
1188         for (; (byte_offset<<3) < desc.mantissa_size; byte_offset++)
1189                 mantissa0 |= sc_sub_bits(_mant(value), mantissa_size, byte_offset) << ((byte_offset - 4) << 3);
1190
1191 #ifdef HAVE_LONG_DOUBLE
1192         buildval.val.high = sign << 15;
1193         buildval.val.high |= exponent;
1194         buildval.val.mid = mantissa0;
1195         buildval.val.low = mantissa1;
1196 #else /* no long double */
1197         mantissa0 &= 0x000FFFFF;  /* get rid of garbage */
1198         buildval.val.high = sign << 31;
1199         buildval.val.high |= exponent << 20;
1200         buildval.val.high |= mantissa0;
1201         buildval.val.low = mantissa1;
1202 #endif
1203
1204         TRACEPRINTF(("val_to_float: %d-%x-%x%x\n", sign, exponent, mantissa0, mantissa1));
1205         return buildval.d;
1206 }
1207
1208 fp_value *fc_cast(const fp_value *value, const ieee_descriptor_t *desc, fp_value *result) {
1209         char *temp;
1210         int exp_offset, val_bias, res_bias;
1211
1212         if (result == NULL) result = calc_buffer;
1213         temp = alloca(value_size);
1214
1215         if (value->desc.exponent_size == desc->exponent_size &&
1216                 value->desc.mantissa_size == desc->mantissa_size &&
1217                 value->desc.explicit_one  == desc->explicit_one) {
1218                 if (value != result)
1219                         memcpy(result, value, calc_buffer_size);
1220                 return result;
1221         }
1222
1223         if (value->desc.clss == NAN) {
1224                 if (sc_get_highest_set_bit(_mant(value)) == value->desc.mantissa_size + 1)
1225                         return fc_get_qnan(desc, result);
1226                 else
1227                         return fc_get_snan(desc, result);
1228         }
1229
1230         /* set the descriptor of the new value */
1231         result->desc.exponent_size = desc->exponent_size;
1232         result->desc.mantissa_size = desc->mantissa_size;
1233         result->desc.explicit_one  = desc->explicit_one;
1234         result->desc.clss          = value->desc.clss;
1235
1236         result->sign = value->sign;
1237
1238         /* when the mantissa sizes differ normalizing has to shift to align it.
1239          * this would change the exponent, which is unwanted. So calculate this
1240          * offset and add it */
1241         val_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1242         res_bias = (1 << (desc->exponent_size - 1)) - 1;
1243
1244         exp_offset = (res_bias - val_bias) - (value->desc.mantissa_size - desc->mantissa_size);
1245         sc_val_from_long(exp_offset, temp);
1246         sc_add(_exp(value), temp, _exp(result));
1247
1248         /* _normalize expects normalized radix point */
1249         if (value->desc.clss == SUBNORMAL) {
1250                 sc_val_from_ulong(1, NULL);
1251                 _shift_left(_mant(value), sc_get_buffer(), _mant(result));
1252         } else if (value != result) {
1253                 memcpy(_mant(result), _mant(value), value_size);
1254         } else {
1255                 memmove(_mant(result), _mant(value), value_size);
1256         }
1257
1258         normalize(result, result, 0);
1259         TRACEPRINTF(("Cast results in %s\n", fc_print(result, temp, value_size, FC_PACKED)));
1260         return result;
1261 }
1262
1263 fp_value *fc_get_max(const ieee_descriptor_t *desc, fp_value *result) {
1264         if (result == NULL) result = calc_buffer;
1265
1266         result->desc.exponent_size = desc->exponent_size;
1267         result->desc.mantissa_size = desc->mantissa_size;
1268         result->desc.explicit_one  = desc->explicit_one;
1269         result->desc.clss          = NORMAL;
1270
1271         result->sign = 0;
1272
1273         sc_val_from_ulong((1 << desc->exponent_size) - 2, _exp(result));
1274
1275         sc_max_from_bits(desc->mantissa_size + 1, 0, _mant(result));
1276         sc_val_from_ulong(ROUNDING_BITS, NULL);
1277         _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1278
1279         return result;
1280 }
1281
1282 fp_value *fc_get_min(const ieee_descriptor_t *desc, fp_value *result) {
1283         if (result == NULL) result = calc_buffer;
1284
1285         fc_get_max(desc, result);
1286         result->sign = 1;
1287
1288         return result;
1289 }
1290
1291 fp_value *fc_get_snan(const ieee_descriptor_t *desc, fp_value *result) {
1292         if (result == NULL) result = calc_buffer;
1293
1294         result->desc.exponent_size = desc->exponent_size;
1295         result->desc.mantissa_size = desc->mantissa_size;
1296         result->desc.explicit_one  = desc->explicit_one;
1297         result->desc.clss          = NAN;
1298
1299         result->sign = 0;
1300
1301         sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1302
1303         /* signaling NaN has non-zero mantissa with msb not set */
1304         sc_val_from_ulong(1, _mant(result));
1305
1306         return result;
1307 }
1308
1309 fp_value *fc_get_qnan(const ieee_descriptor_t *desc, fp_value *result) {
1310         if (result == NULL) result = calc_buffer;
1311
1312         result->desc.exponent_size = desc->exponent_size;
1313         result->desc.mantissa_size = desc->mantissa_size;
1314         result->desc.explicit_one  = desc->explicit_one;
1315         result->desc.clss          = NAN;
1316
1317         result->sign = 0;
1318
1319         sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1320
1321         /* quiet NaN has the msb of the mantissa set, so shift one there */
1322         sc_val_from_ulong(1, _mant(result));
1323         /* mantissa_size >+< 1 because of two extra rounding bits */
1324         sc_val_from_ulong(desc->mantissa_size + 1, NULL);
1325         _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1326
1327         return result;
1328 }
1329
1330 fp_value *fc_get_plusinf(const ieee_descriptor_t *desc, fp_value *result) {
1331         if (result == NULL) result = calc_buffer;
1332
1333         result->desc.exponent_size = desc->exponent_size;
1334         result->desc.mantissa_size = desc->mantissa_size;
1335         result->desc.explicit_one  = desc->explicit_one;
1336         result->desc.clss          = INF;
1337
1338         result->sign = 0;
1339
1340         sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1341
1342         sc_val_from_ulong(0, _mant(result));
1343
1344         return result;
1345 }
1346
1347 fp_value *fc_get_minusinf(const ieee_descriptor_t *desc, fp_value *result) {
1348         if (result == NULL) result = calc_buffer;
1349
1350         fc_get_plusinf(desc, result);
1351         result->sign = 1;
1352
1353         return result;
1354 }
1355
1356 int fc_comp(const fp_value *val_a, const fp_value *val_b) {
1357         int mul = 1;
1358
1359         /*
1360          * shortcut: if both values are identical, they are either
1361          * Unordered if NaN or equal
1362          */
1363         if (val_a == val_b)
1364                 return val_a->desc.clss == NAN ? 2 : 0;
1365
1366         /* unordered if one is a NaN */
1367         if (val_a->desc.clss == NAN || val_b->desc.clss == NAN)
1368                 return 2;
1369
1370         /* zero is equal independent of sign */
1371         if ((val_a->desc.clss == ZERO) && (val_b->desc.clss == ZERO))
1372                 return 0;
1373
1374         /* different signs make compare easy */
1375         if (val_a->sign != val_b->sign)
1376                 return (val_a->sign == 0) ? (1) : (-1);
1377
1378         mul = val_a->sign ? -1 : 1;
1379
1380         /* both infinity means equality */
1381         if ((val_a->desc.clss == INF) && (val_b->desc.clss == INF))
1382                 return 0;
1383
1384         /* infinity is bigger than the rest */
1385         if (val_a->desc.clss == INF)
1386                 return  1 * mul;
1387         if (val_b->desc.clss == INF)
1388                 return -1 * mul;
1389
1390         /* check first exponent, that mantissa if equal */
1391         switch (sc_comp(_exp(val_a), _exp(val_b))) {
1392         case -1:
1393                 return -1 * mul;
1394         case  1:
1395                 return  1 * mul;
1396         case  0:
1397                 return sc_comp(_mant(val_a), _mant(val_b)) * mul;
1398         default:
1399                 return 2;
1400         }
1401 }
1402
1403 int fc_is_zero(const fp_value *a) {
1404         return a->desc.clss == ZERO;
1405 }
1406
1407 int fc_is_negative(const fp_value *a) {
1408         return a->sign;
1409 }
1410
1411 int fc_is_inf(const fp_value *a) {
1412         return a->desc.clss == INF;
1413 }
1414
1415 int fc_is_nan(const fp_value *a) {
1416         return a->desc.clss == NAN;
1417 }
1418
1419 int fc_is_subnormal(const fp_value *a) {
1420         return a->desc.clss == SUBNORMAL;
1421 }
1422
1423 char *fc_print(const fp_value *val, char *buf, int buflen, unsigned base) {
1424         char *mul_1;
1425         LLDBL flt_val;
1426
1427         mul_1 = alloca(calc_buffer_size);
1428
1429         switch (base) {
1430         case FC_DEC:
1431                 switch ((value_class_t)val->desc.clss) {
1432                 case INF:
1433                         snprintf(buf, buflen, "%cINF", val->sign ? '-' : '+');
1434                         break;
1435                 case NAN:
1436                         snprintf(buf, buflen, "NaN");
1437                         break;
1438                 case ZERO:
1439                         snprintf(buf, buflen, "0.0");
1440                         break;
1441                 default:
1442                         flt_val = fc_val_to_ieee754(val);
1443 #ifdef HAVE_LONG_DOUBLE
1444                         /* XXX 30 is arbitrary */
1445                         snprintf(buf, buflen, "%.30LE", flt_val);
1446 #else
1447                         snprintf(buf, buflen, "%.18E", flt_val);
1448 #endif
1449                 }
1450                 break;
1451
1452         case FC_HEX:
1453                 switch ((value_class_t)val->desc.clss) {
1454                 case INF:
1455                         snprintf(buf, buflen, "%cINF", val->sign ? '-' : '+');
1456                         break;
1457                 case NAN:
1458                         snprintf(buf, buflen, "NAN");
1459                         break;
1460                 case ZERO:
1461                         snprintf(buf, buflen, "0.0");
1462                         break;
1463                 default:
1464                         flt_val = fc_val_to_ieee754(val);
1465 #ifdef HAVE_LONG_DOUBLE
1466                         snprintf(buf, buflen, "%LA", flt_val);
1467 #else
1468                         snprintf(buf, buflen, "%A", flt_val);
1469 #endif
1470                 }
1471                 break;
1472
1473         case FC_PACKED:
1474         default:
1475                 snprintf(buf, buflen, "%s", sc_print(pack(val, mul_1), value_size*4, SC_HEX, 0));
1476                 buf[buflen - 1] = '\0';
1477                 break;
1478         }
1479         return buf;
1480 }
1481
1482 unsigned char fc_sub_bits(const fp_value *value, unsigned num_bits, unsigned byte_ofs) {
1483         /* this is used to cache the packed version of the value */
1484         static char *packed_value = NULL;
1485
1486         if (packed_value == NULL) packed_value = XMALLOCN(char, value_size);
1487
1488         if (value != NULL)
1489                 pack(value, packed_value);
1490
1491         return sc_sub_bits(packed_value, num_bits, byte_ofs);
1492 }
1493
1494 /* Returns non-zero if the mantissa is zero, i.e. 1.0Exxx */
1495 int fc_zero_mantissa(const fp_value *value) {
1496         return sc_get_lowest_set_bit(_mant(value)) == ROUNDING_BITS + value->desc.mantissa_size;
1497 }
1498
1499 /* Returns the exponent of a value. */
1500 int fc_get_exponent(const fp_value *value) {
1501         int exp_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1502         return sc_val_to_long(_exp(value)) - exp_bias;
1503 }
1504
1505 /* Return non-zero if a given value can be converted lossless into another precision */
1506 int fc_can_lossless_conv_to(const fp_value *value, const ieee_descriptor_t *desc) {
1507         int v;
1508         int exp_bias;
1509
1510         /* handle some special cases first */
1511         switch (value->desc.clss) {
1512         case ZERO:
1513         case INF:
1514         case NAN:
1515                 return 1;
1516         default:
1517                 break;
1518         }
1519
1520         /* check if the exponent can be encoded: note, 0 and all ones are reserved for the exponent */
1521         exp_bias = (1 << (desc->exponent_size - 1)) - 1;
1522         v = fc_get_exponent(value) + exp_bias;
1523         if (0 < v && v < (1 << desc->exponent_size) - 1) {
1524                 /* exponent can be encoded, now check the mantissa */
1525                 v = value->desc.mantissa_size + ROUNDING_BITS - sc_get_lowest_set_bit(_mant(value));
1526                 return v < desc->mantissa_size;
1527         }
1528         return 0;
1529 }
1530
1531
1532 fc_rounding_mode_t fc_set_rounding_mode(fc_rounding_mode_t mode) {
1533         if (mode == FC_TONEAREST || mode == FC_TOPOSITIVE || mode == FC_TONEGATIVE || mode == FC_TOZERO)
1534                 rounding_mode = mode;
1535
1536         return rounding_mode;
1537 }
1538
1539 fc_rounding_mode_t fc_get_rounding_mode(void) {
1540         return rounding_mode;
1541 }
1542
1543 void init_fltcalc(int precision) {
1544         if (calc_buffer == NULL) {
1545                 /* does nothing if already init */
1546                 if (precision == 0) precision = FC_DEFAULT_PRECISION;
1547
1548                 init_strcalc(precision + 2 + ROUNDING_BITS);
1549
1550                 /* needs additionally rounding bits, one bit as explicit 1., and one for
1551                  * addition overflow */
1552                 max_precision = sc_get_precision() - (2 + ROUNDING_BITS);
1553                 if (max_precision < precision)
1554                         printf("WARNING: not enough precision available, using %d\n", max_precision);
1555
1556                 rounding_mode    = FC_TONEAREST;
1557                 value_size       = sc_get_buffer_length();
1558                 calc_buffer_size = sizeof(fp_value) + 2*value_size - 1;
1559
1560                 calc_buffer = xmalloc(calc_buffer_size);
1561                 memset(calc_buffer, 0, calc_buffer_size);
1562                 DEBUGPRINTF(("init fltcalc:\n\tVALUE_SIZE = %d\ntCALC_BUFFER_SIZE = %d\n\tcalc_buffer = %p\n\n", value_size, calc_buffer_size, calc_buffer));
1563 #ifdef HAVE_LONG_DOUBLE
1564                 DEBUGPRINTF(("\tUsing long double (1-15-64) interface\n"));
1565 #else
1566                 DEBUGPRINTF(("\tUsing double (1-11-52) interface\n"));
1567 #endif
1568 #ifdef WORDS_BIGENDIAN
1569                 DEBUGPRINTF(("\tWord order is big endian\n\n"));
1570 #else
1571                 DEBUGPRINTF(("\tWord order is little endian\n\n"));
1572 #endif
1573         }
1574 }
1575
1576 void finish_fltcalc (void) {
1577         free(calc_buffer); calc_buffer = NULL;
1578 }
1579
1580 #ifdef FLTCALC_TRACE_CALC
1581 static char buffer[100];
1582 #endif
1583
1584 /* definition of interface functions */
1585 fp_value *fc_add(const fp_value *a, const fp_value *b, fp_value *result) {
1586         if (result == NULL) result = calc_buffer;
1587
1588         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1589         TRACEPRINTF(("+ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1590
1591         /* make the value with the bigger exponent the first one */
1592         if (sc_comp(_exp(a), _exp(b)) == -1)
1593                 _fadd(b, a, result);
1594         else
1595                 _fadd(a, b, result);
1596
1597         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1598         return result;
1599 }
1600
1601 fp_value *fc_sub(const fp_value *a, const fp_value *b, fp_value *result) {
1602         fp_value *temp;
1603
1604         if (result == NULL) result = calc_buffer;
1605
1606         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1607         TRACEPRINTF(("- %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1608
1609         temp = alloca(calc_buffer_size);
1610         memcpy(temp, b, calc_buffer_size);
1611         temp->sign = !b->sign;
1612         if (sc_comp(_exp(a), _exp(temp)) == -1)
1613                 _fadd(temp, a, result);
1614         else
1615                 _fadd(a, temp, result);
1616
1617         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1618         return result;
1619 }
1620
1621 fp_value *fc_mul(const fp_value *a, const fp_value *b, fp_value *result) {
1622         if (result == NULL) result = calc_buffer;
1623
1624         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1625         TRACEPRINTF(("* %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1626
1627         _fmul(a, b, result);
1628
1629         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1630         return result;
1631 }
1632
1633 fp_value *fc_div(const fp_value *a, const fp_value *b, fp_value *result) {
1634         if (result == NULL) result = calc_buffer;
1635
1636         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1637         TRACEPRINTF(("/ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1638
1639         _fdiv(a, b, result);
1640
1641         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1642         return result;
1643 }
1644
1645 fp_value *fc_neg(const fp_value *a, fp_value *result) {
1646         if (result == NULL) result = calc_buffer;
1647
1648         TRACEPRINTF(("- %s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1649
1650         if (a != result)
1651                 memcpy(result, a, calc_buffer_size);
1652         result->sign = !a->sign;
1653
1654         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1655         return result;
1656 }
1657
1658 fp_value *fc_int(const fp_value *a, fp_value *result) {
1659         if (result == NULL) result = calc_buffer;
1660
1661         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1662         TRACEPRINTF(("truncated to integer "));
1663
1664         _trunc(a, result);
1665
1666         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1667         return result;
1668 }
1669
1670 fp_value *fc_rnd(const fp_value *a, fp_value *result) {
1671         if (result == NULL) result = calc_buffer;
1672
1673         (void) a;
1674         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1675         TRACEPRINTF(("rounded to integer "));
1676
1677         assert(!"fc_rnd() not yet implemented");
1678
1679         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1680         return result;
1681 }
1682
1683 /*
1684  * convert a floating point value into an sc value ...
1685  */
1686 int fc_flt2int(const fp_value *a, void *result, ir_mode *dst_mode) {
1687         if (a->desc.clss == NORMAL) {
1688                 int exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
1689                 int exp_val  = sc_val_to_long(_exp(a)) - exp_bias;
1690                 int shift, highest;
1691
1692                 if (a->sign && !mode_is_signed(dst_mode)) {
1693                         /* FIXME: for now we cannot convert this */
1694                         return 0;
1695                 }
1696
1697                 assert(exp_val >= 0 && "floating point value not integral before fc_flt2int() call");
1698                 shift = exp_val - (a->desc.mantissa_size + ROUNDING_BITS);
1699
1700                 if (shift > 0) {
1701                         sc_shlI(_mant(a),  shift, 64, 0, result);
1702                 } else {
1703                         sc_shrI(_mant(a), -shift, 64, 0, result);
1704                 }
1705
1706                 /* check for overflow */
1707                 highest = sc_get_highest_set_bit(result);
1708
1709                 if (mode_is_signed(dst_mode)) {
1710                         if (highest == sc_get_lowest_set_bit(result)) {
1711                                 /* need extra test for MIN_INT */
1712                                 if (highest >= (int) get_mode_size_bits(dst_mode)) {
1713                                         /* FIXME: handle overflow */
1714                                         return 0;
1715                                 }
1716                         } else {
1717                                 if (highest >= (int) get_mode_size_bits(dst_mode) - 1) {
1718                                         /* FIXME: handle overflow */
1719                                         return 0;
1720                                 }
1721                         }
1722                 } else {
1723                         if (highest >= (int) get_mode_size_bits(dst_mode)) {
1724                                 /* FIXME: handle overflow */
1725                                 return 0;
1726                         }
1727                 }
1728
1729                 if (a->sign)
1730                         sc_neg(result, result);
1731
1732                 return 1;
1733         }
1734         else if (a->desc.clss == ZERO) {
1735                 sc_zero(result);
1736                 return 1;
1737         }
1738         return 0;
1739 }
1740
1741
1742 unsigned fc_set_immediate_precision(unsigned bits) {
1743         unsigned old = immediate_prec;
1744
1745         immediate_prec = bits;
1746         return old;
1747 }
1748
1749 int fc_is_exact(void) {
1750         return fc_exact;
1751 }