iropt: cmp(~x & 1, 0) => !cmp(x & 1, 0)
[libfirm] / ir / tv / fltcalc.c
1 /*
2  * Copyright (C) 1995-2011 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 #include "config.h"
28
29 #include "fltcalc.h"
30 #include "strcalc.h"
31 #include "error.h"
32
33 #include <math.h>
34 #include <inttypes.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <stdio.h>
38 #include <assert.h>
39 #include <stdbool.h>
40
41 #include "xmalloc.h"
42
43 /*
44  * portability stuff (why do we even care about the msvc people with their C89?)
45  */
46
47
48 static long double string_to_long_double(const char *str)
49 {
50 #if __STDC_VERSION__ >= 199901L || _POSIX_C_SOURCE >= 200112L
51         return strtold(str, NULL);
52 #else
53         return strtod(str, NULL);
54 #endif
55 }
56
57 static bool my_isnan(long double val)
58 {
59 #if __STDC_VERSION__ >= 199901L
60         return isnan(val);
61 #else
62         /* hopefully the compiler does not optimize aggressively (=incorrect) */
63         return val != val;
64 #endif
65 }
66
67 static bool my_isinf(long double val)
68 {
69 #if __STDC_VERSION__ >= 199901L
70         return isinf(val);
71 #else
72         /* hopefully the compiler does not optimize aggressively (=incorrect) */
73         return my_isnan(val-val) && !my_isnan(val);
74 #endif
75 }
76
77 /** The number of extra precision rounding bits */
78 #define ROUNDING_BITS 2
79
80 typedef union {
81         struct {
82 #ifdef WORDS_BIGENDIAN
83                 uint32_t high;
84 #else
85                 uint32_t low;
86 #endif
87                 uint32_t mid;
88 #ifdef WORDS_BIGENDIAN
89                 uint32_t low;
90 #else
91                 uint32_t high;
92 #endif
93         } val_ld12;
94         struct {
95 #ifdef WORDS_BIGENDIAN
96                 uint32_t high;
97 #else
98                 uint32_t low;
99 #endif
100 #ifdef WORDS_BIGENDIAN
101                 uint32_t low;
102 #else
103                 uint32_t high;
104 #endif
105         } val_ld8;
106         volatile long double d;
107 } value_t;
108
109 #define CLEAR_BUFFER(buffer) memset(buffer, 0, calc_buffer_size)
110
111 /* our floating point value */
112 struct fp_value {
113         float_descriptor_t desc;
114         unsigned char clss;
115         char sign;
116         char value[1];        /* exp[value_size] + mant[value_size] */
117 };
118
119 #define _exp(a)  &((a)->value[0])
120 #define _mant(a) &((a)->value[value_size])
121
122 #define _save_result(x) memcpy((x), sc_get_buffer(), value_size)
123 #define _shift_right(x, y, res) sc_shr((x), (y), value_size*4, 0, (res))
124 #define _shift_left(x, y, res) sc_shl((x), (y), value_size*4, 0, (res))
125
126
127 #ifdef FLTCALC_DEBUG
128 #  define DEBUGPRINTF(x) printf x
129 #else
130 #  define DEBUGPRINTF(x) ((void)0)
131 #endif
132
133 #ifdef FLTCALC_TRACE_CALC
134 #  define TRACEPRINTF(x) printf x
135 #else
136 #  define TRACEPRINTF(x) ((void)0)
137 #endif
138
139 /** A temporal buffer. */
140 static fp_value *calc_buffer = NULL;
141
142 /** Current rounding mode.*/
143 static fc_rounding_mode_t rounding_mode;
144
145 static int calc_buffer_size;
146 static int value_size;
147 static int max_precision;
148
149 /** Exact flag. */
150 static int fc_exact = 1;
151
152 /** pack machine-like */
153 static void *pack(const fp_value *int_float, void *packed)
154 {
155         char     *shift_val;
156         char     *temp;
157         fp_value *val_buffer;
158         int      pos;
159
160         temp      = (char*) alloca(value_size);
161         shift_val = (char*) alloca(value_size);
162
163         switch ((value_class_t)int_float->clss) {
164         case FC_NAN:
165                 val_buffer = (fp_value*) alloca(calc_buffer_size);
166                 fc_get_qnan(&int_float->desc, val_buffer);
167                 int_float = val_buffer;
168                 break;
169
170         case FC_INF:
171                 val_buffer = (fp_value*) alloca(calc_buffer_size);
172                 fc_get_plusinf(&int_float->desc, val_buffer);
173                 val_buffer->sign = int_float->sign;
174                 int_float = val_buffer;
175                 break;
176
177         default:
178                 break;
179         }
180         assert(int_float->desc.explicit_one <= 1);
181
182         /* pack sign: move it to the left after exponent AND mantissa */
183         sc_val_from_ulong(int_float->sign, temp);
184
185         pos = int_float->desc.exponent_size + int_float->desc.mantissa_size + int_float->desc.explicit_one;
186         sc_val_from_ulong(pos, NULL);
187         _shift_left(temp, sc_get_buffer(), packed);
188
189         /* pack exponent: move it to the left after mantissa */
190         pos = int_float->desc.mantissa_size + int_float->desc.explicit_one;
191         sc_val_from_ulong(pos, shift_val);
192         _shift_left(_exp(int_float), shift_val, temp);
193
194         /* combine sign|exponent */
195         sc_or(temp, packed, packed);
196
197         /* extract mantissa */
198         /* remove rounding bits */
199         sc_val_from_ulong(ROUNDING_BITS, shift_val);
200         _shift_right(_mant(int_float), shift_val, temp);
201
202         /* remove leading 1 (or 0 if denormalized) */
203         sc_max_from_bits(pos, 0, shift_val); /* all mantissa bits are 1's */
204         sc_and(temp, shift_val, temp);
205
206         /* combine sign|exponent|mantissa */
207         sc_or(temp, packed, packed);
208
209         return packed;
210 }
211
212 /**
213  * Normalize a fp_value.
214  *
215  * @return non-zero if result is exact
216  */
217 static int normalize(const fp_value *in_val, fp_value *out_val, int sticky)
218 {
219         int exact = 1;
220         int hsb;
221         char lsb, guard, round, round_dir = 0;
222         char *temp = (char*) 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                 out_val->desc = in_val->desc;
230         }
231
232         out_val->clss = FC_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->clss = FC_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->clss == FC_SUBNORMAL))
325                 out_val->clss = FC_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->clss != FC_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->clss == FC_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->clss = FC_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->clss = FC_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->clss = FC_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->clss == FC_NAN) {                                \
404     if (a != result) memcpy(result, a, calc_buffer_size); \
405     fc_exact = 0;                                         \
406     return;                                               \
407   }                                                       \
408   if (b->clss == FC_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 {
421         char *temp;
422         char *exp_diff;
423
424         char sign, res_sign;
425         char sticky;
426
427         fc_exact = 1;
428
429         handle_NAN(a, b, result);
430
431         /* make sure result has a descriptor */
432         if (result != a && result != b)
433                 result->desc = a->desc;
434
435         /* determine if this is an addition or subtraction */
436         sign = a->sign ^ b->sign;
437
438         /* produce NaN on inf - inf */
439         if (sign && (a->clss == FC_INF) && (b->clss == FC_INF)) {
440                 fc_exact = 0;
441                 fc_get_qnan(&a->desc, result);
442                 return;
443         }
444
445         temp     = (char*) alloca(value_size);
446         exp_diff = (char*) alloca(value_size);
447
448         /* get exponent difference */
449         sc_sub(_exp(a), _exp(b), exp_diff);
450
451         /* initially set sign to be the sign of a, special treatment of subtraction
452          * when exponents are equal is required though.
453          * Also special care about the sign is needed when the mantissas are equal
454          * (+/- 0 ?) */
455         if (sign && sc_val_to_long(exp_diff) == 0) {
456                 switch (sc_comp(_mant(a), _mant(b))) {
457                 case 1:  /* a > b */
458                         res_sign = a->sign;  /* abs(a) is bigger and a is negative */
459                         break;
460                 case 0:  /* a == b */
461                         res_sign = (rounding_mode == FC_TONEGATIVE);
462                         break;
463                 case -1: /* a < b */
464                         res_sign = b->sign; /* abs(b) is bigger and b is negative */
465                         break;
466                 default:
467                         /* can't be reached */
468                         res_sign = 0;
469                         break;
470                 }
471         }
472         else
473                 res_sign = a->sign;
474         result->sign = res_sign;
475
476         /* sign has been taken care of, check for special cases */
477         if (a->clss == FC_ZERO || b->clss == FC_INF) {
478                 if (b != result)
479                         memcpy(result, b, calc_buffer_size);
480                 fc_exact = b->clss == FC_NORMAL;
481                 result->sign = res_sign;
482                 return;
483         }
484         if (b->clss == FC_ZERO || a->clss == FC_INF) {
485                 if (a != result)
486                         memcpy(result, a, calc_buffer_size);
487                 fc_exact = a->clss == FC_NORMAL;
488                 result->sign = res_sign;
489                 return;
490         }
491
492         /* shift the smaller value to the right to align the radix point */
493         /* subnormals have their radix point shifted to the right,
494          * take care of this first */
495         if ((b->clss == FC_SUBNORMAL) && (a->clss != FC_SUBNORMAL)) {
496                 sc_val_from_ulong(1, temp);
497                 sc_sub(exp_diff, temp, exp_diff);
498         }
499
500         _shift_right(_mant(b), exp_diff, temp);
501         sticky = sc_had_carry();
502         fc_exact &= !sticky;
503
504         if (sticky && sign) {
505                 /* if subtracting a little more than the represented value or adding a little
506                  * more than the represented value to a negative value this, in addition to the
507                  * still set sticky bit, takes account of the 'little more' */
508                 char *temp1 = (char*) alloca(calc_buffer_size);
509                 sc_val_from_ulong(1, temp1);
510                 sc_add(temp, temp1, temp);
511         }
512
513         if (sign) {
514                 if (sc_comp(_mant(a), temp) == -1)
515                         sc_sub(temp, _mant(a), _mant(result));
516                 else
517                         sc_sub(_mant(a), temp, _mant(result));
518         } else {
519                 sc_add(_mant(a), temp, _mant(result));
520         }
521
522         /* _normalize expects a 'normal' radix point, adding two subnormals
523          * results in a subnormal radix point -> shifting before normalizing */
524         if ((a->clss == FC_SUBNORMAL) && (b->clss == FC_SUBNORMAL)) {
525                 sc_val_from_ulong(1, NULL);
526                 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
527         }
528
529         /* resulting exponent is the bigger one */
530         memmove(_exp(result), _exp(a), value_size);
531
532         fc_exact &= normalize(result, result, sticky);
533 }
534
535 /**
536  * calculate a * b
537  */
538 static void _fmul(const fp_value *a, const fp_value *b, fp_value *result)
539 {
540         int sticky;
541         char *temp;
542         char res_sign;
543
544         fc_exact = 1;
545
546         handle_NAN(a, b, result);
547
548         temp = (char*) alloca(value_size);
549
550         if (result != a && result != b)
551                 result->desc = a->desc;
552
553         result->sign = res_sign = a->sign ^ b->sign;
554
555         /* produce NaN on 0 * inf */
556         if (a->clss == FC_ZERO) {
557                 if (b->clss == FC_INF) {
558                         fc_get_qnan(&a->desc, result);
559                         fc_exact = 0;
560                 } else {
561                         if (a != result)
562                                 memcpy(result, a, calc_buffer_size);
563                         result->sign = res_sign;
564                 }
565                 return;
566         }
567         if (b->clss == FC_ZERO) {
568                 if (a->clss == FC_INF) {
569                         fc_get_qnan(&a->desc, result);
570                         fc_exact = 0;
571                 } else {
572                         if (b != result)
573                                 memcpy(result, b, calc_buffer_size);
574                         result->sign = res_sign;
575                 }
576                 return;
577         }
578
579         if (a->clss == FC_INF) {
580                 fc_exact = 0;
581                 if (a != result)
582                         memcpy(result, a, calc_buffer_size);
583                 result->sign = res_sign;
584                 return;
585         }
586         if (b->clss == FC_INF) {
587                 fc_exact = 0;
588                 if (b != result)
589                         memcpy(result, b, calc_buffer_size);
590                 result->sign = res_sign;
591                 return;
592         }
593
594         /* exp = exp(a) + exp(b) - excess */
595         sc_add(_exp(a), _exp(b), _exp(result));
596
597         sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 1, temp);
598         sc_sub(_exp(result), temp, _exp(result));
599
600         /* mixed normal, subnormal values introduce an error of 1, correct it */
601         if ((a->clss == FC_SUBNORMAL) ^ (b->clss == FC_SUBNORMAL)) {
602                 sc_val_from_ulong(1, temp);
603                 sc_add(_exp(result), temp, _exp(result));
604         }
605
606         sc_mul(_mant(a), _mant(b), _mant(result));
607
608         /* realign result: after a multiplication the digits right of the radix
609          * point are the sum of the factors' digits after the radix point. As all
610          * values are normalized they both have the same amount of these digits,
611          * which has to be restored by proper shifting
612          * because of the rounding bits */
613         sc_val_from_ulong(ROUNDING_BITS + result->desc.mantissa_size, temp);
614
615         _shift_right(_mant(result), temp, _mant(result));
616         sticky = sc_had_carry();
617         fc_exact &= !sticky;
618
619         fc_exact &= normalize(result, result, sticky);
620 }
621
622 /**
623  * calculate a / b
624  */
625 static void _fdiv(const fp_value *a, const fp_value *b, fp_value *result)
626 {
627         int sticky;
628         char *temp, *dividend;
629         char res_sign;
630
631         fc_exact = 1;
632
633         handle_NAN(a, b, result);
634
635         temp = (char*) alloca(value_size);
636         dividend = (char*) alloca(value_size);
637
638         if (result != a && result != b)
639                 result->desc = a->desc;
640
641         result->sign = res_sign = a->sign ^ b->sign;
642
643         /* produce FC_NAN on 0/0 and inf/inf */
644         if (a->clss == FC_ZERO) {
645                 if (b->clss == FC_ZERO) {
646                         /* 0/0 -> NaN */
647                         fc_get_qnan(&a->desc, result);
648                         fc_exact = 0;
649                 } else {
650                         /* 0/x -> a */
651                         if (a != result)
652                                 memcpy(result, a, calc_buffer_size);
653                         result->sign = res_sign;
654                 }
655                 return;
656         }
657
658         if (b->clss == FC_INF) {
659                 fc_exact = 0;
660                 if (a->clss == FC_INF) {
661                         /* inf/inf -> NaN */
662                         fc_get_qnan(&a->desc, result);
663                 } else {
664                         /* x/inf -> 0 */
665                         sc_val_from_ulong(0, NULL);
666                         _save_result(_exp(result));
667                         _save_result(_mant(result));
668                         result->clss = FC_ZERO;
669                 }
670                 return;
671         }
672
673         if (a->clss == FC_INF) {
674                 fc_exact = 0;
675                 /* inf/x -> inf */
676                 if (a != result)
677                         memcpy(result, a, calc_buffer_size);
678                 result->sign = res_sign;
679                 return;
680         }
681         if (b->clss == FC_ZERO) {
682                 fc_exact = 0;
683                 /* division by zero */
684                 if (result->sign)
685                         fc_get_minusinf(&a->desc, result);
686                 else
687                         fc_get_plusinf(&a->desc, result);
688                 return;
689         }
690
691         /* exp = exp(a) - exp(b) + excess - 1*/
692         sc_sub(_exp(a), _exp(b), _exp(result));
693         sc_val_from_ulong((1 << (a->desc.exponent_size - 1)) - 2, temp);
694         sc_add(_exp(result), temp, _exp(result));
695
696         /* mixed normal, subnormal values introduce an error of 1, correct it */
697         if ((a->clss == FC_SUBNORMAL) ^ (b->clss == FC_SUBNORMAL)) {
698                 sc_val_from_ulong(1, temp);
699                 sc_add(_exp(result), temp, _exp(result));
700         }
701
702         /* mant(res) = mant(a) / 1/2mant(b) */
703         /* to gain more bits of precision in the result the dividend could be
704          * shifted left, as this operation does not loose bits. This would not
705          * fit into the integer precision, but due to the rounding bits (which
706          * are always zero because the values are all normalized) the divisor
707          * can be shifted right instead to achieve the same result */
708         sc_val_from_ulong(ROUNDING_BITS + result->desc.mantissa_size, temp);
709
710         _shift_left(_mant(a), temp, dividend);
711
712         {
713                 char *divisor = (char*) alloca(calc_buffer_size);
714                 sc_val_from_ulong(1, divisor);
715                 _shift_right(_mant(b), divisor, divisor);
716                 sc_div(dividend, divisor, _mant(result));
717                 sticky = sc_had_carry();
718                 fc_exact &= !sticky;
719         }
720
721         fc_exact &= normalize(result, result, sticky);
722 }
723
724 #if 0
725 static void _power_of_ten(int exp, float_descriptor_t *desc, char *result)
726 {
727         char *build;
728         char *temp;
729
730         /* positive sign */
731         result->sign = 0;
732
733         /* set new descriptor (else result is supposed to already have one) */
734         if (desc != NULL)
735                 result->desc = *desc;
736
737         build = alloca(value_size);
738         temp = alloca(value_size);
739
740         sc_val_from_ulong((1 << (result->desc.exponent_size - 1)) - 1, _exp(result));
741
742         if (exp > 0) {
743                 /* temp is value of ten now */
744                 sc_val_from_ulong(10, NULL);
745                 _save_result(temp);
746
747                 for (exp--; exp > 0; exp--) {
748                         _save_result(build);
749                         sc_mul(build, temp, NULL);
750                 }
751                 _save_result(build);
752
753                 /* temp is amount of left shift needed to put the value left of the radix point */
754                 sc_val_from_ulong(result->desc.mantissa_size + ROUNDING_BITS, temp);
755
756                 _shift_left(build, temp, _mant(result));
757
758                 _normalize(result, result, 0);
759         }
760 }
761 #endif
762
763 /**
764  * Truncate the fractional part away.
765  *
766  * This does not clip to any integer range.
767  */
768 static void _trunc(const fp_value *a, fp_value *result)
769 {
770         /*
771          * When exponent == 0 all bits left of the radix point
772          * are the integral part of the value. For 15bit exp_size
773          * this would require a left shift of max. 16383 bits which
774          * is too much.
775          * But it is enough to ensure that no bit right of the radix
776          * point remains set. This restricts the interesting
777          * exponents to the interval [0, mant_size-1].
778          * Outside this interval the truncated value is either 0 or
779          * it does not have fractional parts.
780          */
781
782         int exp_bias, exp_val;
783         char *temp;
784
785         /* fixme: can be exact */
786         fc_exact = 0;
787
788         temp = (char*) alloca(value_size);
789
790         if (a != result) {
791                 result->desc = a->desc;
792                 result->clss = a->clss;
793         }
794
795         exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
796         exp_val  = sc_val_to_long(_exp(a)) - exp_bias;
797
798         if (exp_val < 0) {
799                 sc_val_from_ulong(0, NULL);
800                 _save_result(_exp(result));
801                 _save_result(_mant(result));
802                 result->clss = FC_ZERO;
803
804                 return;
805         }
806
807         if (exp_val > (long)a->desc.mantissa_size) {
808                 if (a != result)
809                         memcpy(result, a, calc_buffer_size);
810
811                 return;
812         }
813
814         /* set up a proper mask to delete all bits right of the
815          * radix point if the mantissa had been shifted until exp == 0 */
816         sc_max_from_bits(1 + exp_val, 0, temp);
817         sc_val_from_long(a->desc.mantissa_size - exp_val + 2, NULL);
818         _shift_left(temp, sc_get_buffer(), temp);
819
820         /* and the mask and return the result */
821         sc_and(_mant(a), temp, _mant(result));
822
823         if (a != result) {
824                 memcpy(_exp(result), _exp(a), value_size);
825                 result->sign = a->sign;
826         }
827 }
828
829 /********
830  * functions defined in fltcalc.h
831  ********/
832 const void *fc_get_buffer(void)
833 {
834         return calc_buffer;
835 }
836
837 int fc_get_buffer_length(void)
838 {
839         return calc_buffer_size;
840 }
841
842 void *fc_val_from_str(const char *str, size_t len,
843                       const float_descriptor_t *desc, void *result)
844 {
845         char *buffer;
846
847         /* XXX excuse of an implementation to make things work */
848         long double        val;
849         fp_value          *tmp = (fp_value*) alloca(calc_buffer_size);
850         float_descriptor_t tmp_desc;
851
852         buffer = (char*) alloca(len+1);
853         memcpy(buffer, str, len);
854         buffer[len] = '\0';
855         val = string_to_long_double(buffer);
856
857         DEBUGPRINTF(("val_from_str(%s)\n", str));
858         tmp_desc.exponent_size = 15;
859         tmp_desc.mantissa_size = 63;
860         tmp_desc.explicit_one  = 1;
861         fc_val_from_ieee754(val, &tmp_desc, tmp);
862
863         return fc_cast(tmp, desc, (fp_value*) result);
864 }
865
866 fp_value *fc_val_from_ieee754(long double l, const float_descriptor_t *desc,
867                               fp_value *result)
868 {
869         char    *temp;
870         int      bias_res, bias_val, mant_val;
871         value_t  srcval;
872         char     sign;
873         uint32_t exponent, mantissa0, mantissa1;
874         size_t   long_double_size = sizeof(long double);
875
876         srcval.d = l;
877         bias_res = ((1 << (desc->exponent_size - 1)) - 1);
878
879         if (long_double_size == 8) {
880                 mant_val  = 52;
881                 bias_val  = 0x3ff;
882                 sign      = (srcval.val_ld8.high & 0x80000000) != 0;
883                 exponent  = (srcval.val_ld8.high & 0x7FF00000) >> 20;
884                 mantissa0 = srcval.val_ld8.high & 0x000FFFFF;
885                 mantissa1 = srcval.val_ld8.low;
886         } else {
887                 /* we assume an x86-like 80bit representation of the value... */
888                 assert(sizeof(long double)==12 || sizeof(long double)==16);
889                 mant_val  = 63;
890                 bias_val  = 0x3fff;
891                 sign      = (srcval.val_ld12.high & 0x00008000) != 0;
892                 exponent  = (srcval.val_ld12.high & 0x00007FFF) ;
893                 mantissa0 = srcval.val_ld12.mid;
894                 mantissa1 = srcval.val_ld12.low;
895         }
896
897         if (result == NULL)
898                 result = calc_buffer;
899         temp = (char*) alloca(value_size);
900
901         /* CLEAR the buffer, else some bits might be uninitialized */
902         memset(result, 0, fc_get_buffer_length());
903
904         result->desc = *desc;
905         result->clss = FC_NORMAL;
906         result->sign = sign;
907
908         /* sign and flag suffice to identify NaN or inf, no exponent/mantissa
909          * encoding is needed. the function can return immediately in these cases */
910         if (my_isnan(l)) {
911                 result->clss = FC_NAN;
912                 TRACEPRINTF(("val_from_float resulted in NAN\n"));
913                 return result;
914         } else if (my_isinf(l)) {
915                 result->clss = FC_INF;
916                 TRACEPRINTF(("val_from_float resulted in %sINF\n", (result->sign == 1) ? "-" : ""));
917                 return result;
918         }
919
920         /* build exponent, because input and output exponent and mantissa sizes may differ
921          * this looks more complicated than it is: unbiased input exponent + output bias,
922          * minus the mantissa difference which is added again later when the output float
923          * becomes normalized */
924         sc_val_from_long((exponent - bias_val + bias_res) - (mant_val - desc->mantissa_size), _exp(result));
925
926         /* build mantissa representation */
927         if (exponent != 0) {
928                 /* insert the hidden bit */
929                 sc_val_from_ulong(1, temp);
930                 sc_val_from_ulong(mant_val + ROUNDING_BITS, NULL);
931                 _shift_left(temp, sc_get_buffer(), NULL);
932         }
933         else {
934                 sc_val_from_ulong(0, NULL);
935         }
936
937         _save_result(_mant(result));
938
939         /* bits from the upper word */
940         sc_val_from_ulong(mantissa0, temp);
941         sc_val_from_ulong(34, NULL);
942         _shift_left(temp, sc_get_buffer(), temp);
943         sc_or(_mant(result), temp, _mant(result));
944
945         /* bits from the lower word */
946         sc_val_from_ulong(mantissa1, temp);
947         sc_val_from_ulong(ROUNDING_BITS, NULL);
948         _shift_left(temp, sc_get_buffer(), temp);
949         sc_or(_mant(result), temp, _mant(result));
950
951         /* _normalize expects the radix point to be normal, so shift mantissa of subnormal
952          * origin one to the left */
953         if (exponent == 0) {
954                 sc_val_from_ulong(1, NULL);
955                 _shift_left(_mant(result), sc_get_buffer(), _mant(result));
956         }
957
958         normalize(result, result, 0);
959
960         TRACEPRINTF(("val_from_float results in %s\n", fc_print(result, temp, calc_buffer_size, FC_PACKED)));
961
962         return result;
963 }
964
965 long double fc_val_to_ieee754(const fp_value *val)
966 {
967         fp_value *value;
968         fp_value *temp = NULL;
969
970         unsigned byte_offset;
971
972         uint32_t sign;
973         uint32_t exponent;
974         uint32_t mantissa0;
975         uint32_t mantissa1;
976
977         value_t           buildval;
978         float_descriptor_t desc;
979         unsigned          mantissa_size;
980
981         size_t            long_double_size = sizeof(long double);
982
983         if (long_double_size == 8) {
984                 desc.exponent_size = 11;
985                 desc.mantissa_size = 52;
986                 desc.explicit_one  = 0;
987         } else {
988                 desc.exponent_size = 15;
989                 desc.mantissa_size = 63;
990                 desc.explicit_one  = 1;
991         }
992         mantissa_size = desc.mantissa_size + desc.explicit_one;
993
994         temp = (fp_value*) alloca(calc_buffer_size);
995         value = fc_cast(val, &desc, temp);
996
997         sign = value->sign;
998
999         /* @@@ long double exponent is 15bit, so the use of sc_val_to_long should not
1000          * lead to wrong results */
1001         exponent = sc_val_to_long(_exp(value)) ;
1002
1003         sc_val_from_ulong(ROUNDING_BITS, NULL);
1004         _shift_right(_mant(value), sc_get_buffer(), _mant(value));
1005
1006         mantissa0 = 0;
1007         mantissa1 = 0;
1008
1009         for (byte_offset = 0; byte_offset < 4; byte_offset++)
1010                 mantissa1 |= sc_sub_bits(_mant(value), mantissa_size, byte_offset) << (byte_offset << 3);
1011
1012         for (; (byte_offset<<3) < desc.mantissa_size; byte_offset++)
1013                 mantissa0 |= sc_sub_bits(_mant(value), mantissa_size, byte_offset) << ((byte_offset - 4) << 3);
1014
1015         if (long_double_size == 8) {
1016                 mantissa0 &= 0x000FFFFF;  /* get rid of garbage */
1017                 buildval.val_ld8.high = sign << 31;
1018                 buildval.val_ld8.high |= exponent << 20;
1019                 buildval.val_ld8.high |= mantissa0;
1020                 buildval.val_ld8.low = mantissa1;
1021         } else {
1022                 buildval.val_ld12.high = sign << 15;
1023                 buildval.val_ld12.high |= exponent;
1024                 buildval.val_ld12.mid = mantissa0;
1025                 buildval.val_ld12.low = mantissa1;
1026         }
1027
1028         TRACEPRINTF(("val_to_float: %d-%x-%x%x\n", sign, exponent, mantissa0, mantissa1));
1029         return buildval.d;
1030 }
1031
1032 fp_value *fc_cast(const fp_value *value, const float_descriptor_t *desc,
1033                   fp_value *result)
1034 {
1035         char *temp;
1036         int exp_offset, val_bias, res_bias;
1037
1038         if (result == NULL) result = calc_buffer;
1039         temp = (char*) alloca(value_size);
1040
1041         if (value->desc.exponent_size == desc->exponent_size &&
1042                 value->desc.mantissa_size == desc->mantissa_size &&
1043                 value->desc.explicit_one  == desc->explicit_one) {
1044                 if (value != result)
1045                         memcpy(result, value, calc_buffer_size);
1046                 return result;
1047         }
1048
1049         if (value->clss == FC_NAN) {
1050                 if (sc_get_highest_set_bit(_mant(value)) == value->desc.mantissa_size + 1)
1051                         return fc_get_qnan(desc, result);
1052                 else
1053                         return fc_get_snan(desc, result);
1054         }
1055         else if (value->clss == FC_INF) {
1056                 if (value->sign == 0)
1057                         return fc_get_plusinf(desc, result);
1058                 else
1059                         return fc_get_minusinf(desc, result);
1060         }
1061
1062         /* set the descriptor of the new value */
1063         result->desc = *desc;
1064         result->clss = value->clss;
1065         result->sign = value->sign;
1066
1067         /* when the mantissa sizes differ normalizing has to shift to align it.
1068          * this would change the exponent, which is unwanted. So calculate this
1069          * offset and add it */
1070         val_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1071         res_bias = (1 << (desc->exponent_size - 1)) - 1;
1072
1073         exp_offset = (res_bias - val_bias) - (value->desc.mantissa_size - desc->mantissa_size);
1074         sc_val_from_long(exp_offset, temp);
1075         sc_add(_exp(value), temp, _exp(result));
1076
1077         /* _normalize expects normalized radix point */
1078         if (value->clss == FC_SUBNORMAL) {
1079                 sc_val_from_ulong(1, NULL);
1080                 _shift_left(_mant(value), sc_get_buffer(), _mant(result));
1081         } else if (value != result) {
1082                 memcpy(_mant(result), _mant(value), value_size);
1083         } else {
1084                 memmove(_mant(result), _mant(value), value_size);
1085         }
1086
1087         normalize(result, result, 0);
1088         TRACEPRINTF(("Cast results in %s\n", fc_print(result, temp, value_size, FC_PACKED)));
1089         return result;
1090 }
1091
1092 fp_value *fc_get_max(const float_descriptor_t *desc, fp_value *result)
1093 {
1094         if (result == NULL) result = calc_buffer;
1095
1096         result->desc = *desc;
1097         result->clss = FC_NORMAL;
1098         result->sign = 0;
1099
1100         sc_val_from_ulong((1 << desc->exponent_size) - 2, _exp(result));
1101
1102         sc_max_from_bits(desc->mantissa_size + 1, 0, _mant(result));
1103         sc_val_from_ulong(ROUNDING_BITS, NULL);
1104         _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1105
1106         return result;
1107 }
1108
1109 fp_value *fc_get_min(const float_descriptor_t *desc, fp_value *result)
1110 {
1111         if (result == NULL) result = calc_buffer;
1112
1113         fc_get_max(desc, result);
1114         result->sign = 1;
1115
1116         return result;
1117 }
1118
1119 fp_value *fc_get_snan(const float_descriptor_t *desc, fp_value *result)
1120 {
1121         if (result == NULL) result = calc_buffer;
1122
1123         result->desc = *desc;
1124         result->clss = FC_NAN;
1125         result->sign = 0;
1126
1127         sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1128
1129         /* signaling NaN has non-zero mantissa with msb not set */
1130         sc_val_from_ulong(1, _mant(result));
1131
1132         return result;
1133 }
1134
1135 fp_value *fc_get_qnan(const float_descriptor_t *desc, fp_value *result)
1136 {
1137         if (result == NULL) result = calc_buffer;
1138
1139         result->desc = *desc;
1140         result->clss = FC_NAN;
1141         result->sign = 0;
1142
1143         sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1144
1145         /* quiet NaN has the msb of the mantissa set, so shift one there */
1146         sc_val_from_ulong(1, _mant(result));
1147         /* mantissa_size >+< 1 because of two extra rounding bits */
1148         sc_val_from_ulong(desc->mantissa_size + 1, NULL);
1149         _shift_left(_mant(result), sc_get_buffer(), _mant(result));
1150
1151         return result;
1152 }
1153
1154 fp_value *fc_get_plusinf(const float_descriptor_t *desc, fp_value *result)
1155 {
1156         char *mant;
1157
1158         if (result == NULL) result = calc_buffer;
1159
1160         result->desc = *desc;
1161         result->clss = FC_INF;
1162         result->sign = 0;
1163
1164         sc_val_from_ulong((1 << desc->exponent_size) - 1, _exp(result));
1165
1166         mant = _mant(result);
1167         sc_val_from_ulong(0, mant);
1168         if (desc->explicit_one) {
1169                 sc_set_bit_at(mant, result->desc.mantissa_size + ROUNDING_BITS);
1170         }
1171
1172         return result;
1173 }
1174
1175 fp_value *fc_get_minusinf(const float_descriptor_t *desc, fp_value *result)
1176 {
1177         if (result == NULL) result = calc_buffer;
1178
1179         fc_get_plusinf(desc, result);
1180         result->sign = 1;
1181
1182         return result;
1183 }
1184
1185 int fc_comp(const fp_value *val_a, const fp_value *val_b)
1186 {
1187         int mul = 1;
1188
1189         /*
1190          * shortcut: if both values are identical, they are either
1191          * Unordered if NaN or equal
1192          */
1193         if (val_a == val_b)
1194                 return val_a->clss == FC_NAN ? 2 : 0;
1195
1196         /* unordered if one is a NaN */
1197         if (val_a->clss == FC_NAN || val_b->clss == FC_NAN)
1198                 return 2;
1199
1200         /* zero is equal independent of sign */
1201         if ((val_a->clss == FC_ZERO) && (val_b->clss == FC_ZERO))
1202                 return 0;
1203
1204         /* different signs make compare easy */
1205         if (val_a->sign != val_b->sign)
1206                 return (val_a->sign == 0) ? (1) : (-1);
1207
1208         mul = val_a->sign ? -1 : 1;
1209
1210         /* both infinity means equality */
1211         if ((val_a->clss == FC_INF) && (val_b->clss == FC_INF))
1212                 return 0;
1213
1214         /* infinity is bigger than the rest */
1215         if (val_a->clss == FC_INF)
1216                 return  1 * mul;
1217         if (val_b->clss == FC_INF)
1218                 return -1 * mul;
1219
1220         /* check first exponent, that mantissa if equal */
1221         switch (sc_comp(_exp(val_a), _exp(val_b))) {
1222         case -1:
1223                 return -1 * mul;
1224         case  1:
1225                 return  1 * mul;
1226         case  0:
1227                 return sc_comp(_mant(val_a), _mant(val_b)) * mul;
1228         default:
1229                 return 2;
1230         }
1231 }
1232
1233 int fc_is_zero(const fp_value *a)
1234 {
1235         return a->clss == FC_ZERO;
1236 }
1237
1238 int fc_is_negative(const fp_value *a)
1239 {
1240         return a->sign;
1241 }
1242
1243 int fc_is_inf(const fp_value *a)
1244 {
1245         return a->clss == FC_INF;
1246 }
1247
1248 int fc_is_nan(const fp_value *a)
1249 {
1250         return a->clss == FC_NAN;
1251 }
1252
1253 int fc_is_subnormal(const fp_value *a)
1254 {
1255         return a->clss == FC_SUBNORMAL;
1256 }
1257
1258 char *fc_print(const fp_value *val, char *buf, int buflen, unsigned base)
1259 {
1260         char *mul_1;
1261         long double flt_val;
1262
1263         mul_1 = (char*) alloca(calc_buffer_size);
1264
1265         switch (base) {
1266         case FC_DEC:
1267                 switch ((value_class_t)val->clss) {
1268                 case FC_INF:
1269                         snprintf(buf, buflen, "%cINF", val->sign ? '-' : '+');
1270                         break;
1271                 case FC_NAN:
1272                         snprintf(buf, buflen, "NaN");
1273                         break;
1274                 case FC_ZERO:
1275                         snprintf(buf, buflen, "0.0");
1276                         break;
1277                 default:
1278                         flt_val = fc_val_to_ieee754(val);
1279                         /* XXX 30 is arbitrary */
1280                         snprintf(buf, buflen, "%.30LE", flt_val);
1281                 }
1282                 break;
1283
1284         case FC_HEX:
1285                 switch ((value_class_t)val->clss) {
1286                 case FC_INF:
1287                         snprintf(buf, buflen, "%cINF", val->sign ? '-' : '+');
1288                         break;
1289                 case FC_NAN:
1290                         snprintf(buf, buflen, "NaN");
1291                         break;
1292                 case FC_ZERO:
1293                         snprintf(buf, buflen, "0.0");
1294                         break;
1295                 default:
1296                         flt_val = fc_val_to_ieee754(val);
1297                         snprintf(buf, buflen, "%LA", flt_val);
1298                 }
1299                 break;
1300
1301         case FC_PACKED:
1302         default:
1303                 snprintf(buf, buflen, "%s", sc_print(pack(val, mul_1), value_size*4, SC_HEX, 0));
1304                 buf[buflen - 1] = '\0';
1305                 break;
1306         }
1307         return buf;
1308 }
1309
1310 unsigned char fc_sub_bits(const fp_value *value, unsigned num_bits, unsigned byte_ofs)
1311 {
1312         /* this is used to cache the packed version of the value */
1313         static char *packed_value = NULL;
1314
1315         if (packed_value == NULL) packed_value = XMALLOCN(char, value_size);
1316
1317         if (value != NULL)
1318                 pack(value, packed_value);
1319
1320         return sc_sub_bits(packed_value, num_bits, byte_ofs);
1321 }
1322
1323 /* Returns non-zero if the mantissa is zero, i.e. 1.0Exxx */
1324 int fc_zero_mantissa(const fp_value *value)
1325 {
1326         return sc_get_lowest_set_bit(_mant(value)) == ROUNDING_BITS + value->desc.mantissa_size;
1327 }
1328
1329 /* Returns the exponent of a value. */
1330 int fc_get_exponent(const fp_value *value)
1331 {
1332         int exp_bias = (1 << (value->desc.exponent_size - 1)) - 1;
1333         return sc_val_to_long(_exp(value)) - exp_bias;
1334 }
1335
1336 /* Return non-zero if a given value can be converted lossless into another precision */
1337 int fc_can_lossless_conv_to(const fp_value *value, const float_descriptor_t *desc)
1338 {
1339         int v;
1340         int exp_bias;
1341
1342         /* handle some special cases first */
1343         switch (value->clss) {
1344         case FC_ZERO:
1345         case FC_INF:
1346         case FC_NAN:
1347                 return 1;
1348         default:
1349                 break;
1350         }
1351
1352         /* check if the exponent can be encoded: note, 0 and all ones are reserved for the exponent */
1353         exp_bias = (1 << (desc->exponent_size - 1)) - 1;
1354         v = fc_get_exponent(value) + exp_bias;
1355         if (0 < v && v < (1 << desc->exponent_size) - 1) {
1356                 /* exponent can be encoded, now check the mantissa */
1357                 v = value->desc.mantissa_size + ROUNDING_BITS - sc_get_lowest_set_bit(_mant(value));
1358                 return v <= (int)desc->mantissa_size;
1359         }
1360         return 0;
1361 }
1362
1363
1364 fc_rounding_mode_t fc_set_rounding_mode(fc_rounding_mode_t mode)
1365 {
1366         if (mode == FC_TONEAREST || mode == FC_TOPOSITIVE || mode == FC_TONEGATIVE || mode == FC_TOZERO)
1367                 rounding_mode = mode;
1368
1369         return rounding_mode;
1370 }
1371
1372 fc_rounding_mode_t fc_get_rounding_mode(void)
1373 {
1374         return rounding_mode;
1375 }
1376
1377 void init_fltcalc(int precision)
1378 {
1379         if (calc_buffer == NULL) {
1380                 /* does nothing if already init */
1381                 if (precision == 0) precision = FC_DEFAULT_PRECISION;
1382
1383                 init_strcalc(precision + 2 + ROUNDING_BITS);
1384
1385                 /* needs additionally rounding bits, one bit as explicit 1., and one for
1386                  * addition overflow */
1387                 max_precision = sc_get_precision() - (2 + ROUNDING_BITS);
1388                 if (max_precision < precision)
1389                         printf("WARNING: not enough precision available, using %d\n", max_precision);
1390
1391                 rounding_mode    = FC_TONEAREST;
1392                 value_size       = sc_get_buffer_length();
1393                 calc_buffer_size = sizeof(fp_value) + 2*value_size - 1;
1394
1395                 calc_buffer = (fp_value*) xmalloc(calc_buffer_size);
1396                 memset(calc_buffer, 0, calc_buffer_size);
1397                 DEBUGPRINTF(("init fltcalc:\n\tVALUE_SIZE = %d\ntCALC_BUFFER_SIZE = %d\n\tcalc_buffer = %p\n\n", value_size, calc_buffer_size, calc_buffer));
1398         }
1399 }
1400
1401 void finish_fltcalc (void)
1402 {
1403         free(calc_buffer); calc_buffer = NULL;
1404 }
1405
1406 #ifdef FLTCALC_TRACE_CALC
1407 static char buffer[100];
1408 #endif
1409
1410 /* definition of interface functions */
1411 fp_value *fc_add(const fp_value *a, const fp_value *b, fp_value *result)
1412 {
1413         if (result == NULL) result = calc_buffer;
1414
1415         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1416         TRACEPRINTF(("+ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1417
1418         /* make the value with the bigger exponent the first one */
1419         if (sc_comp(_exp(a), _exp(b)) == -1)
1420                 _fadd(b, a, result);
1421         else
1422                 _fadd(a, b, result);
1423
1424         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1425         return result;
1426 }
1427
1428 fp_value *fc_sub(const fp_value *a, const fp_value *b, fp_value *result)
1429 {
1430         fp_value *temp;
1431
1432         if (result == NULL) result = calc_buffer;
1433
1434         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1435         TRACEPRINTF(("- %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1436
1437         temp = (fp_value*) alloca(calc_buffer_size);
1438         memcpy(temp, b, calc_buffer_size);
1439         temp->sign = !b->sign;
1440         if (sc_comp(_exp(a), _exp(temp)) == -1)
1441                 _fadd(temp, a, result);
1442         else
1443                 _fadd(a, temp, result);
1444
1445         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1446         return result;
1447 }
1448
1449 fp_value *fc_mul(const fp_value *a, const fp_value *b, fp_value *result)
1450 {
1451         if (result == NULL) result = calc_buffer;
1452
1453         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1454         TRACEPRINTF(("* %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1455
1456         _fmul(a, b, result);
1457
1458         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1459         return result;
1460 }
1461
1462 fp_value *fc_div(const fp_value *a, const fp_value *b, fp_value *result)
1463 {
1464         if (result == NULL) result = calc_buffer;
1465
1466         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1467         TRACEPRINTF(("/ %s ", fc_print(b, buffer, sizeof(buffer), FC_PACKED)));
1468
1469         _fdiv(a, b, result);
1470
1471         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1472         return result;
1473 }
1474
1475 fp_value *fc_neg(const fp_value *a, fp_value *result)
1476 {
1477         if (result == NULL) result = calc_buffer;
1478
1479         TRACEPRINTF(("- %s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1480
1481         if (a != result)
1482                 memcpy(result, a, calc_buffer_size);
1483         result->sign = !a->sign;
1484
1485         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1486         return result;
1487 }
1488
1489 fp_value *fc_int(const fp_value *a, fp_value *result)
1490 {
1491         if (result == NULL) result = calc_buffer;
1492
1493         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1494         TRACEPRINTF(("truncated to integer "));
1495
1496         _trunc(a, result);
1497
1498         TRACEPRINTF(("= %s\n", fc_print(result, buffer, sizeof(buffer), FC_PACKED)));
1499         return result;
1500 }
1501
1502 fp_value *fc_rnd(const fp_value *a, fp_value *result)
1503 {
1504         if (result == NULL) result = calc_buffer;
1505
1506         (void) a;
1507         TRACEPRINTF(("%s ", fc_print(a, buffer, sizeof(buffer), FC_PACKED)));
1508         TRACEPRINTF(("rounded to integer "));
1509
1510         panic("fc_rnd() not yet implemented");
1511 }
1512
1513 /*
1514  * convert a floating point value into an sc value ...
1515  */
1516 int fc_flt2int(const fp_value *a, void *result, ir_mode *dst_mode)
1517 {
1518         if (a->clss == FC_NORMAL) {
1519                 int exp_bias = (1 << (a->desc.exponent_size - 1)) - 1;
1520                 int exp_val  = sc_val_to_long(_exp(a)) - exp_bias;
1521                 int shift, highest;
1522                 int mantissa_size;
1523                 int tgt_bits;
1524
1525                 if (a->sign && !mode_is_signed(dst_mode)) {
1526                         /* FIXME: for now we cannot convert this */
1527                         return 0;
1528                 }
1529
1530                 tgt_bits = get_mode_size_bits(dst_mode);
1531                 if (mode_is_signed(dst_mode))
1532                         --tgt_bits;
1533
1534                 assert(exp_val >= 0 && "floating point value not integral before fc_flt2int() call");
1535                 mantissa_size = a->desc.mantissa_size + ROUNDING_BITS;
1536                 shift         = exp_val - mantissa_size;
1537
1538                 if (tgt_bits < mantissa_size + 1)
1539                         tgt_bits = mantissa_size + 1;
1540                 if (shift > 0) {
1541                         sc_shlI(_mant(a),  shift, tgt_bits, 0, result);
1542                 } else {
1543                         sc_shrI(_mant(a), -shift, tgt_bits, 0, result);
1544                 }
1545
1546                 /* check for overflow */
1547                 highest = sc_get_highest_set_bit(result);
1548
1549                 if (mode_is_signed(dst_mode)) {
1550                         if (highest == sc_get_lowest_set_bit(result)) {
1551                                 /* need extra test for MIN_INT */
1552                                 if (highest >= (int) get_mode_size_bits(dst_mode)) {
1553                                         /* FIXME: handle overflow */
1554                                         return 0;
1555                                 }
1556                         } else {
1557                                 if (highest >= (int) get_mode_size_bits(dst_mode) - 1) {
1558                                         /* FIXME: handle overflow */
1559                                         return 0;
1560                                 }
1561                         }
1562                 } else {
1563                         if (highest >= (int) get_mode_size_bits(dst_mode)) {
1564                                 /* FIXME: handle overflow */
1565                                 return 0;
1566                         }
1567                 }
1568
1569                 if (a->sign)
1570                         sc_neg(result, result);
1571
1572                 return 1;
1573         } else if (a->clss == FC_ZERO) {
1574                 sc_zero(result);
1575                 return 1;
1576         }
1577         return 0;
1578 }
1579
1580 int fc_is_exact(void)
1581 {
1582         return fc_exact;
1583 }