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