Implement and use tarval_andnot().
[libfirm] / ir / tv / strcalc.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief    Provides basic mathematical operations on values represented as strings.
23  * @date     2003
24  * @author   Mathias Heil
25  * @version  $Id$
26  */
27 #include "config.h"
28
29 #include <stdlib.h>
30 #include <string.h>
31 #include <assert.h>
32 #include <stdio.h>
33 #include <limits.h>
34
35 #include "strcalc.h"
36 #include "xmalloc.h"
37 #include "error.h"
38
39 /*
40  * local definitions and macros
41  */
42 #define CLEAR_BUFFER(b) assert(b); memset(b, SC_0, calc_buffer_size)
43 #define _val(a) ((a)-SC_0)
44 #define _digit(a) ((a)+SC_0)
45 #define _bitisset(digit, pos) ((digit & shift_table[pos]) != SC_0)
46
47 #define fail_char(a, b, c, d) _fail_char((a), (b), (c), (d), __FILE__,  __LINE__)
48
49 /* shortcut output for debugging */
50 #  define sc_print_hex(a) sc_print((a), 0, SC_HEX, 0)
51 #  define sc_print_dec(a) sc_print((a), 0, SC_DEC, 1)
52 #  define sc_print_oct(a) sc_print((a), 0, SC_OCT, 0)
53 #  define sc_print_bin(a) sc_print((a), 0, SC_BIN, 0)
54
55 #ifdef STRCALC_DEBUG_PRINTCOMP
56 #  define DEBUGPRINTF_COMPUTATION(x) printf x
57 #else
58 #  define DEBUGPRINTF_COMPUTATION(x) ((void)0)
59 #endif
60 #ifdef STRCALC_DEBUG
61 #  define DEBUGPRINTF(x) printf x
62 #else
63 #  define DEBUGPRINTF(x) ((void)0)
64 #endif
65
66
67 /*
68  * private variables
69  */
70 static char *calc_buffer = NULL;    /* buffer holding all results */
71 static char *output_buffer = NULL;  /* buffer for output */
72 static int bit_pattern_size;        /* maximum number of bits */
73 static int calc_buffer_size;        /* size of internally stored values */
74 static int max_value_size;          /* maximum size of values */
75
76 static int carry_flag;              /**< some computation set the carry_flag:
77                                          - right shift if bits were lost due to shifting
78                                          - division if there was a remainder
79                                          However, the meaning of carry is machine dependent
80                                          and often defined in other ways! */
81
82 static const char sex_digit[4] = { SC_E, SC_C, SC_8, SC_0 };
83 static const char zex_digit[4] = { SC_1, SC_3, SC_7, SC_F };
84 static const char max_digit[4] = { SC_0, SC_1, SC_3, SC_7 };
85 static const char min_digit[4] = { SC_F, SC_E, SC_C, SC_8 };
86
87 static const char shift_table[4] = { SC_1, SC_2, SC_4, SC_8 };
88
89 static char const add_table[16][16][2] = {
90                        { {SC_0, SC_0}, {SC_1, SC_0}, {SC_2, SC_0}, {SC_3, SC_0},
91                          {SC_4, SC_0}, {SC_5, SC_0}, {SC_6, SC_0}, {SC_7, SC_0},
92                          {SC_8, SC_0}, {SC_9, SC_0}, {SC_A, SC_0}, {SC_B, SC_0},
93                          {SC_C, SC_0}, {SC_D, SC_0}, {SC_E, SC_0}, {SC_F, SC_0} },
94
95                        { {SC_1, SC_0}, {SC_2, SC_0}, {SC_3, SC_0}, {SC_4, SC_0},
96                          {SC_5, SC_0}, {SC_6, SC_0}, {SC_7, SC_0}, {SC_8, SC_0},
97                          {SC_9, SC_0}, {SC_A, SC_0}, {SC_B, SC_0}, {SC_C, SC_0},
98                          {SC_D, SC_0}, {SC_E, SC_0}, {SC_F, SC_0}, {SC_0, SC_1} },
99
100                        { {SC_2, SC_0}, {SC_3, SC_0}, {SC_4, SC_0}, {SC_5, SC_0},
101                          {SC_6, SC_0}, {SC_7, SC_0}, {SC_8, SC_0}, {SC_9, SC_0},
102                          {SC_A, SC_0}, {SC_B, SC_0}, {SC_C, SC_0}, {SC_D, SC_0},
103                          {SC_E, SC_0}, {SC_F, SC_0}, {SC_0, SC_1}, {SC_1, SC_1} },
104
105                        { {SC_3, SC_0}, {SC_4, SC_0}, {SC_5, SC_0}, {SC_6, SC_0},
106                          {SC_7, SC_0}, {SC_8, SC_0}, {SC_9, SC_0}, {SC_A, SC_0},
107                          {SC_B, SC_0}, {SC_C, SC_0}, {SC_D, SC_0}, {SC_E, SC_0},
108                          {SC_F, SC_0}, {SC_0, SC_1}, {SC_1, SC_1}, {SC_2, SC_1} },
109
110                        { {SC_4, SC_0}, {SC_5, SC_0}, {SC_6, SC_0}, {SC_7, SC_0},
111                          {SC_8, SC_0}, {SC_9, SC_0}, {SC_A, SC_0}, {SC_B, SC_0},
112                          {SC_C, SC_0}, {SC_D, SC_0}, {SC_E, SC_0}, {SC_F, SC_0},
113                          {SC_0, SC_1}, {SC_1, SC_1}, {SC_2, SC_1}, {SC_3, SC_1} },
114
115                        { {SC_5, SC_0}, {SC_6, SC_0}, {SC_7, SC_0}, {SC_8, SC_0},
116                          {SC_9, SC_0}, {SC_A, SC_0}, {SC_B, SC_0}, {SC_C, SC_0},
117                          {SC_D, SC_0}, {SC_E, SC_0}, {SC_F, SC_0}, {SC_0, SC_1},
118                          {SC_1, SC_1}, {SC_2, SC_1}, {SC_3, SC_1}, {SC_4, SC_1} },
119
120                        { {SC_6, SC_0}, {SC_7, SC_0}, {SC_8, SC_0}, {SC_9, SC_0},
121                          {SC_A, SC_0}, {SC_B, SC_0}, {SC_C, SC_0}, {SC_D, SC_0},
122                          {SC_E, SC_0}, {SC_F, SC_0}, {SC_0, SC_1}, {SC_1, SC_1},
123                          {SC_2, SC_1}, {SC_3, SC_1}, {SC_4, SC_1}, {SC_5, SC_1} },
124
125                        { {SC_7, SC_0}, {SC_8, SC_0}, {SC_9, SC_0}, {SC_A, SC_0},
126                          {SC_B, SC_0}, {SC_C, SC_0}, {SC_D, SC_0}, {SC_E, SC_0},
127                          {SC_F, SC_0}, {SC_0, SC_1}, {SC_1, SC_1}, {SC_2, SC_1},
128                          {SC_3, SC_1}, {SC_4, SC_1}, {SC_5, SC_1}, {SC_6, SC_1} },
129
130                        { {SC_8, SC_0}, {SC_9, SC_0}, {SC_A, SC_0}, {SC_B, SC_0},
131                          {SC_C, SC_0}, {SC_D, SC_0}, {SC_E, SC_0}, {SC_F, SC_0},
132                          {SC_0, SC_1}, {SC_1, SC_1}, {SC_2, SC_1}, {SC_3, SC_1},
133                          {SC_4, SC_1}, {SC_5, SC_1}, {SC_6, SC_1}, {SC_7, SC_1} },
134
135                        { {SC_9, SC_0}, {SC_A, SC_0}, {SC_B, SC_0}, {SC_C, SC_0},
136                          {SC_D, SC_0}, {SC_E, SC_0}, {SC_F, SC_0}, {SC_0, SC_1},
137                          {SC_1, SC_1}, {SC_2, SC_1}, {SC_3, SC_1}, {SC_4, SC_1},
138                          {SC_5, SC_1}, {SC_6, SC_1}, {SC_7, SC_1}, {SC_8, SC_1} },
139
140                        { {SC_A, SC_0}, {SC_B, SC_0}, {SC_C, SC_0}, {SC_D, SC_0},
141                          {SC_E, SC_0}, {SC_F, SC_0}, {SC_0, SC_1}, {SC_1, SC_1},
142                          {SC_2, SC_1}, {SC_3, SC_1}, {SC_4, SC_1}, {SC_5, SC_1},
143                          {SC_6, SC_1}, {SC_7, SC_1}, {SC_8, SC_1}, {SC_9, SC_1} },
144
145                        { {SC_B, SC_0}, {SC_C, SC_0}, {SC_D, SC_0}, {SC_E, SC_0},
146                          {SC_F, SC_0}, {SC_0, SC_1}, {SC_1, SC_1}, {SC_2, SC_1},
147                          {SC_3, SC_1}, {SC_4, SC_1}, {SC_5, SC_1}, {SC_6, SC_1},
148                          {SC_7, SC_1}, {SC_8, SC_1}, {SC_9, SC_1}, {SC_A, SC_1} },
149
150                        { {SC_C, SC_0}, {SC_D, SC_0}, {SC_E, SC_0}, {SC_F, SC_0},
151                          {SC_0, SC_1}, {SC_1, SC_1}, {SC_2, SC_1}, {SC_3, SC_1},
152                          {SC_4, SC_1}, {SC_5, SC_1}, {SC_6, SC_1}, {SC_7, SC_1},
153                          {SC_8, SC_1}, {SC_9, SC_1}, {SC_A, SC_1}, {SC_B, SC_1} },
154
155                        { {SC_D, SC_0}, {SC_E, SC_0}, {SC_F, SC_0}, {SC_0, SC_1},
156                          {SC_1, SC_1}, {SC_2, SC_1}, {SC_3, SC_1}, {SC_4, SC_1},
157                          {SC_5, SC_1}, {SC_6, SC_1}, {SC_7, SC_1}, {SC_8, SC_1},
158                          {SC_9, SC_1}, {SC_A, SC_1}, {SC_B, SC_1}, {SC_C, SC_1} },
159
160                        { {SC_E, SC_0}, {SC_F, SC_0}, {SC_0, SC_1}, {SC_1, SC_1},
161                          {SC_2, SC_1}, {SC_3, SC_1}, {SC_4, SC_1}, {SC_5, SC_1},
162                          {SC_6, SC_1}, {SC_7, SC_1}, {SC_8, SC_1}, {SC_9, SC_1},
163                          {SC_A, SC_1}, {SC_B, SC_1}, {SC_C, SC_1}, {SC_D, SC_1} },
164
165                        { {SC_F, SC_0}, {SC_0, SC_1}, {SC_1, SC_1}, {SC_2, SC_1},
166                          {SC_3, SC_1}, {SC_4, SC_1}, {SC_5, SC_1}, {SC_6, SC_1},
167                          {SC_7, SC_1}, {SC_8, SC_1}, {SC_9, SC_1}, {SC_A, SC_1},
168                          {SC_B, SC_1}, {SC_C, SC_1}, {SC_D, SC_1}, {SC_E, SC_1} }
169                              };
170
171 static char const mul_table[16][16][2] = {
172                        { {SC_0, SC_0}, {SC_0, SC_0}, {SC_0, SC_0}, {SC_0, SC_0},
173                          {SC_0, SC_0}, {SC_0, SC_0}, {SC_0, SC_0}, {SC_0, SC_0},
174                          {SC_0, SC_0}, {SC_0, SC_0}, {SC_0, SC_0}, {SC_0, SC_0},
175                          {SC_0, SC_0}, {SC_0, SC_0}, {SC_0, SC_0}, {SC_0, SC_0} },
176
177                        { {SC_0, SC_0}, {SC_1, SC_0}, {SC_2, SC_0}, {SC_3, SC_0},
178                          {SC_4, SC_0}, {SC_5, SC_0}, {SC_6, SC_0}, {SC_7, SC_0},
179                          {SC_8, SC_0}, {SC_9, SC_0}, {SC_A, SC_0}, {SC_B, SC_0},
180                          {SC_C, SC_0}, {SC_D, SC_0}, {SC_E, SC_0}, {SC_F, SC_0} },
181
182                        { {SC_0, SC_0}, {SC_2, SC_0}, {SC_4, SC_0}, {SC_6, SC_0},
183                          {SC_8, SC_0}, {SC_A, SC_0}, {SC_C, SC_0}, {SC_E, SC_0},
184                          {SC_0, SC_1}, {SC_2, SC_1}, {SC_4, SC_1}, {SC_6, SC_1},
185                          {SC_8, SC_1}, {SC_A, SC_1}, {SC_C, SC_1}, {SC_E, SC_1} },
186
187                        { {SC_0, SC_0}, {SC_3, SC_0}, {SC_6, SC_0}, {SC_9, SC_0},
188                          {SC_C, SC_0}, {SC_F, SC_0}, {SC_2, SC_1}, {SC_5, SC_1},
189                          {SC_8, SC_1}, {SC_B, SC_1}, {SC_E, SC_1}, {SC_1, SC_2},
190                          {SC_4, SC_2}, {SC_7, SC_2}, {SC_A, SC_2}, {SC_D, SC_2} },
191
192                        { {SC_0, SC_0}, {SC_4, SC_0}, {SC_8, SC_0}, {SC_C, SC_0},
193                          {SC_0, SC_1}, {SC_4, SC_1}, {SC_8, SC_1}, {SC_C, SC_1},
194                          {SC_0, SC_2}, {SC_4, SC_2}, {SC_8, SC_2}, {SC_C, SC_2},
195                          {SC_0, SC_3}, {SC_4, SC_3}, {SC_8, SC_3}, {SC_C, SC_3} },
196
197                        { {SC_0, SC_0}, {SC_5, SC_0}, {SC_A, SC_0}, {SC_F, SC_0},
198                          {SC_4, SC_1}, {SC_9, SC_1}, {SC_E, SC_1}, {SC_3, SC_2},
199                          {SC_8, SC_2}, {SC_D, SC_2}, {SC_2, SC_3}, {SC_7, SC_3},
200                          {SC_C, SC_3}, {SC_1, SC_4}, {SC_6, SC_4}, {SC_B, SC_4} },
201
202                        { {SC_0, SC_0}, {SC_6, SC_0}, {SC_C, SC_0}, {SC_2, SC_1},
203                          {SC_8, SC_1}, {SC_E, SC_1}, {SC_4, SC_2}, {SC_A, SC_2},
204                          {SC_0, SC_3}, {SC_6, SC_3}, {SC_C, SC_3}, {SC_2, SC_4},
205                          {SC_8, SC_4}, {SC_E, SC_4}, {SC_4, SC_5}, {SC_A, SC_5} },
206
207                        { {SC_0, SC_0}, {SC_7, SC_0}, {SC_E, SC_0}, {SC_5, SC_1},
208                          {SC_C, SC_1}, {SC_3, SC_2}, {SC_A, SC_2}, {SC_1, SC_3},
209                          {SC_8, SC_3}, {SC_F, SC_3}, {SC_6, SC_4}, {SC_D, SC_4},
210                          {SC_4, SC_5}, {SC_B, SC_5}, {SC_2, SC_6}, {SC_9, SC_6} },
211
212                        { {SC_0, SC_0}, {SC_8, SC_0}, {SC_0, SC_1}, {SC_8, SC_1},
213                          {SC_0, SC_2}, {SC_8, SC_2}, {SC_0, SC_3}, {SC_8, SC_3},
214                          {SC_0, SC_4}, {SC_8, SC_4}, {SC_0, SC_5}, {SC_8, SC_5},
215                          {SC_0, SC_6}, {SC_8, SC_6}, {SC_0, SC_7}, {SC_8, SC_7} },
216
217                        { {SC_0, SC_0}, {SC_9, SC_0}, {SC_2, SC_1}, {SC_B, SC_1},
218                          {SC_4, SC_2}, {SC_D, SC_2}, {SC_6, SC_3}, {SC_F, SC_3},
219                          {SC_8, SC_4}, {SC_1, SC_5}, {SC_A, SC_5}, {SC_3, SC_6},
220                          {SC_C, SC_6}, {SC_5, SC_7}, {SC_E, SC_7}, {SC_7, SC_8} },
221
222                        { {SC_0, SC_0}, {SC_A, SC_0}, {SC_4, SC_1}, {SC_E, SC_1},
223                          {SC_8, SC_2}, {SC_2, SC_3}, {SC_C, SC_3}, {SC_6, SC_4},
224                          {SC_0, SC_5}, {SC_A, SC_5}, {SC_4, SC_6}, {SC_E, SC_6},
225                          {SC_8, SC_7}, {SC_2, SC_8}, {SC_C, SC_8}, {SC_6, SC_9} },
226
227                        { {SC_0, SC_0}, {SC_B, SC_0}, {SC_6, SC_1}, {SC_1, SC_2},
228                          {SC_C, SC_2}, {SC_7, SC_3}, {SC_2, SC_4}, {SC_D, SC_4},
229                          {SC_8, SC_5}, {SC_3, SC_6}, {SC_E, SC_6}, {SC_9, SC_7},
230                          {SC_4, SC_8}, {SC_F, SC_8}, {SC_A, SC_9}, {SC_5, SC_A} },
231
232                        { {SC_0, SC_0}, {SC_C, SC_0}, {SC_8, SC_1}, {SC_4, SC_2},
233                          {SC_0, SC_3}, {SC_C, SC_3}, {SC_8, SC_4}, {SC_4, SC_5},
234                          {SC_0, SC_6}, {SC_C, SC_6}, {SC_8, SC_7}, {SC_4, SC_8},
235                          {SC_0, SC_9}, {SC_C, SC_9}, {SC_8, SC_A}, {SC_4, SC_B} },
236
237                        { {SC_0, SC_0}, {SC_D, SC_0}, {SC_A, SC_1}, {SC_7, SC_2},
238                          {SC_4, SC_3}, {SC_1, SC_4}, {SC_E, SC_4}, {SC_B, SC_5},
239                          {SC_8, SC_6}, {SC_5, SC_7}, {SC_2, SC_8}, {SC_F, SC_8},
240                          {SC_C, SC_9}, {SC_9, SC_A}, {SC_6, SC_B}, {SC_3, SC_C} },
241
242                        { {SC_0, SC_0}, {SC_E, SC_0}, {SC_C, SC_1}, {SC_A, SC_2},
243                          {SC_8, SC_3}, {SC_6, SC_4}, {SC_4, SC_5}, {SC_2, SC_6},
244                          {SC_0, SC_7}, {SC_E, SC_7}, {SC_C, SC_8}, {SC_A, SC_9},
245                          {SC_8, SC_A}, {SC_6, SC_B}, {SC_4, SC_C}, {SC_2, SC_D} },
246
247                        { {SC_0, SC_0}, {SC_F, SC_0}, {SC_E, SC_1}, {SC_D, SC_2},
248                          {SC_C, SC_3}, {SC_B, SC_4}, {SC_A, SC_5}, {SC_9, SC_6},
249                          {SC_8, SC_7}, {SC_7, SC_8}, {SC_6, SC_9}, {SC_5, SC_A},
250                          {SC_4, SC_B}, {SC_3, SC_C}, {SC_2, SC_D}, {SC_1, SC_E} }
251                              };
252
253 static char const shrs_table[16][4][2] = {
254                        { {SC_0, SC_0}, {SC_0, SC_0}, {SC_0, SC_0}, {SC_0, SC_0} },
255                        { {SC_1, SC_0}, {SC_0, SC_8}, {SC_0, SC_4}, {SC_0, SC_2} },
256                        { {SC_2, SC_0}, {SC_1, SC_0}, {SC_0, SC_8}, {SC_0, SC_4} },
257                        { {SC_3, SC_0}, {SC_1, SC_8}, {SC_0, SC_C}, {SC_0, SC_6} },
258                        { {SC_4, SC_0}, {SC_2, SC_0}, {SC_1, SC_0}, {SC_0, SC_8} },
259                        { {SC_5, SC_0}, {SC_2, SC_8}, {SC_1, SC_4}, {SC_0, SC_A} },
260                        { {SC_6, SC_0}, {SC_3, SC_0}, {SC_1, SC_8}, {SC_0, SC_C} },
261                        { {SC_7, SC_0}, {SC_3, SC_8}, {SC_1, SC_C}, {SC_0, SC_E} },
262                        { {SC_8, SC_0}, {SC_4, SC_0}, {SC_2, SC_0}, {SC_1, SC_0} },
263                        { {SC_9, SC_0}, {SC_4, SC_8}, {SC_2, SC_4}, {SC_1, SC_2} },
264                        { {SC_A, SC_0}, {SC_5, SC_0}, {SC_2, SC_8}, {SC_1, SC_4} },
265                        { {SC_B, SC_0}, {SC_5, SC_8}, {SC_2, SC_C}, {SC_1, SC_6} },
266                        { {SC_C, SC_0}, {SC_6, SC_0}, {SC_3, SC_0}, {SC_1, SC_8} },
267                        { {SC_D, SC_0}, {SC_6, SC_8}, {SC_3, SC_4}, {SC_1, SC_A} },
268                        { {SC_E, SC_0}, {SC_7, SC_0}, {SC_3, SC_8}, {SC_1, SC_C} },
269                        { {SC_F, SC_0}, {SC_7, SC_8}, {SC_3, SC_C}, {SC_1, SC_E} }
270                                    };
271
272 /** converting a digit to a binary string */
273 static const char *binary_table[16] = {
274         "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
275         "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
276 };
277
278 /*****************************************************************************
279  * private functions
280  *****************************************************************************/
281 static void _fail_char(const char *str, size_t len, const char fchar, int pos,
282                        const char *file, int line) {
283         printf("ERROR:\n");
284         printf("Unexpected character '%c' in %s:%d\n", fchar, file, line);
285         while (len-- && *str) printf("%c", *str++); printf("\n");
286         while (--pos) printf(" "); printf("^\n");
287         exit(-1);
288 }
289
290 /**
291  * implements the bitwise NOT operation
292  */
293 static void do_bitnot(const char *val, char *buffer) {
294         int counter;
295
296         for (counter = 0; counter<calc_buffer_size; counter++)
297                 buffer[counter] = val[counter] ^ SC_F;
298 }
299
300 /**
301  * implements the bitwise OR operation
302  */
303 static void do_bitor(const char *val1, const char *val2, char *buffer) {
304         int counter;
305
306         for (counter = 0; counter<calc_buffer_size; counter++)
307                 buffer[counter] = val1[counter] | val2[counter];
308 }
309
310 /**
311  * implements the bitwise eXclusive OR operation
312  */
313 static void do_bitxor(const char *val1, const char *val2, char *buffer) {
314         int counter;
315
316         for (counter = 0; counter<calc_buffer_size; counter++)
317                 buffer[counter] = val1[counter] ^ val2[counter];
318 }
319
320 /**
321  * implements the bitwise AND operation
322  */
323 static void do_bitand(const char *val1, const char *val2, char *buffer) {
324         int counter;
325
326         for (counter = 0; counter<calc_buffer_size; counter++)
327                 buffer[counter] = val1[counter] & val2[counter];
328 }
329
330 /**
331  * implements the bitwise AND not operation
332  */
333 static void do_bitandnot(const char *val1, const char *val2, char *buffer)
334 {
335         int counter;
336
337         for (counter = 0; counter < calc_buffer_size; ++counter)
338                 buffer[counter] = val1[counter] & (SC_F ^ val2[counter]);
339 }
340
341 /**
342  * returns the sign bit.
343  *
344  * @todo This implementation is wrong, as it returns the highest bit of the buffer
345  *       NOT the highest bit depending on the real mode
346  */
347 static int do_sign(const char *val) {
348         return (val[calc_buffer_size-1] <= SC_7) ? (1) : (-1);
349 }
350
351 /**
352  * returns non-zero if bit at position pos is set
353  */
354 static int do_bit(const char *val, int pos) {
355         int bit    = pos & 3;
356         int nibble = pos >> 2;
357
358         return _bitisset(val[nibble], bit);
359 }
360
361 /**
362  * Implements a fast ADD + 1
363  */
364 static void do_inc(const char *val, char *buffer) {
365         int counter = 0;
366
367         while (counter++ < calc_buffer_size) {
368                 if (*val == SC_F) {
369                         *buffer++ = SC_0;
370                         val++;
371                 } else {
372                         /* No carry here, *val != SC_F */
373                         *buffer = add_table[_val(*val)][SC_1][0];
374                         return;
375                 }
376         }
377         /* here a carry could be lost, this is intended because this should
378          * happen only when a value changes sign. */
379 }
380
381 /**
382  * Implements a unary MINUS
383  */
384 static void do_negate(const char *val, char *buffer) {
385         do_bitnot(val, buffer);
386         do_inc(buffer, buffer);
387 }
388
389 /**
390  * Implements a binary ADD
391  *
392  * @todo The implementation of carry is wrong, as it is the
393  *       calc_buffer_size carry, not the mode depending
394  */
395 static void do_add(const char *val1, const char *val2, char *buffer) {
396         int counter;
397         const char *add1, *add2;
398         char carry = SC_0;
399
400         for (counter = 0; counter < calc_buffer_size; counter++)   {
401                 add1 = add_table[_val(val1[counter])][_val(val2[counter])];
402                 add2 = add_table[_val(add1[0])][_val(carry)];
403                 /* carry might be zero */
404                 buffer[counter] = add2[0];
405                 carry = add_table[_val(add1[1])][_val(add2[1])][0];
406         }
407         carry_flag = carry != SC_0;
408 }
409
410 /**
411  * Implements a binary SUB
412  */
413 static void do_sub(const char *val1, const char *val2, char *buffer) {
414         char *temp_buffer = alloca(calc_buffer_size); /* intermediate buffer to hold -val2 */
415
416         do_negate(val2, temp_buffer);
417         do_add(val1, temp_buffer, buffer);
418 }
419
420 /**
421  * Implements a binary MUL
422  */
423 static void do_mul(const char *val1, const char *val2, char *buffer) {
424         char *temp_buffer; /* result buffer */
425         char *neg_val1;    /* abs of val1 */
426         char *neg_val2;    /* abs of val2 */
427
428         const char *mul, *add1, *add2;      /* intermediate result containers */
429         char carry = SC_0;                  /* container for carries */
430         char sign = 0;                      /* marks result sign */
431         int c_inner, c_outer;               /* loop counters */
432
433         temp_buffer = alloca(calc_buffer_size);
434         neg_val1 = alloca(calc_buffer_size);
435         neg_val2 = alloca(calc_buffer_size);
436
437         /* init result buffer to zeros */
438         memset(temp_buffer, SC_0, calc_buffer_size);
439
440         /* the multiplication works only for positive values, for negative values *
441          * it is necessary to negate them and adjust the result accordingly       */
442         if (do_sign(val1) == -1) {
443                 do_negate(val1, neg_val1);
444                 val1 = neg_val1;
445                 sign ^= 1;
446         }
447         if (do_sign(val2) == -1) {
448                 do_negate(val2, neg_val2);
449                 val2 = neg_val2;
450                 sign ^= 1;
451         }
452
453         for (c_outer = 0; c_outer < max_value_size; c_outer++) {
454                 if (val2[c_outer] != SC_0) {
455                         for (c_inner = 0; c_inner < max_value_size; c_inner++) {
456                                 /* do the following calculation:                                    *
457                                  * Add the current carry, the value at position c_outer+c_inner     *
458                                  * and the result of the multiplication of val1[c_inner] and        *
459                                  * val2[c_outer]. This is the usual pen-and-paper multiplication.   */
460
461                                 /* multiplicate the two digits */
462                                 mul = mul_table[_val(val1[c_inner])][_val(val2[c_outer])];
463                                 /* add old value to result of multiplication */
464                                 add1 = add_table[_val(temp_buffer[c_inner + c_outer])][_val(mul[0])];
465                                 /* add carry to the sum */
466                                 add2 = add_table[_val(add1[0])][_val(carry)];
467
468                                 /* all carries together result in new carry. This is always smaller *
469                                  * than the base b:                                                 *
470                                  * Both multiplicands, the carry and the value already in the temp  *
471                                  * buffer are single digits and their value is therefore at most    *
472                                  * equal to (b-1).                                                  *
473                                  * This leads to:                                                   *
474                                  * (b-1)(b-1)+(b-1)+(b-1) = b*b-1                                   *
475                                  * The tables list all operations rem b, so the carry is at most    *
476                                  * (b*b-1)rem b = -1rem b = b-1                                     */
477                                 carry = add_table[_val(mul[1])][_val(add1[1])][0];
478                                 carry = add_table[_val(carry)][_val(add2[1])][0];
479
480                                 temp_buffer[c_inner + c_outer] = add2[0];
481                         }
482
483                         /* A carry may hang over */
484                         /* c_outer is always smaller than max_value_size! */
485                         temp_buffer[max_value_size + c_outer] = carry;
486                         carry = SC_0;
487                 }
488         }
489
490         if (sign)
491                 do_negate(temp_buffer, buffer);
492         else
493                 memcpy(buffer, temp_buffer, calc_buffer_size);
494 }
495
496 /**
497  * Shift the buffer to left and add a 4 bit digit
498  */
499 static void do_push(const char digit, char *buffer) {
500         int counter;
501
502         for (counter = calc_buffer_size - 2; counter >= 0; counter--) {
503                 buffer[counter+1] = buffer[counter];
504         }
505         buffer[0] = digit;
506 }
507
508 /**
509  * Implements truncating integer division and remainder.
510  *
511  * Note: This is MOST slow
512  */
513 static void do_divmod(const char *rDividend, const char *divisor, char *quot, char *rem) {
514         const char *dividend = rDividend;
515         const char *minus_divisor;
516         char *neg_val1;
517         char *neg_val2;
518
519         char div_sign = 0;     /* remember division result sign */
520         char rem_sign = 0;     /* remember remainder result sign */
521
522         int c_dividend;      /* loop counters */
523
524         neg_val1 = alloca(calc_buffer_size);
525         neg_val2 = alloca(calc_buffer_size);
526
527         /* clear result buffer */
528         memset(quot, SC_0, calc_buffer_size);
529         memset(rem, SC_0, calc_buffer_size);
530
531         /* if the divisor is zero this won't work (quot is zero) */
532         if (sc_comp(divisor, quot) == 0) assert(0 && "division by zero!");
533
534         /* if the dividend is zero result is zero (quot is zero) */
535         if (sc_comp(dividend, quot) == 0)
536                 return;
537
538         if (do_sign(dividend) == -1) {
539                 do_negate(dividend, neg_val1);
540                 div_sign ^= 1;
541                 rem_sign ^= 1;
542                 dividend = neg_val1;
543         }
544
545         do_negate(divisor, neg_val2);
546         if (do_sign(divisor) == -1) {
547                 div_sign ^= 1;
548                 minus_divisor = divisor;
549                 divisor = neg_val2;
550         } else
551                 minus_divisor = neg_val2;
552
553         /* if divisor >= dividend division is easy
554          * (remember these are absolute values) */
555         switch (sc_comp(dividend, divisor)) {
556         case 0: /* dividend == divisor */
557                 quot[0] = SC_1;
558                 goto end;
559
560         case -1: /* dividend < divisor */
561                 memcpy(rem, dividend, calc_buffer_size);
562                 goto end;
563
564         default: /* unluckily division is necessary :( */
565                 break;
566         }
567
568         for (c_dividend = calc_buffer_size - 1; c_dividend >= 0; c_dividend--) {
569                 do_push(dividend[c_dividend], rem);
570                 do_push(SC_0, quot);
571
572                 if (sc_comp(rem, divisor) != -1) {  /* remainder >= divisor */
573                         /* subtract until the remainder becomes negative, this should
574                          * be faster than comparing remainder with divisor  */
575                         do_add(rem, minus_divisor, rem);
576
577                         while (do_sign(rem) == 1) {
578                                 quot[0] = add_table[_val(quot[0])][SC_1][0];
579                                 do_add(rem, minus_divisor, rem);
580                         }
581
582                         /* subtracted one too much */
583                         do_add(rem, divisor, rem);
584                 }
585         }
586 end:
587         /* sets carry if remainder is non-zero ??? */
588         carry_flag = !sc_is_zero(rem);
589
590         if (div_sign)
591                 do_negate(quot, quot);
592
593         if (rem_sign)
594                 do_negate(rem, rem);
595 }
596
597 /**
598  * Implements a Shift Left, which can either preserve the sign bit
599  * or not.
600  *
601  * @todo Assertions seems to be wrong
602  */
603 static void do_shl(const char *val1, char *buffer, long shift_cnt, int bitsize, unsigned is_signed) {
604         const char *shl;
605         char shift;
606         char carry = SC_0;
607
608         int counter;
609         int bitoffset = 0;
610
611         assert((shift_cnt >= 0) || (0 && "negative leftshift"));
612         assert(((do_sign(val1) != -1) || is_signed) || (0 && "unsigned mode and negative value"));
613         assert(((!_bitisset(val1[(bitsize-1)/4], (bitsize-1)%4)) || !is_signed || (do_sign(val1) == -1)) || (0 && "value is positive, should be negative"));
614         assert(((_bitisset(val1[(bitsize-1)/4], (bitsize-1)%4)) || !is_signed || (do_sign(val1) == 1)) || (0 && "value is negative, should be positive"));
615
616         /* if shifting far enough the result is zero */
617         if (shift_cnt >= bitsize) {
618                 memset(buffer, SC_0, calc_buffer_size);
619                 return;
620         }
621
622         shift = shift_table[_val(shift_cnt%4)];      /* this is 2 ** (offset % 4) */
623         shift_cnt = shift_cnt / 4;
624
625         /* shift the single digits some bytes (offset) and some bits (table)
626          * to the left */
627         for (counter = 0; counter < bitsize/4 - shift_cnt; counter++) {
628                 shl = mul_table[_val(val1[counter])][_val(shift)];
629                 buffer[counter + shift_cnt] = shl[0] | carry;
630                 carry = shl[1];
631         }
632         if (bitsize%4 > 0) {
633                 shl = mul_table[_val(val1[counter])][_val(shift)];
634                 buffer[counter + shift_cnt] = shl[0] | carry;
635                 bitoffset = counter;
636         } else {
637                 bitoffset = counter - 1;
638         }
639
640         /* fill with zeroes */
641         for (counter = 0; counter < shift_cnt; counter++)
642                 buffer[counter] = SC_0;
643
644         /* if the mode was signed, change sign when the mode's msb is now 1 */
645         shift_cnt = bitoffset + shift_cnt;
646         bitoffset = (bitsize-1) % 4;
647         if (is_signed && _bitisset(buffer[shift_cnt], bitoffset)) {
648                 /* this sets the upper bits of the leftmost digit */
649                 buffer[shift_cnt] |= min_digit[bitoffset];
650                 for (counter = shift_cnt+1; counter < calc_buffer_size; counter++) {
651                         buffer[counter] = SC_F;
652                 }
653         } else if (is_signed && !_bitisset(buffer[shift_cnt], bitoffset)) {
654                 /* this clears the upper bits of the leftmost digit */
655                 buffer[shift_cnt] &= max_digit[bitoffset];
656                 for (counter = shift_cnt+1; counter < calc_buffer_size; counter++) {
657                         buffer[counter] = SC_0;
658                 }
659         }
660 }
661
662 /**
663  * Implements a Shift Right, which can either preserve the sign bit
664  * or not.
665  *
666  * @param bitsize   bitsize of the value to be shifted
667  *
668  * @todo Assertions seems to be wrong
669  */
670 static void do_shr(const char *val1, char *buffer, long shift_cnt, int bitsize, unsigned is_signed, int signed_shift) {
671         const char *shrs;
672         char sign;
673         char msd;
674
675         int shift_mod, shift_nib;
676
677         int counter;
678         int bitoffset = 0;
679
680         assert((shift_cnt >= 0) || (0 && "negative rightshift"));
681         assert(((!_bitisset(val1[(bitsize-1)/4], (bitsize-1)%4)) || !is_signed || (do_sign(val1) == -1)) || (0 && "value is positive, should be negative"));
682         assert(((_bitisset(val1[(bitsize-1)/4], (bitsize-1)%4)) || !is_signed || (do_sign(val1) == 1)) || (0 && "value is negative, should be positive"));
683
684         sign = signed_shift && do_bit(val1, bitsize - 1) ? SC_F : SC_0;
685
686         /* if shifting far enough the result is either 0 or -1 */
687         if (shift_cnt >= bitsize) {
688                 if (!sc_is_zero(val1)) {
689                         carry_flag = 1;
690                 }
691                 memset(buffer, sign, calc_buffer_size);
692                 return;
693         }
694
695         shift_mod = shift_cnt &  3;
696         shift_nib = shift_cnt >> 2;
697
698         /* check if any bits are lost, and set carry_flag if so */
699         for (counter = 0; counter < shift_nib; ++counter) {
700                 if (val1[counter] != 0) {
701                         carry_flag = 1;
702                         break;
703                 }
704         }
705         if ((_val(val1[counter]) & ((1<<shift_mod)-1)) != 0)
706                 carry_flag = 1;
707
708         /* shift digits to the right with offset, carry and all */
709         buffer[0] = shrs_table[_val(val1[shift_nib])][shift_mod][0];
710         for (counter = 1; counter < ((bitsize + 3) >> 2) - shift_nib; counter++) {
711                 shrs = shrs_table[_val(val1[counter + shift_nib])][shift_mod];
712                 buffer[counter]      = shrs[0];
713                 buffer[counter - 1] |= shrs[1];
714         }
715
716         /* the last digit is special in regard of signed/unsigned shift */
717         bitoffset = bitsize & 3;
718         msd = sign;  /* most significant digit */
719
720         /* remove sign bits if mode was signed and this is an unsigned shift */
721         if (!signed_shift && is_signed) {
722                 msd &= max_digit[bitoffset];
723         }
724
725         shrs = shrs_table[_val(msd)][shift_mod];
726
727         /* signed shift and signed mode and negative value means all bits to the left are set */
728         if (signed_shift && sign == SC_F) {
729                 buffer[counter] = shrs[0] | min_digit[bitoffset];
730         } else {
731                 buffer[counter] = shrs[0];
732         }
733
734         if (counter > 0)
735                 buffer[counter - 1] |= shrs[1];
736
737         /* fill with SC_F or SC_0 depending on sign */
738         for (counter++; counter < calc_buffer_size; counter++) {
739                 buffer[counter] = sign;
740         }
741 }
742
743 /**
744  * Implements a Rotate Left.
745  * positive: low-order -> high order, negative other direction
746  */
747 static void do_rotl(const char *val1, char *buffer, long offset, int radius, unsigned is_signed) {
748         char *temp1, *temp2;
749         temp1 = alloca(calc_buffer_size);
750         temp2 = alloca(calc_buffer_size);
751
752         offset = offset % radius;
753
754         /* rotation by multiples of the type length is identity */
755         if (offset == 0) {
756                 memmove(buffer, val1, calc_buffer_size);
757                 return;
758         }
759
760         do_shl(val1, temp1, offset, radius, is_signed);
761         do_shr(val1, temp2, radius - offset, radius, is_signed, 0);
762         do_bitor(temp1, temp2, buffer);
763         carry_flag = 0; /* set by shr, but due to rot this is false */
764 }
765
766 /*****************************************************************************
767  * public functions, declared in strcalc.h
768  *****************************************************************************/
769 const void *sc_get_buffer(void) {
770         return (void*)calc_buffer;
771 }
772
773 int sc_get_buffer_length(void) {
774         return calc_buffer_size;
775 }
776
777 /**
778  * Do sign extension if the mode is signed, otherwise to zero extension.
779  */
780 void sign_extend(void *buffer, ir_mode *mode) {
781         char *calc_buffer = buffer;
782         int bits          = get_mode_size_bits(mode) - 1;
783         int nibble        = bits >> 2;
784         int max           = max_digit[bits & 3];
785         int i;
786
787         if (mode_is_signed(mode)) {
788                 if (calc_buffer[nibble] > max) {
789                         /* sign bit is set, we need sign expansion */
790
791                         for (i = nibble + 1; i < calc_buffer_size; ++i)
792                                 calc_buffer[i] = SC_F;
793                         calc_buffer[nibble] |= sex_digit[bits & 3];
794                 } else {
795                         /* set all bits to zero */
796                         for (i = nibble + 1; i < calc_buffer_size; ++i)
797                                 calc_buffer[i] = SC_0;
798                         calc_buffer[nibble] &= zex_digit[bits & 3];
799                 }
800         } else {
801                 /* do zero extension */
802                 for (i = nibble + 1; i < calc_buffer_size; ++i)
803                         calc_buffer[i] = SC_0;
804                 calc_buffer[nibble] &= zex_digit[bits & 3];
805         }
806 }
807
808 /* FIXME doesn't check for overflows */
809 void sc_val_from_str(const char *str, unsigned int len, void *buffer, ir_mode *mode) {
810         const char *orig_str = str;
811         unsigned int orig_len = len;
812
813         char sign = 0;
814         char *base, *val;
815
816         base = alloca(calc_buffer_size);
817         val = alloca(calc_buffer_size);
818
819         /* verify valid pointers (not null) */
820         assert(str);
821         /* a string no characters long is an error */
822         assert(len);
823
824         if (buffer == NULL) buffer = calc_buffer;
825
826         CLEAR_BUFFER(buffer);
827         CLEAR_BUFFER(base);
828         CLEAR_BUFFER(val);
829
830         /* strip leading spaces */
831         while ((len > 0) && (*str == ' ')) { len--; str++; }
832
833         /* if the first two characters are 0x or 0X -> hex
834          * if the first is a 0 -> oct
835          * else dec, strip leading -/+ and remember sign
836          *
837          * only a + or - sign is no number resulting in an error */
838         if (len >= 2) {
839                 switch (str[0]) {
840                 case '0':
841                         if (str[1] == 'x' || str[1] == 'X') { /* hex */
842                                 str += 2;
843                                 len -= 2;
844                                 base[1] = SC_1; base[0] = SC_0;
845                         } else { /* oct */
846                                 str += 1;
847                                 len -= 1;
848                                 base[1] = SC_0; base[0] = SC_8;
849                         }
850                         break;
851
852                 case '+':
853                         str += 1;
854                         len -= 1;
855                         base[1] = SC_0; base[0] = SC_A;
856                         break;
857
858                 case '-':
859                         str += 1;
860                         len -= 1;
861                         sign = 1;
862                         base[1] = SC_0; base[0] = SC_A;
863                         break;
864
865                 default: /* dec, else would have begun with 0x or 0 */
866                         base[1] = SC_0; base[0] = SC_A;
867                 }
868         } else { /* dec, else would have begun with 0x or 0 */
869                 base[1] = SC_0; base[0] = SC_A;
870         }
871
872         /* BEGIN string evaluation, from left to right */
873         while (len > 0) {
874                 switch (*str) {
875                 case 'f':
876                 case 'e':
877                 case 'd':
878                 case 'c':
879                 case 'b':
880                 case 'a':
881                         if (base[0] > SC_A || base[1] > SC_0) { /* (base > 10) */
882                                 val[0] = _digit((*str)-'a'+10);
883                         }
884                         else
885                                 fail_char(orig_str, orig_len, *str, str-orig_str+1);
886                         break;
887
888                 case 'F':
889                 case 'E':
890                 case 'D':
891                 case 'C':
892                 case 'B':
893                 case 'A':
894                         if (base[0] > SC_A || base[1] > SC_0) { /* (base > 10) */
895                                 val[0] = _digit((*str)-'A'+10);
896                         }
897                         else
898                                 fail_char(orig_str, orig_len, *str, str-orig_str+1);
899                         break;
900
901                 case '9':
902                 case '8':
903                         if (base[0] > SC_8 || base[1] > SC_0) { /* (base > 8) */
904                                 val[0] = _digit((*str)-'0');
905                         }
906                         else
907                                 fail_char(orig_str, orig_len, *str, str-orig_str+1);
908                         break;
909
910                 case '7':
911                 case '6':
912                 case '5':
913                 case '4':
914                 case '3':
915                 case '2':
916                 case '1':
917                 case '0':
918                         val[0] = _digit((*str)-'0');
919                         break;
920
921                 default:
922                         fail_char(orig_str, orig_len, *str, str-orig_str+1);
923                 } /* switch(*str) */
924
925                 /* Radix conversion from base b to base B:
926                  *  (UnUn-1...U1U0)b == ((((Un*b + Un-1)*b + ...)*b + U1)*b + U0)B */
927                 do_mul(base, calc_buffer, calc_buffer); /* multiply current value with base */
928                 do_add(val, calc_buffer, calc_buffer);  /* add next digit to current value  */
929
930                 /* get ready for the next letter */
931                 str++;
932                 len--;
933         } /* while (len > 0 ) */
934
935         if (sign)
936                 do_negate(calc_buffer, calc_buffer);
937
938         /* beware: even if hex numbers have no sign, we need sign extension here */
939         sign_extend(calc_buffer, mode);
940 }
941
942 void sc_val_from_long(long value, void *buffer) {
943         char *pos;
944         char sign, is_minlong;
945
946         if (buffer == NULL) buffer = calc_buffer;
947         pos = buffer;
948
949         sign = (value < 0);
950         is_minlong = value == LONG_MIN;
951
952         /* use absolute value, special treatment of MIN_LONG to avoid overflow */
953         if (sign) {
954                 if (is_minlong)
955                         value = -(value+1);
956                 else
957                         value = -value;
958         }
959
960         CLEAR_BUFFER(buffer);
961
962         while ((value != 0) && (pos < (char*)buffer + calc_buffer_size)) {
963                 *pos++ = _digit(value & 0xf);
964                 value >>= 4;
965         }
966
967         if (sign) {
968                 if (is_minlong)
969                         do_inc(buffer, buffer);
970
971                 do_negate(buffer, buffer);
972         }
973 }
974
975 void sc_val_from_ulong(unsigned long value, void *buffer) {
976         unsigned char *pos;
977
978         if (buffer == NULL) buffer = calc_buffer;
979         pos = buffer;
980
981         while (pos < (unsigned char *)buffer + calc_buffer_size) {
982                 *pos++ = (unsigned char)_digit(value & 0xf);
983                 value >>= 4;
984         }
985 }
986
987 long sc_val_to_long(const void *val) {
988         int i;
989         long l = 0;
990
991         for (i = calc_buffer_size - 1; i >= 0; i--) {
992                 l = (l << 4) + _val(((char *)val)[i]);
993         }
994         return l;
995 }
996
997 void sc_min_from_bits(unsigned int num_bits, unsigned int sign, void *buffer) {
998         char *pos;
999         int i, bits;
1000
1001         if (buffer == NULL) buffer = calc_buffer;
1002         CLEAR_BUFFER(buffer);
1003
1004         if (!sign) return;  /* unsigned means minimum is 0(zero) */
1005
1006         pos = buffer;
1007
1008         bits = num_bits - 1;
1009         for (i = 0; i < bits/4; i++)
1010                 *pos++ = SC_0;
1011
1012         *pos++ = min_digit[bits%4];
1013
1014         for (i++; i <= calc_buffer_size - 1; i++)
1015                 *pos++ = SC_F;
1016 }
1017
1018 void sc_max_from_bits(unsigned int num_bits, unsigned int sign, void *buffer) {
1019         char* pos;
1020         int i, bits;
1021
1022         if (buffer == NULL) buffer = calc_buffer;
1023         CLEAR_BUFFER(buffer);
1024         pos = buffer;
1025
1026         bits = num_bits - sign;
1027         for (i = 0; i < bits/4; i++)
1028                 *pos++ = SC_F;
1029
1030         *pos++ = max_digit[bits%4];
1031
1032         for (i++; i <= calc_buffer_size - 1; i++)
1033                 *pos++ = SC_0;
1034 }
1035
1036 void sc_truncate(unsigned int num_bits, void *buffer) {
1037         char *cbuffer = buffer;
1038         char *pos = cbuffer + (num_bits / 4);
1039         char *end = cbuffer + calc_buffer_size;
1040
1041         assert(pos < end);
1042
1043         switch(num_bits % 4) {
1044         case 0: /* nothing to do */ break;
1045         case 1: *pos++ &= SC_1; break;
1046         case 2: *pos++ &= SC_3; break;
1047         case 3: *pos++ &= SC_7; break;
1048         }
1049
1050         for( ; pos < end; ++pos)
1051                 *pos = SC_0;
1052 }
1053
1054 int sc_comp(const void* value1, const void* value2) {
1055         int counter = calc_buffer_size - 1;
1056         const char *val1 = (const char *)value1;
1057         const char *val2 = (const char *)value2;
1058
1059         /* compare signs first:
1060          * the loop below can only compare values of the same sign! */
1061         if (do_sign(val1) != do_sign(val2))
1062                 return (do_sign(val1) == 1)?(1):(-1);
1063
1064         /* loop until two digits differ, the values are equal if there
1065          * are no such two digits */
1066         while (val1[counter] == val2[counter]) {
1067                 counter--;
1068                 if (counter < 0) return 0;
1069         }
1070
1071         /* the leftmost digit is the most significant, so this returns
1072          * the correct result.
1073          * This implies the digit enum is ordered */
1074         return (val1[counter] > val2[counter]) ? (1) : (-1);
1075 }
1076
1077 int sc_get_highest_set_bit(const void *value) {
1078         const char *val = (const char*)value;
1079         int high, counter;
1080
1081         high = calc_buffer_size * 4 - 1;
1082
1083         for (counter = calc_buffer_size-1; counter >= 0; counter--) {
1084                 if (val[counter] == SC_0)
1085                         high -= 4;
1086                 else {
1087                         if (val[counter] > SC_7) return high;
1088                         else if (val[counter] > SC_3) return high - 1;
1089                         else if (val[counter] > SC_1) return high - 2;
1090                         else return high - 3;
1091                 }
1092         }
1093         return high;
1094 }
1095
1096 int sc_get_lowest_set_bit(const void *value) {
1097         const char *val = (const char*)value;
1098         int low, counter;
1099
1100         low = 0;
1101         for (counter = 0; counter < calc_buffer_size; counter++) {
1102                 switch (val[counter]) {
1103                 case SC_1:
1104                 case SC_3:
1105                 case SC_5:
1106                 case SC_7:
1107                 case SC_9:
1108                 case SC_B:
1109                 case SC_D:
1110                 case SC_F:
1111                         return low;
1112                 case SC_2:
1113                 case SC_6:
1114                 case SC_A:
1115                 case SC_E:
1116                         return low + 1;
1117                 case SC_4:
1118                 case SC_C:
1119                         return low + 2;
1120                 case SC_8:
1121                         return low + 3;
1122                 default:
1123                         low += 4;
1124                 }
1125         }
1126         return -1;
1127 }
1128
1129 int sc_get_bit_at(const void *value, unsigned pos) {
1130         const char *val = value;
1131         unsigned nibble = pos >> 2;
1132
1133         return (val[nibble] & shift_table[pos & 3]) != SC_0;
1134 }
1135
1136 void sc_set_bit_at(void *value, unsigned pos)
1137 {
1138         char *val = value;
1139         unsigned nibble = pos >> 2;
1140
1141         val[nibble] |= shift_table[pos & 3];
1142 }
1143
1144 int sc_is_zero(const void *value) {
1145         const char* val = (const char *)value;
1146         int counter;
1147
1148         for (counter = 0; counter < calc_buffer_size; ++counter) {
1149                 if (val[counter] != SC_0)
1150                         return 0;
1151         }
1152         return 1;
1153 }
1154
1155 int sc_is_negative(const void *value) {
1156         return do_sign(value) == -1;
1157 }
1158
1159 int sc_had_carry(void) {
1160         return carry_flag;
1161 }
1162
1163 unsigned char sc_sub_bits(const void *value, int len, unsigned byte_ofs) {
1164         const char *val = (const char *)value;
1165         int nibble_ofs  = 2 * byte_ofs;
1166         unsigned char res;
1167
1168         /* the current scheme uses one byte to store a nibble */
1169         if (4 * nibble_ofs >= len)
1170                 return 0;
1171
1172         res = _val(val[nibble_ofs]);
1173         if (len > 4 * (nibble_ofs + 1))
1174                 res |= _val(val[nibble_ofs + 1]) << 4;
1175
1176         /* kick bits outsize */
1177         if (len - 8 * byte_ofs < 8) {
1178                 res &= (1 << (len - 8 * byte_ofs)) - 1;
1179         }
1180         return res;
1181 }
1182
1183 /*
1184  * convert to a string
1185  * FIXME: Doesn't check buffer bounds
1186  */
1187 const char *sc_print(const void *value, unsigned bits, enum base_t base, int signed_mode) {
1188         static const char big_digits[]   = "0123456789ABCDEF";
1189         static const char small_digits[] = "0123456789abcdef";
1190
1191         char *base_val, *div1_res, *div2_res, *rem_res;
1192         int counter, nibbles, i, sign, mask;
1193         char x;
1194
1195         const char *val = (const char *)value;
1196         const char *p;
1197         char *m, *n, *t;
1198         char *pos;
1199         const char *digits = small_digits;
1200
1201         base_val = alloca(calc_buffer_size);
1202         div1_res = alloca(calc_buffer_size);
1203         div2_res = alloca(calc_buffer_size);
1204         rem_res  = alloca(calc_buffer_size);
1205
1206         pos = output_buffer + bit_pattern_size;
1207         *(--pos) = '\0';
1208
1209         /* special case */
1210         if (bits == 0) {
1211                 bits = bit_pattern_size;
1212 #ifdef STRCALC_DEBUG_FULLPRINT
1213                 bits <<= 1;
1214 #endif
1215         }
1216         nibbles = bits >> 2;
1217         switch (base) {
1218
1219         case SC_HEX:
1220                 digits = big_digits;
1221         case SC_hex:
1222                 for (counter = 0; counter < nibbles; ++counter) {
1223                         *(--pos) = digits[_val(val[counter])];
1224 #ifdef STRCALC_DEBUG_GROUPPRINT
1225                         if ((counter+1)%8 == 0)
1226                                 *(--pos) = ' ';
1227 #endif
1228                 }
1229
1230                 /* last nibble must be masked */
1231                 if (bits & 3) {
1232                         mask = zex_digit[(bits & 3) - 1];
1233                         x    = val[counter++] & mask;
1234                         *(--pos) = digits[_val(x)];
1235                 }
1236
1237                 /* now kill zeros */
1238                 for (; counter > 1; --counter, ++pos) {
1239 #ifdef STRCALC_DEBUG_GROUPPRINT
1240                         if (pos[0] == ' ') ++pos;
1241 #endif
1242                         if (pos[0] != '0')
1243                                 break;
1244                 }
1245                 break;
1246
1247         case SC_BIN:
1248                 for (counter = 0; counter < nibbles; ++counter) {
1249                         pos -= 4;
1250                         p = binary_table[_val(val[counter])];
1251                         pos[0] = p[0];
1252                         pos[1] = p[1];
1253                         pos[2] = p[2];
1254                         pos[3] = p[3];
1255                 }
1256
1257                 /* last nibble must be masked */
1258                 if (bits & 3) {
1259                         mask = zex_digit[(bits & 3) - 1];
1260                         x    = val[counter++] & mask;
1261
1262                         pos -= 4;
1263                         p = binary_table[_val(x)];
1264                         pos[0] = p[0];
1265                         pos[1] = p[1];
1266                         pos[2] = p[2];
1267                         pos[3] = p[3];
1268                 }
1269
1270                 /* now kill zeros */
1271                 for (counter <<= 2; counter > 1; --counter, ++pos)
1272                         if (pos[0] != '0')
1273                                 break;
1274                         break;
1275
1276         case SC_DEC:
1277         case SC_OCT:
1278                 memset(base_val, SC_0, calc_buffer_size);
1279                 base_val[0] = base == SC_DEC ? SC_A : SC_8;
1280
1281                 p    = val;
1282                 sign = 0;
1283                 if (signed_mode && base == SC_DEC) {
1284                         /* check for negative values */
1285                         if (do_bit(val, bits - 1)) {
1286                                 do_negate(val, div2_res);
1287                                 sign = 1;
1288                                 p = div2_res;
1289                         }
1290                 }
1291
1292                 /* transfer data into oscillating buffers */
1293                 memset(div1_res, SC_0, calc_buffer_size);
1294                 for (counter = 0; counter < nibbles; ++counter)
1295                         div1_res[counter] = p[counter];
1296
1297                 /* last nibble must be masked */
1298                 if (bits & 3) {
1299                         mask = zex_digit[(bits & 3) - 1];
1300                         div1_res[counter] = p[counter] & mask;
1301                         ++counter;
1302                 }
1303
1304                 m = div1_res;
1305                 n = div2_res;
1306                 for (;;) {
1307                         do_divmod(m, base_val, n, rem_res);
1308                         t = m;
1309                         m = n;
1310                         n = t;
1311                         *(--pos) = digits[_val(rem_res[0])];
1312
1313                         x = 0;
1314                         for (i = 0; i < calc_buffer_size; ++i)
1315                                 x |= _val(m[i]);
1316
1317                         if (x == 0)
1318                                 break;
1319                 }
1320                 if (sign)
1321                         *(--pos) = '-';
1322                 break;
1323
1324         default:
1325                 panic("Unsupported base %d", base);
1326         }
1327         return pos;
1328 }
1329
1330 void init_strcalc(int precision) {
1331         if (calc_buffer == NULL) {
1332                 if (precision <= 0) precision = SC_DEFAULT_PRECISION;
1333
1334                 /* round up to multiple of 4 */
1335                 precision = (precision + 3) & ~3;
1336
1337                 bit_pattern_size = (precision);
1338                 calc_buffer_size = (precision / 2);
1339                 max_value_size   = (precision / 4);
1340
1341                 calc_buffer   = XMALLOCN(char, calc_buffer_size + 1);
1342                 output_buffer = XMALLOCN(char, bit_pattern_size + 1);
1343
1344                 DEBUGPRINTF(("init strcalc: \n\tPRECISION: %d\n\tCALC_BUFFER_SIZE = %d\n\tMAX_VALUE_SIZE = %d\n\tbuffer pointer: %p\n", precision, calc_buffer_size, max_value_size, calc_buffer));
1345         }
1346 }
1347
1348
1349 void finish_strcalc(void) {
1350         free(calc_buffer);   calc_buffer   = NULL;
1351         free(output_buffer); output_buffer = NULL;
1352 }
1353
1354 int sc_get_precision(void) {
1355         return bit_pattern_size;
1356 }
1357
1358
1359 void sc_add(const void *value1, const void *value2, void *buffer) {
1360         CLEAR_BUFFER(calc_buffer);
1361         carry_flag = 0;
1362
1363         DEBUGPRINTF_COMPUTATION(("%s + ", sc_print_hex(value1)));
1364         DEBUGPRINTF_COMPUTATION(("%s -> ", sc_print_hex(value2)));
1365
1366         do_add(value1, value2, calc_buffer);
1367
1368         DEBUGPRINTF_COMPUTATION(("%s\n", sc_print_hex(calc_buffer)));
1369
1370         if ((buffer != NULL) && (buffer != calc_buffer)) {
1371                 memcpy(buffer, calc_buffer, calc_buffer_size);
1372         }
1373 }
1374
1375 void sc_sub(const void *value1, const void *value2, void *buffer) {
1376         CLEAR_BUFFER(calc_buffer);
1377         carry_flag = 0;
1378
1379         DEBUGPRINTF_COMPUTATION(("%s - ", sc_print_hex(value1)));
1380         DEBUGPRINTF_COMPUTATION(("%s -> ", sc_print_hex(value2)));
1381
1382         do_sub(value1, value2, calc_buffer);
1383
1384         DEBUGPRINTF_COMPUTATION(("%s\n", sc_print_hex(calc_buffer)));
1385
1386         if ((buffer != NULL) && (buffer != calc_buffer)) {
1387                 memcpy(buffer, calc_buffer, calc_buffer_size);
1388         }
1389 }
1390
1391 void sc_neg(const void *value1, void *buffer) {
1392         carry_flag = 0;
1393
1394         DEBUGPRINTF_COMPUTATION(("- %s ->", sc_print_hex(value1)));
1395
1396         do_negate(value1, calc_buffer);
1397
1398         DEBUGPRINTF_COMPUTATION(("%s\n", sc_print_hex(calc_buffer)));
1399
1400         if ((buffer != NULL) && (buffer != calc_buffer)) {
1401                 memcpy(buffer, calc_buffer, calc_buffer_size);
1402         }
1403 }
1404
1405 void sc_and(const void *value1, const void *value2, void *buffer) {
1406         CLEAR_BUFFER(calc_buffer);
1407         carry_flag = 0;
1408
1409         DEBUGPRINTF_COMPUTATION(("%s & ", sc_print_hex(value1)));
1410         DEBUGPRINTF_COMPUTATION(("%s -> ", sc_print_hex(value2)));
1411
1412         do_bitand(value1, value2, calc_buffer);
1413
1414         DEBUGPRINTF_COMPUTATION(("%s\n", sc_print_hex(calc_buffer)));
1415
1416         if ((buffer != NULL) && (buffer != calc_buffer)) {
1417                 memcpy(buffer, calc_buffer, calc_buffer_size);
1418         }
1419 }
1420
1421 void sc_andnot(const void *value1, const void *value2, void *buffer)
1422 {
1423         CLEAR_BUFFER(calc_buffer);
1424         carry_flag = 0;
1425
1426         DEBUGPRINTF_COMPUTATION(("%s & ", sc_print_hex(value1)));
1427         DEBUGPRINTF_COMPUTATION(("~%s -> ", sc_print_hex(value2)));
1428
1429         do_bitandnot(value1, value2, calc_buffer);
1430
1431         DEBUGPRINTF_COMPUTATION(("%s\n", sc_print_hex(calc_buffer)));
1432
1433         if (buffer != NULL && buffer != calc_buffer) {
1434                 memcpy(buffer, calc_buffer, calc_buffer_size);
1435         }
1436 }
1437
1438 void sc_or(const void *value1, const void *value2, void *buffer) {
1439         CLEAR_BUFFER(calc_buffer);
1440         carry_flag = 0;
1441
1442         DEBUGPRINTF_COMPUTATION(("%s | ", sc_print_hex(value1)));
1443         DEBUGPRINTF_COMPUTATION(("%s -> ", sc_print_hex(value2)));
1444
1445         do_bitor(value1, value2, calc_buffer);
1446
1447         DEBUGPRINTF_COMPUTATION(("%s\n", sc_print_hex(calc_buffer)));
1448
1449         if ((buffer != NULL) && (buffer != calc_buffer)) {
1450                 memcpy(buffer, calc_buffer, calc_buffer_size);
1451         }
1452 }
1453
1454 void sc_xor(const void *value1, const void *value2, void *buffer) {
1455         CLEAR_BUFFER(calc_buffer);
1456         carry_flag = 0;
1457
1458         DEBUGPRINTF_COMPUTATION(("%s ^ ", sc_print_hex(value1)));
1459         DEBUGPRINTF_COMPUTATION(("%s -> ", sc_print_hex(value2)));
1460
1461         do_bitxor(value1, value2, calc_buffer);
1462
1463         DEBUGPRINTF_COMPUTATION(("%s\n", sc_print_hex(calc_buffer)));
1464
1465         if ((buffer != NULL) && (buffer != calc_buffer)) {
1466                 memcpy(buffer, calc_buffer, calc_buffer_size);
1467         }
1468 }
1469
1470 void sc_not(const void *value1, void *buffer) {
1471         CLEAR_BUFFER(calc_buffer);
1472         carry_flag = 0;
1473
1474         DEBUGPRINTF_COMPUTATION(("~ %s ->", sc_print_hex(value1)));
1475
1476         do_bitnot(value1, calc_buffer);
1477
1478         DEBUGPRINTF_COMPUTATION(("%s\n", sc_print_hex(calc_buffer)));
1479
1480         if ((buffer != NULL) && (buffer != calc_buffer)) {
1481                 memcpy(buffer, calc_buffer, calc_buffer_size);
1482         }
1483 }
1484
1485 void sc_mul(const void *value1, const void *value2, void *buffer) {
1486         CLEAR_BUFFER(calc_buffer);
1487         carry_flag = 0;
1488
1489         DEBUGPRINTF_COMPUTATION(("%s * ", sc_print_hex(value1)));
1490         DEBUGPRINTF_COMPUTATION(("%s -> ", sc_print_hex(value2)));
1491
1492         do_mul(value1, value2, calc_buffer);
1493
1494         DEBUGPRINTF_COMPUTATION(("%s\n", sc_print_hex(calc_buffer)));
1495
1496         if ((buffer != NULL) && (buffer != calc_buffer)) {
1497                 memcpy(buffer, calc_buffer, calc_buffer_size);
1498         }
1499 }
1500
1501 void sc_div(const void *value1, const void *value2, void *buffer) {
1502         /* temp buffer holding unused result of divmod */
1503         char *unused_res = alloca(calc_buffer_size);
1504
1505         CLEAR_BUFFER(calc_buffer);
1506         carry_flag = 0;
1507
1508         DEBUGPRINTF_COMPUTATION(("%s / ", sc_print_hex(value1)));
1509         DEBUGPRINTF_COMPUTATION(("%s -> ", sc_print_hex(value2)));
1510
1511         do_divmod(value1, value2, calc_buffer, unused_res);
1512
1513         DEBUGPRINTF_COMPUTATION(("%s\n", sc_print_hex(calc_buffer)));
1514
1515         if ((buffer != NULL) && (buffer != calc_buffer)) {
1516                 memcpy(buffer, calc_buffer, calc_buffer_size);
1517         }
1518 }
1519
1520 void sc_mod(const void *value1, const void *value2, void *buffer) {
1521         /* temp buffer holding unused result of divmod */
1522         char *unused_res = alloca(calc_buffer_size);
1523
1524         CLEAR_BUFFER(calc_buffer);
1525         carry_flag = 0;
1526
1527         DEBUGPRINTF_COMPUTATION(("%s %% ", sc_print_hex(value1)));
1528         DEBUGPRINTF_COMPUTATION(("%s -> ", sc_print_hex(value2)));
1529
1530         do_divmod(value1, value2, unused_res, calc_buffer);
1531
1532         DEBUGPRINTF_COMPUTATION(("%s\n", sc_print_hex(calc_buffer)));
1533
1534         if ((buffer != NULL) && (buffer != calc_buffer)) {
1535                 memcpy(buffer, calc_buffer, calc_buffer_size);
1536         }
1537 }
1538
1539 void sc_divmod(const void *value1, const void *value2, void *div_buffer, void *mod_buffer) {
1540         CLEAR_BUFFER(calc_buffer);
1541         carry_flag = 0;
1542
1543         DEBUGPRINTF_COMPUTATION(("%s %% ", sc_print_hex(value1)));
1544         DEBUGPRINTF_COMPUTATION(("%s -> ", sc_print_hex(value2)));
1545
1546         do_divmod(value1, value2, div_buffer, mod_buffer);
1547
1548         DEBUGPRINTF_COMPUTATION(("%s:%s\n", sc_print_hex(div_buffer), sc_print_hex(mod_buffer)));
1549 }
1550
1551
1552 void sc_shlI(const void *val1, long shift_cnt, int bitsize, int sign, void *buffer) {
1553         carry_flag = 0;
1554
1555         DEBUGPRINTF_COMPUTATION(("%s << %ld ", sc_print_hex(value1), shift_cnt));
1556         do_shl(val1, calc_buffer, shift_cnt, bitsize, sign);
1557
1558         DEBUGPRINTF_COMPUTATION(("-> %s\n", sc_print_hex(calc_buffer)));
1559
1560         if ((buffer != NULL) && (buffer != calc_buffer)) {
1561                 memmove(buffer, calc_buffer, calc_buffer_size);
1562         }
1563 }
1564
1565 void sc_shl(const void *val1, const void *val2, int bitsize, int sign, void *buffer) {
1566         long offset = sc_val_to_long(val2);
1567
1568         sc_shlI(val1, offset, bitsize, sign, buffer);
1569 }
1570
1571 void sc_shrI(const void *val1, long shift_cnt, int bitsize, int sign, void *buffer) {
1572         carry_flag = 0;
1573
1574         DEBUGPRINTF_COMPUTATION(("%s >>u %ld ", sc_print_hex(value1), shift_cnt));
1575         do_shr(val1, calc_buffer, shift_cnt, bitsize, sign, 0);
1576
1577         DEBUGPRINTF_COMPUTATION(("-> %s\n", sc_print_hex(calc_buffer)));
1578
1579         if ((buffer != NULL) && (buffer != calc_buffer)) {
1580                 memmove(buffer, calc_buffer, calc_buffer_size);
1581         }
1582 }
1583
1584 void sc_shr(const void *val1, const void *val2, int bitsize, int sign, void *buffer) {
1585         long shift_cnt = sc_val_to_long(val2);
1586
1587         sc_shrI(val1, shift_cnt, bitsize, sign, buffer);
1588 }
1589
1590 void sc_shrs(const void *val1, const void *val2, int bitsize, int sign, void *buffer) {
1591         long offset = sc_val_to_long(val2);
1592
1593         carry_flag = 0;
1594
1595         DEBUGPRINTF_COMPUTATION(("%s >>s %ld ", sc_print_hex(value1), offset));
1596         do_shr(val1, calc_buffer, offset, bitsize, sign, 1);
1597
1598         DEBUGPRINTF_COMPUTATION(("-> %s\n", sc_print_hex(calc_buffer)));
1599
1600         if ((buffer != NULL) && (buffer != calc_buffer)) {
1601                 memmove(buffer, calc_buffer, calc_buffer_size);
1602         }
1603 }
1604
1605 void sc_rotl(const void *val1, const void *val2, int bitsize, int sign, void *buffer) {
1606         long offset = sc_val_to_long(val2);
1607
1608         carry_flag = 0;
1609
1610         DEBUGPRINTF_COMPUTATION(("%s <<>> %ld ", sc_print_hex(value1), offset));
1611         do_rotl(val1, calc_buffer, offset, bitsize, sign);
1612
1613         DEBUGPRINTF_COMPUTATION(("-> %s\n", sc_print_hex(calc_buffer)));
1614
1615         if ((buffer != NULL) && (buffer != calc_buffer)) {
1616                 memmove(buffer, calc_buffer, calc_buffer_size);
1617         }
1618 }
1619
1620 void sc_zero(void *buffer) {
1621         if (buffer == NULL)
1622                 buffer = calc_buffer;
1623         CLEAR_BUFFER(buffer);
1624         carry_flag = 0;
1625 }