]> git.xonotic.org Git - xonotic/gmqcc.git/blob - fold.cpp
sanitize: shift 1u (unsigned) for flag bits
[xonotic/gmqcc.git] / fold.cpp
1 #include <string.h>
2 #include <math.h>
3
4 #include "fold.h"
5 #include "ast.h"
6 #include "ir.h"
7
8 #include "parser.h"
9
10 #define FOLD_STRING_UNTRANSLATE_HTSIZE 1024
11 #define FOLD_STRING_DOTRANSLATE_HTSIZE 1024
12
13 /* The options to use for inexact and arithmetic exceptions */
14 #define FOLD_ROUNDING SFLOAT_ROUND_NEAREST_EVEN
15 #define FOLD_TINYNESS SFLOAT_TBEFORE
16
17 /*
18  * Comparing float values is an unsafe operation when the operands to the
19  * comparison are floating point values that are inexact. For instance 1/3 is an
20  * inexact value. The FPU is meant to raise exceptions when these sorts of things
21  * happen, including division by zero, underflows and overflows. The C standard
22  * library provides us with the <fenv.h> header to gain access to the floating-
23  * point environment and lets us set the rounding mode and check for these exceptions.
24  * The problem is the standard C library allows an implementation to leave these
25  * stubbed out and does not require they be implemented. Furthermore, depending
26  * on implementations there is no control over the FPU. This is an IEE 754
27  * conforming implementation in software to compensate.
28  */
29 typedef uint32_t sfloat_t;
30
31 union sfloat_cast_t {
32     qcfloat_t f;
33     sfloat_t s;
34 };
35
36 /* Exception flags */
37 enum sfloat_exceptionflags_t {
38     SFLOAT_NOEXCEPT  = 0,
39     SFLOAT_INVALID   = 1,
40     SFLOAT_DIVBYZERO = 4,
41     SFLOAT_OVERFLOW  = 8,
42     SFLOAT_UNDERFLOW = 16,
43     SFLOAT_INEXACT   = 32
44 };
45
46 /* Rounding modes */
47 enum sfloat_roundingmode_t {
48     SFLOAT_ROUND_NEAREST_EVEN,
49     SFLOAT_ROUND_DOWN,
50     SFLOAT_ROUND_UP,
51     SFLOAT_ROUND_TO_ZERO
52 };
53
54 /* Underflow tininess-detection mode */
55 enum sfloat_tdetect_t {
56     SFLOAT_TAFTER,
57     SFLOAT_TBEFORE
58 };
59
60 struct sfloat_state_t {
61     sfloat_roundingmode_t roundingmode;
62     sfloat_exceptionflags_t exceptionflags;
63     sfloat_tdetect_t tiny;
64 };
65
66 /* Counts the number of leading zero bits before the most-significand one bit. */
67 #ifdef _MSC_VER
68 /* MSVC has an intrinsic for this */
69     static GMQCC_INLINE uint32_t sfloat_clz(uint32_t x) {
70         int r = 0;
71         _BitScanForward(&r, x);
72         return r;
73     }
74 #   define SFLOAT_CLZ(X, SUB) \
75         (sfloat_clz((X)) - (SUB))
76 #elif defined(__GNUC__) || defined(__CLANG__)
77 /* Clang and GCC have a builtin for this */
78 #   define SFLOAT_CLZ(X, SUB) \
79         (__builtin_clz((X)) - (SUB))
80 #else
81 /* Native fallback */
82     static GMQCC_INLINE uint32_t sfloat_popcnt(uint32_t x) {
83         x -= ((x >> 1) & 0x55555555);
84         x  = (((x >> 2) & 0x33333333) + (x & 0x33333333));
85         x  = (((x >> 4) + x) & 0x0F0F0F0F);
86         x += x >> 8;
87         x += x >> 16;
88         return x & 0x0000003F;
89     }
90     static GMQCC_INLINE uint32_t sfloat_clz(uint32_t x) {
91         x |= (x >> 1);
92         x |= (x >> 2);
93         x |= (x >> 4);
94         x |= (x >> 8);
95         x |= (x >> 16);
96         return 32 - sfloat_popcnt(x);
97     }
98 #   define SFLOAT_CLZ(X, SUB) \
99         (sfloat_clz((X) - (SUB)))
100 #endif
101
102 /* The value of a NaN */
103 #define SFLOAT_NAN 0xFFFFFFFF
104 /* Test if NaN */
105 #define SFLOAT_ISNAN(A) \
106     (0xFF000000 < (uint32_t)((A) << 1))
107 /* Test if signaling NaN */
108 #define SFLOAT_ISSNAN(A) \
109     (((((A) >> 22) & 0x1FF) == 0x1FE) && ((A) & 0x003FFFFF))
110 /* Raise exception */
111 #define SFLOAT_RAISE(STATE, FLAGS) \
112     ((STATE)->exceptionflags = (sfloat_exceptionflags_t)((STATE)->exceptionflags | (FLAGS)))
113 /*
114  * Shifts `A' right by the number of bits given in `COUNT'. If any non-zero bits
115  * are shifted off they are forced into the least significand bit of the result
116  * by setting it to one. As a result of this, the value of `COUNT' can be
117  * arbitrarily large; if `COUNT' is greater than 32, the result will be either
118  * zero or one, depending on whether `A' is a zero or non-zero. The result is
119  * stored into the value pointed by `Z'.
120  */
121 #define SFLOAT_SHIFT(SIZE, A, COUNT, Z)                                      \
122     *(Z) = ((COUNT) == 0)                                                    \
123         ? 1                                                                  \
124         : (((COUNT) < (SIZE))                                                \
125             ? ((A) >> (COUNT)) | (((A) << ((-(COUNT)) & ((SIZE) - 1))) != 0) \
126             : ((A) != 0))
127
128 /* Extract fractional component */
129 #define SFLOAT_EXTRACT_FRAC(X) \
130     ((uint32_t)((X) & 0x007FFFFF))
131 /* Extract exponent component */
132 #define SFLOAT_EXTRACT_EXP(X) \
133     ((int16_t)((X) >> 23) & 0xFF)
134 /* Extract sign bit */
135 #define SFLOAT_EXTRACT_SIGN(X) \
136     ((X) >> 31)
137 /*
138  * Normalizes the subnormal value represented by the denormalized significand
139  * `SA'. The normalized exponent and significand are stored at the locations
140  * pointed by `Z' and `SZ' respectively.
141  */
142 #define SFLOAT_SUBNORMALIZE(SA, Z, SZ) \
143     (void)(*(SZ) = (SA) << SFLOAT_CLZ((SA), 8), *(Z) = 1 - SFLOAT_CLZ((SA), 8))
144 /*
145  * Packs the sign `SIGN', exponent `EXP' and significand `SIG' into the value
146  * giving the result.
147  *
148  * After the shifting into their proper positions, the fields are added together
149  * to form the result. This means any integer portion of `SIG' will be added
150  * to the exponent. Similarly, because a properly normalized significand will
151  * always have an integer portion equal to one, the exponent input `EXP' should
152  * be one less than the desired result exponent whenever the significant input
153  * `SIG' is a complete, normalized significand.
154  */
155 #define SFLOAT_PACK(SIGN, EXP, SIG) \
156     (sfloat_t)((((uint32_t)(SIGN)) << 31) + (((uint32_t)(EXP)) << 23) + (SIG))
157
158 /*
159  * Takes two values `a' and `b', one of which is a NaN, and returns the appropriate
160  * NaN result. If either `a' or `b' is a signaling NaN than an invalid exception is
161  * raised.
162  */
163 static sfloat_t sfloat_propagate_nan(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
164     bool isnan_a  = SFLOAT_ISNAN(a);
165     bool issnan_a = SFLOAT_ISSNAN(a);
166     bool isnan_b  = SFLOAT_ISNAN(b);
167     bool issnan_b = SFLOAT_ISSNAN(b);
168
169     a |= 0x00400000;
170     b |= 0x00400000;
171
172     if (issnan_a | issnan_b)
173         SFLOAT_RAISE(state, SFLOAT_INVALID);
174     if (isnan_a)
175         return (issnan_a & isnan_b) ? b : a;
176     return b;
177 }
178
179 /*
180  * Takes an abstract value having sign `sign_z', exponent `exp_z', and significand
181  * `sig_z' and returns the appropriate value corresponding to the abstract input.
182  *
183  * The abstract value is simply rounded and packed into the format. If the abstract
184  * input cannot be represented exactly an inexact exception is raised. If the
185  * abstract input is too large, the overflow and inexact exceptions are both raised
186  * and an infinity or maximal finite value is returned. If the abstract value is
187  * too small, the value is rounded to a subnormal and the underflow and inexact
188  * exceptions are only raised if the value cannot be represented exactly with
189  * a subnormal.
190  *
191  * The input significand `sig_z' has it's binary point between bits 30 and 29,
192  * this is seven bits to the left of its usual location. The shifted significand
193  * must be normalized or smaller than this. If it's not normalized then the exponent
194  * `exp_z' must be zero; in that case, the result returned is a subnormal number
195  * which must not require rounding. In the more usual case where the significand
196  * is normalized, the exponent must be one less than the *true* exponent.
197  *
198  * The handling of underflow and overflow is otherwise in alignment with IEC/IEEE.
199  */
200 static sfloat_t SFLOAT_PACK_round(sfloat_state_t *state, bool sign_z, int16_t exp_z, uint32_t sig_z) {
201     sfloat_roundingmode_t mode      = state->roundingmode;
202     bool                  even      = !!(mode == SFLOAT_ROUND_NEAREST_EVEN);
203     unsigned char         increment = 0x40;
204     unsigned char         bits      = sig_z & 0x7F;
205
206     if (!even) {
207         if (mode == SFLOAT_ROUND_TO_ZERO)
208             increment = 0;
209         else {
210             increment = 0x7F;
211             if (sign_z) {
212                 if (mode == SFLOAT_ROUND_UP)
213                     increment = 0;
214             } else {
215                 if (mode == SFLOAT_ROUND_DOWN)
216                     increment = 0;
217             }
218         }
219     }
220
221     if (0xFD <= (uint16_t)exp_z) {
222         if ((0xFD < exp_z) || ((exp_z == 0xFD) && ((int32_t)(sig_z + increment) < 0))) {
223             SFLOAT_RAISE(state, SFLOAT_OVERFLOW | SFLOAT_INEXACT);
224             return SFLOAT_PACK(sign_z, 0xFF, 0) - (increment == 0);
225         }
226         if (exp_z < 0) {
227             /* Check for underflow */
228             bool tiny = (state->tiny == SFLOAT_TBEFORE) || (exp_z < -1) || (sig_z + increment < 0x80000000);
229             SFLOAT_SHIFT(32, sig_z, -exp_z, &sig_z);
230             exp_z = 0;
231             bits = sig_z & 0x7F;
232             if (tiny && bits)
233                 SFLOAT_RAISE(state, SFLOAT_UNDERFLOW);
234         }
235     }
236     if (bits)
237         SFLOAT_RAISE(state, SFLOAT_INEXACT);
238     sig_z = (sig_z + increment) >> 7;
239     sig_z &= ~(((bits ^ 0x40) == 0) & even);
240     if (sig_z == 0)
241         exp_z = 0;
242     return SFLOAT_PACK(sign_z, exp_z, sig_z);
243 }
244
245 /*
246  * Takes an abstract value having sign `sign_z', exponent `exp_z' and significand
247  * `sig_z' and returns the appropriate value corresponding to the abstract input.
248  * This function is exactly like `PACK_round' except the significand does not have
249  * to be normalized.
250  *
251  * Bit 31 of the significand must be zero and the exponent must be one less than
252  * the *true* exponent.
253  */
254 static sfloat_t SFLOAT_PACK_normal(sfloat_state_t *state, bool sign_z, int16_t exp_z, uint32_t sig_z) {
255     unsigned char c = SFLOAT_CLZ(sig_z, 1);
256     return SFLOAT_PACK_round(state, sign_z, exp_z - c, sig_z << c);
257 }
258
259 /*
260  * Returns the result of adding the absolute values of `a' and `b'. The sign
261  * `sign_z' is ignored if the result is a NaN.
262  */
263 static sfloat_t sfloat_add_impl(sfloat_state_t *state, sfloat_t a, sfloat_t b, bool sign_z) {
264     int16_t  exp_a = SFLOAT_EXTRACT_EXP(a);
265     int16_t  exp_b = SFLOAT_EXTRACT_EXP(b);
266     int16_t  exp_z = 0;
267     int16_t  exp_d = exp_a - exp_b;
268     uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a) << 6;
269     uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b) << 6;
270     uint32_t sig_z = 0;
271
272     if (0 < exp_d) {
273         if (exp_a == 0xFF)
274             return sig_a ? sfloat_propagate_nan(state, a, b) : a;
275         if (exp_b == 0)
276             --exp_d;
277         else
278             sig_b |= 0x20000000;
279         SFLOAT_SHIFT(32, sig_b, exp_d, &sig_b);
280         exp_z = exp_a;
281     } else if (exp_d < 0) {
282         if (exp_b == 0xFF)
283             return sig_b ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z, 0xFF, 0);
284         if (exp_a == 0)
285             ++exp_d;
286         else
287             sig_a |= 0x20000000;
288         SFLOAT_SHIFT(32, sig_a, -exp_d, &sig_a);
289         exp_z = exp_b;
290     } else {
291         if (exp_a == 0xFF)
292             return (sig_a | sig_b) ? sfloat_propagate_nan(state, a, b) : a;
293         if (exp_a == 0)
294             return SFLOAT_PACK(sign_z, 0, (sig_a + sig_b) >> 6);
295         sig_z = 0x40000000 + sig_a + sig_b;
296         exp_z = exp_a;
297         goto end;
298     }
299     sig_a |= 0x20000000;
300     sig_z = (sig_a + sig_b) << 1;
301     --exp_z;
302     if ((int32_t)sig_z < 0) {
303         sig_z = sig_a + sig_b;
304         ++exp_z;
305     }
306 end:
307     return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
308 }
309
310 /*
311  * Returns the result of subtracting the absolute values of `a' and `b'. If the
312  * sign `sign_z' is one, the difference is negated before being returned. The
313  * sign is ignored if the result is a NaN.
314  */
315 static sfloat_t sfloat_sub_impl(sfloat_state_t *state, sfloat_t a, sfloat_t b, bool sign_z) {
316     int16_t  exp_a = SFLOAT_EXTRACT_EXP(a);
317     int16_t  exp_b = SFLOAT_EXTRACT_EXP(b);
318     int16_t  exp_z = 0;
319     int16_t  exp_d = exp_a - exp_b;
320     uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a) << 7;
321     uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b) << 7;
322     uint32_t sig_z = 0;
323
324     if (0 < exp_d) goto exp_greater_a;
325     if (exp_d < 0) goto exp_greater_b;
326
327     if (exp_a == 0xFF) {
328         if (sig_a | sig_b)
329             return sfloat_propagate_nan(state, a, b);
330         SFLOAT_RAISE(state, SFLOAT_INVALID);
331         return SFLOAT_NAN;
332     }
333
334     if (exp_a == 0)
335         exp_a = exp_b = 1;
336
337     if (sig_b < sig_a) goto greater_a;
338     if (sig_a < sig_b) goto greater_b;
339
340     return SFLOAT_PACK(state->roundingmode == SFLOAT_ROUND_DOWN, 0, 0);
341
342 exp_greater_b:
343     if (exp_b == 0xFF)
344         return (sig_b) ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z ^ 1, 0xFF, 0);
345     if (exp_a == 0)
346         ++exp_d;
347     else
348         sig_a |= 0x40000000;
349     SFLOAT_SHIFT(32, sig_a, -exp_d, &sig_a);
350     sig_b |= 0x40000000;
351 greater_b:
352     sig_z = sig_b - sig_a;
353     exp_z = exp_b;
354     sign_z ^= 1;
355     goto end;
356
357 exp_greater_a:
358     if (exp_a == 0xFF)
359         return (sig_a) ? sfloat_propagate_nan(state, a, b) : a;
360     if (exp_b == 0)
361         --exp_d;
362     else
363         sig_b |= 0x40000000;
364     SFLOAT_SHIFT(32, sig_b, exp_d, &sig_b);
365     sig_a |= 0x40000000;
366 greater_a:
367     sig_z = sig_a - sig_b;
368     exp_z = exp_a;
369
370 end:
371     --exp_z;
372     return SFLOAT_PACK_normal(state, sign_z, exp_z, sig_z);
373 }
374
375 static GMQCC_INLINE sfloat_t sfloat_add(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
376     bool sign_a = SFLOAT_EXTRACT_SIGN(a);
377     bool sign_b = SFLOAT_EXTRACT_SIGN(b);
378     return (sign_a == sign_b) ? sfloat_add_impl(state, a, b, sign_a)
379                               : sfloat_sub_impl(state, a, b, sign_a);
380 }
381
382 static GMQCC_INLINE sfloat_t sfloat_sub(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
383     bool sign_a = SFLOAT_EXTRACT_SIGN(a);
384     bool sign_b = SFLOAT_EXTRACT_SIGN(b);
385     return (sign_a == sign_b) ? sfloat_sub_impl(state, a, b, sign_a)
386                               : sfloat_add_impl(state, a, b, sign_a);
387 }
388
389 static sfloat_t sfloat_mul(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
390     int16_t  exp_a   = SFLOAT_EXTRACT_EXP(a);
391     int16_t  exp_b   = SFLOAT_EXTRACT_EXP(b);
392     int16_t  exp_z   = 0;
393     uint32_t sig_a   = SFLOAT_EXTRACT_FRAC(a);
394     uint32_t sig_b   = SFLOAT_EXTRACT_FRAC(b);
395     uint32_t sig_z   = 0;
396     uint64_t sig_z64 = 0;
397     bool     sign_a  = SFLOAT_EXTRACT_SIGN(a);
398     bool     sign_b  = SFLOAT_EXTRACT_SIGN(b);
399     bool     sign_z  = sign_a ^ sign_b;
400
401     if (exp_a == 0xFF) {
402         if (sig_a || ((exp_b == 0xFF) && sig_b))
403             return sfloat_propagate_nan(state, a, b);
404         if ((exp_b | sig_b) == 0) {
405             SFLOAT_RAISE(state, SFLOAT_INVALID);
406             return SFLOAT_NAN;
407         }
408         return SFLOAT_PACK(sign_z, 0xFF, 0);
409     }
410     if (exp_b == 0xFF) {
411         if (sig_b)
412             return sfloat_propagate_nan(state, a, b);
413         if ((exp_a | sig_a) == 0) {
414             SFLOAT_RAISE(state, SFLOAT_INVALID);
415             return SFLOAT_NAN;
416         }
417         return SFLOAT_PACK(sign_z, 0xFF, 0);
418     }
419     if (exp_a == 0) {
420         if (sig_a == 0)
421             return SFLOAT_PACK(sign_z, 0, 0);
422         SFLOAT_SUBNORMALIZE(sig_a, &exp_a, &sig_a);
423     }
424     if (exp_b == 0) {
425         if (sig_b == 0)
426             return SFLOAT_PACK(sign_z, 0, 0);
427         SFLOAT_SUBNORMALIZE(sig_b, &exp_b, &sig_b);
428     }
429     exp_z = exp_a + exp_b - 0x7F;
430     sig_a = (sig_a | 0x00800000) << 7;
431     sig_b = (sig_b | 0x00800000) << 8;
432     SFLOAT_SHIFT(64, ((uint64_t)sig_a) * sig_b, 32, &sig_z64);
433     sig_z = sig_z64;
434     if (0 <= (int32_t)(sig_z << 1)) {
435         sig_z <<= 1;
436         --exp_z;
437     }
438     return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
439 }
440
441 static sfloat_t sfloat_div(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
442     int16_t  exp_a   = SFLOAT_EXTRACT_EXP(a);
443     int16_t  exp_b   = SFLOAT_EXTRACT_EXP(b);
444     int16_t  exp_z   = 0;
445     uint32_t sig_a   = SFLOAT_EXTRACT_FRAC(a);
446     uint32_t sig_b   = SFLOAT_EXTRACT_FRAC(b);
447     uint32_t sig_z   = 0;
448     bool     sign_a  = SFLOAT_EXTRACT_SIGN(a);
449     bool     sign_b  = SFLOAT_EXTRACT_SIGN(b);
450     bool     sign_z  = sign_a ^ sign_b;
451
452     if (exp_a == 0xFF) {
453         if (sig_a)
454             return sfloat_propagate_nan(state, a, b);
455         if (exp_b == 0xFF) {
456             if (sig_b)
457                 return sfloat_propagate_nan(state, a, b);
458             SFLOAT_RAISE(state, SFLOAT_INVALID);
459             return SFLOAT_NAN;
460         }
461         return SFLOAT_PACK(sign_z, 0xFF, 0);
462     }
463     if (exp_b == 0xFF)
464         return (sig_b) ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z, 0, 0);
465     if (exp_b == 0) {
466         if (sig_b == 0) {
467             if ((exp_a | sig_a) == 0) {
468                 SFLOAT_RAISE(state, SFLOAT_INVALID);
469                 return SFLOAT_NAN;
470             }
471             SFLOAT_RAISE(state, SFLOAT_DIVBYZERO);
472             return SFLOAT_PACK(sign_z, 0xFF, 0);
473         }
474         SFLOAT_SUBNORMALIZE(sig_b, &exp_b, &sig_b);
475     }
476     if (exp_a == 0) {
477         if (sig_a == 0)
478             return SFLOAT_PACK(sign_z, 0, 0);
479         SFLOAT_SUBNORMALIZE(sig_a, &exp_a, &sig_a);
480     }
481     exp_z = exp_a - exp_b + 0x7D;
482     sig_a = (sig_a | 0x00800000) << 7;
483     sig_b = (sig_b | 0x00800000) << 8;
484     if (sig_b <= (sig_a + sig_a)) {
485         sig_a >>= 1;
486         ++exp_z;
487     }
488     sig_z = (((uint64_t)sig_a) << 32) / sig_b;
489     if ((sig_z & 0x3F) == 0)
490         sig_z |= ((uint64_t)sig_b * sig_z != ((uint64_t)sig_a) << 32);
491     return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
492 }
493
494 static sfloat_t sfloat_neg(sfloat_state_t *state, sfloat_t a) {
495     sfloat_cast_t neg;
496     neg.f = -1;
497     return sfloat_mul(state, a, neg.s);
498 }
499
500 static GMQCC_INLINE void sfloat_check(lex_ctx_t ctx, sfloat_state_t *state, const char *vec) {
501     /* Exception comes from vector component */
502     if (vec) {
503         if (state->exceptionflags & SFLOAT_DIVBYZERO)
504             compile_error(ctx, "division by zero in `%s' component", vec);
505         if (state->exceptionflags & SFLOAT_INVALID)
506             compile_error(ctx, "undefined (inf) in `%s' component", vec);
507         if (state->exceptionflags & SFLOAT_OVERFLOW)
508             compile_error(ctx, "arithmetic overflow in `%s' component", vec);
509         if (state->exceptionflags & SFLOAT_UNDERFLOW)
510             compile_error(ctx, "arithmetic underflow in `%s' component", vec);
511         return;
512     }
513     if (state->exceptionflags & SFLOAT_DIVBYZERO)
514         compile_error(ctx, "division by zero");
515     if (state->exceptionflags & SFLOAT_INVALID)
516         compile_error(ctx, "undefined (inf)");
517     if (state->exceptionflags & SFLOAT_OVERFLOW)
518         compile_error(ctx, "arithmetic overflow");
519     if (state->exceptionflags & SFLOAT_UNDERFLOW)
520         compile_error(ctx, "arithmetic underflow");
521 }
522
523 static GMQCC_INLINE void sfloat_init(sfloat_state_t *state) {
524     state->exceptionflags = SFLOAT_NOEXCEPT;
525     state->roundingmode   = FOLD_ROUNDING;
526     state->tiny           = FOLD_TINYNESS;
527 }
528
529 /*
530  * There is two stages to constant folding in GMQCC: there is the parse
531  * stage constant folding, where, with the help of the AST, operator
532  * usages can be constant folded. Then there is the constant folding
533  * in the IR for things like eliding if statements, can occur.
534  *
535  * This file is thus, split into two parts.
536  */
537
538 #define isfloat(X)      (((X))->m_vtype == TYPE_FLOAT)
539 #define isvector(X)     (((X))->m_vtype == TYPE_VECTOR)
540 #define isstring(X)     (((X))->m_vtype == TYPE_STRING)
541 #define isarray(X)      (((X))->m_vtype == TYPE_ARRAY)
542 #define isfloats(X,Y)   (isfloat  (X) && isfloat (Y))
543
544 /*
545  * Implementation of basic vector math for vec3_t, for trivial constant
546  * folding.
547  *
548  * TODO: gcc/clang hinting for autovectorization
549  */
550 enum vec3_comp_t {
551     VEC_COMP_X = 1 << 0,
552     VEC_COMP_Y = 1 << 1,
553     VEC_COMP_Z = 1 << 2
554 };
555
556 struct vec3_soft_t {
557     sfloat_cast_t x;
558     sfloat_cast_t y;
559     sfloat_cast_t z;
560 };
561
562 struct vec3_soft_state_t {
563     vec3_comp_t faults;
564     sfloat_state_t state[3];
565 };
566
567 static GMQCC_INLINE vec3_soft_t vec3_soft_convert(vec3_t vec) {
568     vec3_soft_t soft;
569     soft.x.f = vec.x;
570     soft.y.f = vec.y;
571     soft.z.f = vec.z;
572     return soft;
573 }
574
575 static GMQCC_INLINE bool vec3_soft_exception(vec3_soft_state_t *vstate, size_t index) {
576     sfloat_exceptionflags_t flags = vstate->state[index].exceptionflags;
577     if (flags & SFLOAT_DIVBYZERO) return true;
578     if (flags & SFLOAT_INVALID)   return true;
579     if (flags & SFLOAT_OVERFLOW)  return true;
580     if (flags & SFLOAT_UNDERFLOW) return true;
581     return false;
582 }
583
584 static GMQCC_INLINE void vec3_soft_eval(vec3_soft_state_t *state,
585                                         sfloat_t         (*callback)(sfloat_state_t *, sfloat_t, sfloat_t),
586                                         vec3_t             a,
587                                         vec3_t             b)
588 {
589     vec3_soft_t sa = vec3_soft_convert(a);
590     vec3_soft_t sb = vec3_soft_convert(b);
591     callback(&state->state[0], sa.x.s, sb.x.s);
592     if (vec3_soft_exception(state, 0)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_X);
593     callback(&state->state[1], sa.y.s, sb.y.s);
594     if (vec3_soft_exception(state, 1)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_Y);
595     callback(&state->state[2], sa.z.s, sb.z.s);
596     if (vec3_soft_exception(state, 2)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_Z);
597 }
598
599 static GMQCC_INLINE void vec3_check_except(vec3_t     a,
600                                            vec3_t     b,
601                                            lex_ctx_t  ctx,
602                                            sfloat_t (*callback)(sfloat_state_t *, sfloat_t, sfloat_t))
603 {
604     vec3_soft_state_t state;
605
606     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
607         return;
608
609     sfloat_init(&state.state[0]);
610     sfloat_init(&state.state[1]);
611     sfloat_init(&state.state[2]);
612
613     vec3_soft_eval(&state, callback, a, b);
614     if (state.faults & VEC_COMP_X) sfloat_check(ctx, &state.state[0], "x");
615     if (state.faults & VEC_COMP_Y) sfloat_check(ctx, &state.state[1], "y");
616     if (state.faults & VEC_COMP_Z) sfloat_check(ctx, &state.state[2], "z");
617 }
618
619 static GMQCC_INLINE vec3_t vec3_add(lex_ctx_t ctx, vec3_t a, vec3_t b) {
620     vec3_t out;
621     vec3_check_except(a, b, ctx, &sfloat_add);
622     out.x = a.x + b.x;
623     out.y = a.y + b.y;
624     out.z = a.z + b.z;
625     return out;
626 }
627
628 static GMQCC_INLINE vec3_t vec3_sub(lex_ctx_t ctx, vec3_t a, vec3_t b) {
629     vec3_t out;
630     vec3_check_except(a, b, ctx, &sfloat_sub);
631     out.x = a.x - b.x;
632     out.y = a.y - b.y;
633     out.z = a.z - b.z;
634     return out;
635 }
636
637 static GMQCC_INLINE vec3_t vec3_neg(lex_ctx_t ctx, vec3_t a) {
638     vec3_t         out;
639     sfloat_cast_t  v[3];
640     sfloat_state_t s[3];
641
642     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
643         goto end;
644
645     v[0].f = a.x;
646     v[1].f = a.y;
647     v[2].f = a.z;
648
649     sfloat_init(&s[0]);
650     sfloat_init(&s[1]);
651     sfloat_init(&s[2]);
652
653     sfloat_neg(&s[0], v[0].s);
654     sfloat_neg(&s[1], v[1].s);
655     sfloat_neg(&s[2], v[2].s);
656
657     sfloat_check(ctx, &s[0], nullptr);
658     sfloat_check(ctx, &s[1], nullptr);
659     sfloat_check(ctx, &s[2], nullptr);
660
661 end:
662     out.x = -a.x;
663     out.y = -a.y;
664     out.z = -a.z;
665     return out;
666 }
667
668 static GMQCC_INLINE vec3_t vec3_or(vec3_t a, vec3_t b) {
669     vec3_t out;
670     out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b.x));
671     out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b.y));
672     out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b.z));
673     return out;
674 }
675
676 static GMQCC_INLINE vec3_t vec3_orvf(vec3_t a, qcfloat_t b) {
677     vec3_t out;
678     out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b));
679     out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b));
680     out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b));
681     return out;
682 }
683
684 static GMQCC_INLINE vec3_t vec3_and(vec3_t a, vec3_t b) {
685     vec3_t out;
686     out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b.x));
687     out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b.y));
688     out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b.z));
689     return out;
690 }
691
692 static GMQCC_INLINE vec3_t vec3_andvf(vec3_t a, qcfloat_t b) {
693     vec3_t out;
694     out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b));
695     out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b));
696     out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b));
697     return out;
698 }
699
700 static GMQCC_INLINE vec3_t vec3_xor(vec3_t a, vec3_t b) {
701     vec3_t out;
702     out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b.x));
703     out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b.y));
704     out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b.z));
705     return out;
706 }
707
708 static GMQCC_INLINE vec3_t vec3_xorvf(vec3_t a, qcfloat_t b) {
709     vec3_t out;
710     out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b));
711     out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b));
712     out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b));
713     return out;
714 }
715
716 static GMQCC_INLINE vec3_t vec3_not(vec3_t a) {
717     vec3_t out;
718     out.x = -1-a.x;
719     out.y = -1-a.y;
720     out.z = -1-a.z;
721     return out;
722 }
723
724 static GMQCC_INLINE qcfloat_t vec3_mulvv(lex_ctx_t ctx, vec3_t a, vec3_t b) {
725     vec3_soft_t    sa;
726     vec3_soft_t    sb;
727     sfloat_state_t s[5];
728     sfloat_t       r[5];
729
730     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
731         goto end;
732
733     sa = vec3_soft_convert(a);
734     sb = vec3_soft_convert(b);
735
736     sfloat_init(&s[0]);
737     sfloat_init(&s[1]);
738     sfloat_init(&s[2]);
739     sfloat_init(&s[3]);
740     sfloat_init(&s[4]);
741
742     r[0] = sfloat_mul(&s[0], sa.x.s, sb.x.s);
743     r[1] = sfloat_mul(&s[1], sa.y.s, sb.y.s);
744     r[2] = sfloat_mul(&s[2], sa.z.s, sb.z.s);
745     r[3] = sfloat_add(&s[3], r[0],   r[1]);
746     r[4] = sfloat_add(&s[4], r[3],   r[2]);
747
748     sfloat_check(ctx, &s[0], nullptr);
749     sfloat_check(ctx, &s[1], nullptr);
750     sfloat_check(ctx, &s[2], nullptr);
751     sfloat_check(ctx, &s[3], nullptr);
752     sfloat_check(ctx, &s[4], nullptr);
753
754 end:
755     return (a.x * b.x + a.y * b.y + a.z * b.z);
756 }
757
758 static GMQCC_INLINE vec3_t vec3_mulvf(lex_ctx_t ctx, vec3_t a, qcfloat_t b) {
759     vec3_t         out;
760     vec3_soft_t    sa;
761     sfloat_cast_t  sb;
762     sfloat_state_t s[3];
763
764     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
765         goto end;
766
767     sa   = vec3_soft_convert(a);
768     sb.f = b;
769     sfloat_init(&s[0]);
770     sfloat_init(&s[1]);
771     sfloat_init(&s[2]);
772
773     sfloat_mul(&s[0], sa.x.s, sb.s);
774     sfloat_mul(&s[1], sa.y.s, sb.s);
775     sfloat_mul(&s[2], sa.z.s, sb.s);
776
777     sfloat_check(ctx, &s[0], "x");
778     sfloat_check(ctx, &s[1], "y");
779     sfloat_check(ctx, &s[2], "z");
780
781 end:
782     out.x = a.x * b;
783     out.y = a.y * b;
784     out.z = a.z * b;
785     return out;
786 }
787
788 static GMQCC_INLINE bool vec3_cmp(vec3_t a, vec3_t b) {
789     return a.x == b.x &&
790            a.y == b.y &&
791            a.z == b.z;
792 }
793
794 static GMQCC_INLINE vec3_t vec3_create(float x, float y, float z) {
795     vec3_t out;
796     out.x = x;
797     out.y = y;
798     out.z = z;
799     return out;
800 }
801
802 static GMQCC_INLINE qcfloat_t vec3_notf(vec3_t a) {
803     return (!a.x && !a.y && !a.z);
804 }
805
806 static GMQCC_INLINE bool vec3_pbool(vec3_t a) {
807     return (a.x || a.y || a.z);
808 }
809
810 static GMQCC_INLINE vec3_t vec3_cross(lex_ctx_t ctx, vec3_t a, vec3_t b) {
811     vec3_t         out;
812     vec3_soft_t    sa;
813     vec3_soft_t    sb;
814     sfloat_t       r[9];
815     sfloat_state_t s[9];
816
817     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
818         goto end;
819
820     sa = vec3_soft_convert(a);
821     sb = vec3_soft_convert(b);
822
823     sfloat_init(&s[0]);
824     sfloat_init(&s[1]);
825     sfloat_init(&s[2]);
826     sfloat_init(&s[3]);
827     sfloat_init(&s[4]);
828     sfloat_init(&s[5]);
829     sfloat_init(&s[6]);
830     sfloat_init(&s[7]);
831     sfloat_init(&s[8]);
832
833     r[0] = sfloat_mul(&s[0], sa.y.s, sb.z.s);
834     r[1] = sfloat_mul(&s[1], sa.z.s, sb.y.s);
835     r[2] = sfloat_mul(&s[2], sa.z.s, sb.x.s);
836     r[3] = sfloat_mul(&s[3], sa.x.s, sb.z.s);
837     r[4] = sfloat_mul(&s[4], sa.x.s, sb.y.s);
838     r[5] = sfloat_mul(&s[5], sa.y.s, sb.x.s);
839     r[6] = sfloat_sub(&s[6], r[0],   r[1]);
840     r[7] = sfloat_sub(&s[7], r[2],   r[3]);
841     r[8] = sfloat_sub(&s[8], r[4],   r[5]);
842
843     sfloat_check(ctx, &s[0], nullptr);
844     sfloat_check(ctx, &s[1], nullptr);
845     sfloat_check(ctx, &s[2], nullptr);
846     sfloat_check(ctx, &s[3], nullptr);
847     sfloat_check(ctx, &s[4], nullptr);
848     sfloat_check(ctx, &s[5], nullptr);
849     sfloat_check(ctx, &s[6], "x");
850     sfloat_check(ctx, &s[7], "y");
851     sfloat_check(ctx, &s[8], "z");
852
853 end:
854     out.x = a.y * b.z - a.z * b.y;
855     out.y = a.z * b.x - a.x * b.z;
856     out.z = a.x * b.y - a.y * b.x;
857     return out;
858 }
859
860 qcfloat_t fold::immvalue_float(ast_value *value) {
861     return value->m_constval.vfloat;
862 }
863
864 vec3_t fold::immvalue_vector(ast_value *value) {
865     return value->m_constval.vvec;
866 }
867
868 const char *fold::immvalue_string(ast_value *value) {
869     return value->m_constval.vstring;
870 }
871
872 lex_ctx_t fold::ctx() {
873     lex_ctx_t ctx;
874     if (m_parser->lex)
875         return parser_ctx(m_parser);
876     memset(&ctx, 0, sizeof(ctx));
877     return ctx;
878 }
879
880 bool fold::immediate_true(ast_value *v) {
881     switch (v->m_vtype) {
882         case TYPE_FLOAT:
883             return !!v->m_constval.vfloat;
884         case TYPE_INTEGER:
885             return !!v->m_constval.vint;
886         case TYPE_VECTOR:
887             if (OPTS_FLAG(CORRECT_LOGIC))
888                 return vec3_pbool(v->m_constval.vvec);
889             return !!(v->m_constval.vvec.x);
890         case TYPE_STRING:
891             if (!v->m_constval.vstring)
892                 return false;
893             if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
894                 return true;
895             return !!v->m_constval.vstring[0];
896         default:
897             compile_error(ctx(), "internal error: fold_immediate_true on invalid type");
898             break;
899     }
900     return !!v->m_constval.vfunc;
901 }
902
903 /* Handy macros to determine if an ast_value can be constant folded. */
904 #define fold_can_1(X)  \
905     (ast_istype(((X)), ast_value) && (X)->m_hasvalue && ((X)->m_cvq == CV_CONST) && \
906                 ((X))->m_vtype != TYPE_FUNCTION)
907
908 #define fold_can_2(X, Y) (fold_can_1(X) && fold_can_1(Y))
909
910 fold::fold()
911     : m_parser(nullptr)
912 {
913 }
914
915 fold::fold(parser_t *parser)
916     : m_parser(parser)
917 {
918     m_imm_string_untranslate = util_htnew(FOLD_STRING_UNTRANSLATE_HTSIZE);
919     m_imm_string_dotranslate = util_htnew(FOLD_STRING_DOTRANSLATE_HTSIZE);
920
921     constgen_float(0.0f, false);
922     constgen_float(1.0f, false);
923     constgen_float(-1.0f, false);
924     constgen_float(2.0f, false);
925
926     constgen_vector(vec3_create(0.0f, 0.0f, 0.0f));
927     constgen_vector(vec3_create(-1.0f, -1.0f, -1.0f));
928 }
929
930 bool fold::generate(ir_builder *ir) {
931     // generate globals for immediate folded values
932     ast_value *cur;
933     for (auto &it : m_imm_float)
934         if (!(cur = it)->generateGlobal(ir, false)) goto err;
935     for (auto &it : m_imm_vector)
936         if (!(cur = it)->generateGlobal(ir, false)) goto err;
937     for (auto &it : m_imm_string)
938         if (!(cur = it)->generateGlobal(ir, false)) goto err;
939     return true;
940 err:
941     con_out("failed to generate global %s\n", cur->m_name.c_str());
942     delete ir;
943     return false;
944 }
945
946 fold::~fold() {
947 // TODO: parser lifetime so this is called when it should be
948 #if 0
949     for (auto &it : m_imm_float) ast_delete(it);
950     for (auto &it : m_imm_vector) ast_delete(it);
951     for (auto &it : m_imm_string) ast_delete(it);
952
953     util_htdel(m_imm_string_untranslate);
954     util_htdel(m_imm_string_dotranslate);
955 #endif
956 }
957
958 ast_expression *fold::constgen_float(qcfloat_t value, bool inexact) {
959     for (auto &it : m_imm_float)
960         if (!memcmp(&it->m_constval.vfloat, &value, sizeof(qcfloat_t)))
961             return it;
962
963     ast_value *out  = new ast_value(ctx(), "#IMMEDIATE", TYPE_FLOAT);
964     out->m_cvq = CV_CONST;
965     out->m_hasvalue = true;
966     out->m_inexact = inexact;
967     out->m_constval.vfloat = value;
968
969     m_imm_float.push_back(out);
970
971     return out;
972 }
973
974 ast_expression *fold::constgen_vector(vec3_t value) {
975     for (auto &it : m_imm_vector)
976         if (vec3_cmp(it->m_constval.vvec, value))
977             return it;
978
979     ast_value *out = new ast_value(ctx(), "#IMMEDIATE", TYPE_VECTOR);
980     out->m_cvq = CV_CONST;
981     out->m_hasvalue = true;
982     out->m_constval.vvec = value;
983
984     m_imm_vector.push_back(out);
985
986     return out;
987 }
988
989 ast_expression *fold::constgen_string(const char *str, bool translate) {
990     hash_table_t *table = translate ? m_imm_string_untranslate : m_imm_string_dotranslate;
991     ast_value *out = nullptr;
992     size_t hash = util_hthash(table, str);
993
994     if ((out = (ast_value*)util_htgeth(table, str, hash)))
995         return out;
996
997     if (translate) {
998         char name[32];
999         util_snprintf(name, sizeof(name), "dotranslate_%zu", m_parser->translated++);
1000         out = new ast_value(ctx(), name, TYPE_STRING);
1001         out->m_flags |= AST_FLAG_INCLUDE_DEF; /* def needs to be included for translatables */
1002     } else {
1003         out = new ast_value(ctx(), "#IMMEDIATE", TYPE_STRING);
1004     }
1005
1006     out->m_cvq = CV_CONST;
1007     out->m_hasvalue = true;
1008     out->m_isimm = true;
1009     out->m_constval.vstring = parser_strdup(str);
1010
1011     m_imm_string.push_back(out);
1012     util_htseth(table, str, hash, out);
1013
1014     return out;
1015 }
1016
1017 ast_expression *fold::constgen_string(const std::string &str, bool translate) {
1018   return constgen_string(str.c_str(), translate);
1019 }
1020
1021 typedef union {
1022     void (*callback)(void);
1023     sfloat_t (*binary)(sfloat_state_t *, sfloat_t, sfloat_t);
1024     sfloat_t (*unary)(sfloat_state_t *, sfloat_t);
1025 } float_check_callback_t;
1026
1027 bool fold::check_except_float_impl(void (*callback)(void), ast_value *a, ast_value *b) {
1028     float_check_callback_t call;
1029     sfloat_state_t s;
1030     sfloat_cast_t ca;
1031
1032     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS) && !OPTS_WARN(WARN_INEXACT_COMPARES))
1033         return false;
1034
1035     call.callback = callback;
1036     sfloat_init(&s);
1037     ca.f = immvalue_float(a);
1038     if (b) {
1039         sfloat_cast_t cb;
1040         cb.f = immvalue_float(b);
1041         call.binary(&s, ca.s, cb.s);
1042     } else {
1043         call.unary(&s, ca.s);
1044     }
1045
1046     if (s.exceptionflags == 0)
1047         return false;
1048
1049     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
1050         goto inexact_possible;
1051
1052     sfloat_check(ctx(), &s, nullptr);
1053
1054 inexact_possible:
1055     return s.exceptionflags & SFLOAT_INEXACT;
1056 }
1057
1058 #define check_except_float(CALLBACK, A, B) \
1059     check_except_float_impl(((void (*)(void))(CALLBACK)), (A), (B))
1060
1061 bool fold::check_inexact_float(ast_value *a, ast_value *b) {
1062     if (!OPTS_WARN(WARN_INEXACT_COMPARES))
1063         return false;
1064     if (!a->m_inexact && !b->m_inexact)
1065         return false;
1066     return compile_warning(ctx(), WARN_INEXACT_COMPARES, "inexact value in comparison");
1067 }
1068
1069 ast_expression *fold::op_mul_vec(vec3_t vec, ast_value *sel, const char *set) {
1070     qcfloat_t x = (&vec.x)[set[0]-'x'];
1071     qcfloat_t y = (&vec.x)[set[1]-'x'];
1072     qcfloat_t z = (&vec.x)[set[2]-'x'];
1073     if (!y && !z) {
1074         ast_expression *out;
1075         ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
1076         out = ast_member::make(ctx(), sel, set[0]-'x', "");
1077         out->m_keep_node = false;
1078         ((ast_member*)out)->m_rvalue = true;
1079         if (x != -1.0f)
1080             return new ast_binary(ctx(), INSTR_MUL_F, constgen_float(x, false), out);
1081     }
1082     return nullptr;
1083 }
1084
1085
1086 ast_expression *fold::op_neg(ast_value *a) {
1087     if (isfloat(a)) {
1088         if (fold_can_1(a)) {
1089             /* Negation can produce inexact as well */
1090             bool inexact = check_except_float(&sfloat_neg, a, nullptr);
1091             return constgen_float(-immvalue_float(a), inexact);
1092         }
1093     } else if (isvector(a)) {
1094         if (fold_can_1(a))
1095             return constgen_vector(vec3_neg(ctx(), immvalue_vector(a)));
1096     }
1097     return nullptr;
1098 }
1099
1100 ast_expression *fold::op_not(ast_value *a) {
1101     if (isfloat(a)) {
1102         if (fold_can_1(a))
1103             return constgen_float(!immvalue_float(a), false);
1104     } else if (isvector(a)) {
1105         if (fold_can_1(a))
1106             return constgen_float(vec3_notf(immvalue_vector(a)), false);
1107     } else if (isstring(a)) {
1108         if (fold_can_1(a)) {
1109             if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
1110                 return constgen_float(!immvalue_string(a), false);
1111             else
1112                 return constgen_float(!immvalue_string(a) || !*immvalue_string(a), false);
1113         }
1114     }
1115     return nullptr;
1116 }
1117
1118 ast_expression *fold::op_add(ast_value *a, ast_value *b) {
1119     if (isfloat(a)) {
1120         if (fold_can_2(a, b)) {
1121             bool inexact = check_except_float(&sfloat_add, a, b);
1122             return constgen_float(immvalue_float(a) + immvalue_float(b), inexact);
1123         }
1124     } else if (isvector(a)) {
1125         if (fold_can_2(a, b))
1126             return constgen_vector(vec3_add(ctx(),
1127                                                        immvalue_vector(a),
1128                                                        immvalue_vector(b)));
1129     }
1130     return nullptr;
1131 }
1132
1133 ast_expression *fold::op_sub(ast_value *a, ast_value *b) {
1134     if (isfloat(a)) {
1135         if (fold_can_2(a, b)) {
1136             bool inexact = check_except_float(&sfloat_sub, a, b);
1137             return constgen_float(immvalue_float(a) - immvalue_float(b), inexact);
1138         }
1139     } else if (isvector(a)) {
1140         if (fold_can_2(a, b))
1141             return constgen_vector(vec3_sub(ctx(),
1142                                                        immvalue_vector(a),
1143                                                        immvalue_vector(b)));
1144     }
1145     return nullptr;
1146 }
1147
1148 ast_expression *fold::op_mul(ast_value *a, ast_value *b) {
1149     if (isfloat(a)) {
1150         if (isvector(b)) {
1151             if (fold_can_2(a, b))
1152                 return constgen_vector(vec3_mulvf(ctx(), immvalue_vector(b), immvalue_float(a)));
1153         } else {
1154             if (fold_can_2(a, b)) {
1155                 bool inexact = check_except_float(&sfloat_mul, a, b);
1156                 return constgen_float(immvalue_float(a) * immvalue_float(b), inexact);
1157             }
1158         }
1159     } else if (isvector(a)) {
1160         if (isfloat(b)) {
1161             if (fold_can_2(a, b))
1162                 return constgen_vector(vec3_mulvf(ctx(), immvalue_vector(a), immvalue_float(b)));
1163         } else {
1164             if (fold_can_2(a, b)) {
1165                 return constgen_float(vec3_mulvv(ctx(), immvalue_vector(a), immvalue_vector(b)), false);
1166             } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(a)) {
1167                 ast_expression *out;
1168                 if ((out = op_mul_vec(immvalue_vector(a), b, "xyz"))) return out;
1169                 if ((out = op_mul_vec(immvalue_vector(a), b, "yxz"))) return out;
1170                 if ((out = op_mul_vec(immvalue_vector(a), b, "zxy"))) return out;
1171             } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(b)) {
1172                 ast_expression *out;
1173                 if ((out = op_mul_vec(immvalue_vector(b), a, "xyz"))) return out;
1174                 if ((out = op_mul_vec(immvalue_vector(b), a, "yxz"))) return out;
1175                 if ((out = op_mul_vec(immvalue_vector(b), a, "zxy"))) return out;
1176             }
1177         }
1178     }
1179     return nullptr;
1180 }
1181
1182 ast_expression *fold::op_div(ast_value *a, ast_value *b) {
1183     if (isfloat(a)) {
1184         if (fold_can_2(a, b)) {
1185             bool inexact = check_except_float(&sfloat_div, a, b);
1186             return constgen_float(immvalue_float(a) / immvalue_float(b), inexact);
1187         } else if (fold_can_1(b)) {
1188             return new ast_binary(
1189                 ctx(),
1190                 INSTR_MUL_F,
1191                 a,
1192                 constgen_float(1.0f / immvalue_float(b), false)
1193             );
1194         }
1195     } else if (isvector(a)) {
1196         if (fold_can_2(a, b)) {
1197             return constgen_vector(vec3_mulvf(ctx(), immvalue_vector(a), 1.0f / immvalue_float(b)));
1198         } else {
1199             return new ast_binary(
1200                 ctx(),
1201                 INSTR_MUL_VF,
1202                 a,
1203                 (fold_can_1(b))
1204                     ? constgen_float(1.0f / immvalue_float(b), false)
1205                     : new ast_binary(ctx(),
1206                                      INSTR_DIV_F,
1207                                      m_imm_float[1],
1208                                      b
1209                     )
1210             );
1211         }
1212     }
1213     return nullptr;
1214 }
1215
1216 ast_expression *fold::op_mod(ast_value *a, ast_value *b) {
1217     return (fold_can_2(a, b))
1218                 ? constgen_float(fmod(immvalue_float(a), immvalue_float(b)), false)
1219                 : nullptr;
1220 }
1221
1222 ast_expression *fold::op_bor(ast_value *a, ast_value *b) {
1223     if (isfloat(a)) {
1224         if (fold_can_2(a, b))
1225             return constgen_float((qcfloat_t)(((qcint_t)immvalue_float(a)) | ((qcint_t)immvalue_float(b))), false);
1226     } else {
1227         if (isvector(b)) {
1228             if (fold_can_2(a, b))
1229                 return constgen_vector(vec3_or(immvalue_vector(a), immvalue_vector(b)));
1230         } else {
1231             if (fold_can_2(a, b))
1232                 return constgen_vector(vec3_orvf(immvalue_vector(a), immvalue_float(b)));
1233         }
1234     }
1235     return nullptr;
1236 }
1237
1238 ast_expression *fold::op_band(ast_value *a, ast_value *b) {
1239     if (isfloat(a)) {
1240         if (fold_can_2(a, b))
1241             return constgen_float((qcfloat_t)(((qcint_t)immvalue_float(a)) & ((qcint_t)immvalue_float(b))), false);
1242     } else {
1243         if (isvector(b)) {
1244             if (fold_can_2(a, b))
1245                 return constgen_vector(vec3_and(immvalue_vector(a), immvalue_vector(b)));
1246         } else {
1247             if (fold_can_2(a, b))
1248                 return constgen_vector(vec3_andvf(immvalue_vector(a), immvalue_float(b)));
1249         }
1250     }
1251     return nullptr;
1252 }
1253
1254 ast_expression *fold::op_xor(ast_value *a, ast_value *b) {
1255     if (isfloat(a)) {
1256         if (fold_can_2(a, b))
1257             return constgen_float((qcfloat_t)(((qcint_t)immvalue_float(a)) ^ ((qcint_t)immvalue_float(b))), false);
1258     } else {
1259         if (fold_can_2(a, b)) {
1260             if (isvector(b))
1261                 return constgen_vector(vec3_xor(immvalue_vector(a), immvalue_vector(b)));
1262             else
1263                 return constgen_vector(vec3_xorvf(immvalue_vector(a), immvalue_float(b)));
1264         }
1265     }
1266     return nullptr;
1267 }
1268
1269 ast_expression *fold::op_lshift(ast_value *a, ast_value *b) {
1270     if (fold_can_2(a, b) && isfloats(a, b))
1271         return constgen_float((qcfloat_t)floorf(immvalue_float(a) * powf(2.0f, immvalue_float(b))), false);
1272     return nullptr;
1273 }
1274
1275 ast_expression *fold::op_rshift(ast_value *a, ast_value *b) {
1276     if (fold_can_2(a, b) && isfloats(a, b))
1277         return constgen_float((qcfloat_t)floorf(immvalue_float(a) / powf(2.0f, immvalue_float(b))), false);
1278     return nullptr;
1279 }
1280
1281 ast_expression *fold::op_andor(ast_value *a, ast_value *b, float expr) {
1282     if (fold_can_2(a, b)) {
1283         if (OPTS_FLAG(PERL_LOGIC)) {
1284             if (expr)
1285                 return immediate_true(a) ? a : b;
1286             else
1287                 return immediate_true(a) ? b : a;
1288         } else {
1289             return constgen_float(
1290                 ((expr) ? (immediate_true(a) || immediate_true(b))
1291                         : (immediate_true(a) && immediate_true(b)))
1292                             ? 1
1293                             : 0,
1294                 false
1295             );
1296         }
1297     }
1298     return nullptr;
1299 }
1300
1301 ast_expression *fold::op_tern(ast_value *a, ast_value *b, ast_value *c) {
1302     if (fold_can_1(a)) {
1303         return immediate_true(a)
1304                     ? b
1305                     : c;
1306     }
1307     return nullptr;
1308 }
1309
1310 ast_expression *fold::op_exp(ast_value *a, ast_value *b) {
1311     if (fold_can_2(a, b))
1312         return constgen_float((qcfloat_t)powf(immvalue_float(a), immvalue_float(b)), false);
1313     return nullptr;
1314 }
1315
1316 ast_expression *fold::op_lteqgt(ast_value *a, ast_value *b) {
1317     if (fold_can_2(a,b)) {
1318         check_inexact_float(a, b);
1319         if (immvalue_float(a) <  immvalue_float(b)) return m_imm_float[2];
1320         if (immvalue_float(a) == immvalue_float(b)) return m_imm_float[0];
1321         if (immvalue_float(a) >  immvalue_float(b)) return m_imm_float[1];
1322     }
1323     return nullptr;
1324 }
1325
1326 ast_expression *fold::op_ltgt(ast_value *a, ast_value *b, bool lt) {
1327     if (fold_can_2(a, b)) {
1328         check_inexact_float(a, b);
1329         return (lt) ? m_imm_float[!!(immvalue_float(a) < immvalue_float(b))]
1330                     : m_imm_float[!!(immvalue_float(a) > immvalue_float(b))];
1331     }
1332     return nullptr;
1333 }
1334
1335 ast_expression *fold::op_cmp(ast_value *a, ast_value *b, bool ne) {
1336     if (fold_can_2(a, b)) {
1337         if (isfloat(a) && isfloat(b)) {
1338             float la = immvalue_float(a);
1339             float lb = immvalue_float(b);
1340             check_inexact_float(a, b);
1341             return m_imm_float[ne ? la != lb : la == lb];
1342         } else if (isvector(a) && isvector(b)) {
1343             vec3_t la = immvalue_vector(a);
1344             vec3_t lb = immvalue_vector(b);
1345             bool compare = vec3_cmp(la, lb);
1346             return m_imm_float[ne ? !compare : compare];
1347         } else if (isstring(a) && isstring(b)) {
1348             bool compare = !strcmp(immvalue_string(a), immvalue_string(b));
1349             return m_imm_float[ne ? !compare : compare];
1350         }
1351     }
1352     return nullptr;
1353 }
1354
1355 ast_expression *fold::op_bnot(ast_value *a) {
1356     if (isfloat(a)) {
1357         if (fold_can_1(a))
1358             return constgen_float(-1-immvalue_float(a), false);
1359     } else {
1360         if (isvector(a)) {
1361             if (fold_can_1(a))
1362                 return constgen_vector(vec3_not(immvalue_vector(a)));
1363         }
1364     }
1365     return nullptr;
1366 }
1367
1368 ast_expression *fold::op_cross(ast_value *a, ast_value *b) {
1369     if (fold_can_2(a, b))
1370         return constgen_vector(vec3_cross(ctx(),
1371                                           immvalue_vector(a),
1372                                           immvalue_vector(b)));
1373     return nullptr;
1374 }
1375
1376 ast_expression *fold::op_length(ast_value *a) {
1377     if (fold_can_1(a) && isstring(a))
1378         return constgen_float(strlen(immvalue_string(a)), false);
1379     if (isarray(a))
1380         return constgen_float(a->m_initlist.size(), false);
1381     return nullptr;
1382 }
1383
1384 ast_expression *fold::op(const oper_info *info, ast_expression **opexprs) {
1385     ast_value *a = (ast_value*)opexprs[0];
1386     ast_value *b = (ast_value*)opexprs[1];
1387     ast_value *c = (ast_value*)opexprs[2];
1388     ast_expression *e = nullptr;
1389
1390     /* can a fold operation be applied to this operator usage? */
1391     if (!info->folds)
1392         return nullptr;
1393
1394     switch(info->operands) {
1395         case 3: if(!c) return nullptr;
1396         case 2: if(!b) return nullptr;
1397         case 1:
1398         if(!a) {
1399             compile_error(ctx(), "internal error: fold_op no operands to fold\n");
1400             return nullptr;
1401         }
1402     }
1403
1404     #define fold_op_case(ARGS, ARGS_OPID, OP, ARGS_FOLD)    \
1405         case opid##ARGS ARGS_OPID:                          \
1406             if ((e = op_##OP ARGS_FOLD)) {                  \
1407                 ++opts_optimizationcount[OPTIM_CONST_FOLD]; \
1408             }                                               \
1409             return e
1410
1411     switch(info->id) {
1412         fold_op_case(2, ('-', 'P'),      neg,    (a));
1413         fold_op_case(2, ('!', 'P'),      not,    (a));
1414         fold_op_case(1, ('+'),           add,    (a, b));
1415         fold_op_case(1, ('-'),           sub,    (a, b));
1416         fold_op_case(1, ('*'),           mul,    (a, b));
1417         fold_op_case(1, ('/'),           div,    (a, b));
1418         fold_op_case(1, ('%'),           mod,    (a, b));
1419         fold_op_case(1, ('|'),           bor,    (a, b));
1420         fold_op_case(1, ('&'),           band,   (a, b));
1421         fold_op_case(1, ('^'),           xor,    (a, b));
1422         fold_op_case(1, ('<'),           ltgt,   (a, b, true));
1423         fold_op_case(1, ('>'),           ltgt,   (a, b, false));
1424         fold_op_case(2, ('<', '<'),      lshift, (a, b));
1425         fold_op_case(2, ('>', '>'),      rshift, (a, b));
1426         fold_op_case(2, ('|', '|'),      andor,  (a, b, true));
1427         fold_op_case(2, ('&', '&'),      andor,  (a, b, false));
1428         fold_op_case(2, ('?', ':'),      tern,   (a, b, c));
1429         fold_op_case(2, ('*', '*'),      exp,    (a, b));
1430         fold_op_case(3, ('<','=','>'),   lteqgt, (a, b));
1431         fold_op_case(2, ('!', '='),      cmp,    (a, b, true));
1432         fold_op_case(2, ('=', '='),      cmp,    (a, b, false));
1433         fold_op_case(2, ('~', 'P'),      bnot,   (a));
1434         fold_op_case(2, ('>', '<'),      cross,  (a, b));
1435         fold_op_case(3, ('l', 'e', 'n'), length, (a));
1436     }
1437     #undef fold_op_case
1438     compile_error(ctx(), "internal error: attempted to constant-fold for unsupported operator");
1439     return nullptr;
1440 }
1441
1442 /*
1443  * Constant folding for compiler intrinsics, similar approach to operator
1444  * folding, primarily: individual functions for each intrinsics to fold,
1445  * and a generic selection function.
1446  */
1447 ast_expression *fold::intrinsic_isfinite(ast_value *a) {
1448     return constgen_float(isfinite(immvalue_float(a)), false);
1449 }
1450 ast_expression *fold::intrinsic_isinf(ast_value *a) {
1451     return constgen_float(isinf(immvalue_float(a)), false);
1452 }
1453 ast_expression *fold::intrinsic_isnan(ast_value *a) {
1454     return constgen_float(isnan(immvalue_float(a)), false);
1455 }
1456 ast_expression *fold::intrinsic_isnormal(ast_value *a) {
1457     return constgen_float(isnormal(immvalue_float(a)), false);
1458 }
1459 ast_expression *fold::intrinsic_signbit(ast_value *a) {
1460     return constgen_float(signbit(immvalue_float(a)), false);
1461 }
1462 ast_expression *fold::intrinsic_acosh(ast_value *a) {
1463     return constgen_float(acoshf(immvalue_float(a)), false);
1464 }
1465 ast_expression *fold::intrinsic_asinh(ast_value *a) {
1466     return constgen_float(asinhf(immvalue_float(a)), false);
1467 }
1468 ast_expression *fold::intrinsic_atanh(ast_value *a) {
1469     return constgen_float((float)atanh(immvalue_float(a)), false);
1470 }
1471 ast_expression *fold::intrinsic_exp(ast_value *a) {
1472     return constgen_float(expf(immvalue_float(a)), false);
1473 }
1474 ast_expression *fold::intrinsic_exp2(ast_value *a) {
1475     return constgen_float(exp2f(immvalue_float(a)), false);
1476 }
1477 ast_expression *fold::intrinsic_expm1(ast_value *a) {
1478     return constgen_float(expm1f(immvalue_float(a)), false);
1479 }
1480 ast_expression *fold::intrinsic_mod(ast_value *lhs, ast_value *rhs) {
1481     return constgen_float(fmodf(immvalue_float(lhs), immvalue_float(rhs)), false);
1482 }
1483 ast_expression *fold::intrinsic_pow(ast_value *lhs, ast_value *rhs) {
1484     return constgen_float(powf(immvalue_float(lhs), immvalue_float(rhs)), false);
1485 }
1486 ast_expression *fold::intrinsic_fabs(ast_value *a) {
1487     return constgen_float(fabsf(immvalue_float(a)), false);
1488 }
1489
1490 ast_expression *fold::intrinsic(const char *intrinsic, ast_expression **arg) {
1491     ast_expression *ret = nullptr;
1492     ast_value *a = (ast_value*)arg[0];
1493     ast_value *b = (ast_value*)arg[1];
1494
1495     if (!strcmp(intrinsic, "isfinite")) ret = intrinsic_isfinite(a);
1496     if (!strcmp(intrinsic, "isinf"))    ret = intrinsic_isinf(a);
1497     if (!strcmp(intrinsic, "isnan"))    ret = intrinsic_isnan(a);
1498     if (!strcmp(intrinsic, "isnormal")) ret = intrinsic_isnormal(a);
1499     if (!strcmp(intrinsic, "signbit"))  ret = intrinsic_signbit(a);
1500     if (!strcmp(intrinsic, "acosh"))    ret = intrinsic_acosh(a);
1501     if (!strcmp(intrinsic, "asinh"))    ret = intrinsic_asinh(a);
1502     if (!strcmp(intrinsic, "atanh"))    ret = intrinsic_atanh(a);
1503     if (!strcmp(intrinsic, "exp"))      ret = intrinsic_exp(a);
1504     if (!strcmp(intrinsic, "exp2"))     ret = intrinsic_exp2(a);
1505     if (!strcmp(intrinsic, "expm1"))    ret = intrinsic_expm1(a);
1506     if (!strcmp(intrinsic, "mod"))      ret = intrinsic_mod(a, b);
1507     if (!strcmp(intrinsic, "pow"))      ret = intrinsic_pow(a, b);
1508     if (!strcmp(intrinsic, "fabs"))     ret = intrinsic_fabs(a);
1509
1510     if (ret)
1511         ++opts_optimizationcount[OPTIM_CONST_FOLD];
1512
1513     return ret;
1514 }
1515
1516 /*
1517  * These are all the actual constant folding methods that happen in between
1518  * the AST/IR stage of the compiler , i.e eliminating branches for const
1519  * expressions, which is the only supported thing so far. We undefine the
1520  * testing macros here because an ir_value is differant than an ast_value.
1521  */
1522 #undef expect
1523 #undef isfloat
1524 #undef isstring
1525 #undef isvector
1526 #undef fold__immvalue_float
1527 #undef fold__immvalue_string
1528 #undef fold__immvalue_vector
1529 #undef fold_can_1
1530 #undef fold_can_2
1531
1532 #define isfloat(X)              ((X)->m_vtype == TYPE_FLOAT)
1533 /*#define isstring(X)             ((X)->m_vtype == TYPE_STRING)*/
1534 /*#define isvector(X)             ((X)->m_vtype == TYPE_VECTOR)*/
1535 #define fold_can_1(X)           ((X)->m_hasvalue && (X)->m_cvq == CV_CONST)
1536 /*#define fold_can_2(X,Y)         (fold_can_1(X) && fold_can_1(Y))*/
1537
1538 qcfloat_t fold::immvalue_float(ir_value *value) {
1539     return value->m_constval.vfloat;
1540 }
1541
1542 vec3_t fold::immvalue_vector(ir_value *value) {
1543     return value->m_constval.vvec;
1544 }
1545
1546 ast_expression *fold::superfluous(ast_expression *left, ast_expression *right, int op) {
1547     ast_expression *swapped = nullptr; /* using this as bool */
1548     ast_value *load;
1549
1550     if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right))) {
1551         swapped = left;
1552         left    = right;
1553         right   = swapped;
1554     }
1555
1556     if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right)))
1557         return nullptr;
1558
1559     switch (op) {
1560         case INSTR_DIV_F:
1561             if (swapped)
1562                 return nullptr;
1563         case INSTR_MUL_F:
1564             if (immvalue_float(load) == 1.0f) {
1565                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1566                 ast_unref(right);
1567                 return left;
1568             }
1569             break;
1570
1571
1572         case INSTR_SUB_F:
1573             if (swapped)
1574                 return nullptr;
1575         case INSTR_ADD_F:
1576             if (immvalue_float(load) == 0.0f) {
1577                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1578                 ast_unref(right);
1579                 return left;
1580             }
1581             break;
1582
1583         case INSTR_MUL_V:
1584             if (vec3_cmp(immvalue_vector(load), vec3_create(1, 1, 1))) {
1585                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1586                 ast_unref(right);
1587                 return left;
1588             }
1589             break;
1590
1591         case INSTR_SUB_V:
1592             if (swapped)
1593                 return nullptr;
1594         case INSTR_ADD_V:
1595             if (vec3_cmp(immvalue_vector(load), vec3_create(0, 0, 0))) {
1596                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1597                 ast_unref(right);
1598                 return left;
1599             }
1600             break;
1601     }
1602
1603     return nullptr;
1604 }
1605
1606 ast_expression *fold::binary(lex_ctx_t ctx, int op, ast_expression *left, ast_expression *right) {
1607     ast_expression *ret = superfluous(left, right, op);
1608     if (ret)
1609         return ret;
1610     return new ast_binary(ctx, op, left, right);
1611 }
1612
1613 int fold::cond(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1614     if (isfloat(condval) && fold_can_1(condval) && OPTS_OPTIMIZATION(OPTIM_CONST_FOLD_DCE)) {
1615         ir_block               *elide;
1616         ir_value               *dummy;
1617         bool                    istrue  = (immvalue_float(condval) != 0.0f && branch->m_on_true);
1618         bool                    isfalse = (immvalue_float(condval) == 0.0f && branch->m_on_false);
1619         ast_expression         *path    = (istrue)  ? branch->m_on_true  :
1620                                           (isfalse) ? branch->m_on_false : nullptr;
1621         if (!path) {
1622             /*
1623              * no path to take implies that the evaluation is if(0) and there
1624              * is no else block. so eliminate all the code.
1625              */
1626             ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1627             return true;
1628         }
1629
1630         if (!(elide = ir_function_create_block(branch->m_context, func->m_ir_func, func->makeLabel((istrue) ? "ontrue" : "onfalse"))))
1631             return false;
1632         if (!path->codegen(func, false, &dummy))
1633             return false;
1634         if (!ir_block_create_jump(func->m_curblock, branch->m_context, elide))
1635             return false;
1636         /*
1637          * now the branch has been eliminated and the correct block for the constant evaluation
1638          * is expanded into the current block for the function.
1639          */
1640         func->m_curblock = elide;
1641         ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1642         return true;
1643     }
1644     return -1; /* nothing done */
1645 }
1646
1647 int fold::cond_ternary(ir_value *condval, ast_function *func, ast_ternary *branch) {
1648     return cond(condval, func, (ast_ifthen*)branch);
1649 }
1650
1651 int fold::cond_ifthen(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1652     return cond(condval, func, branch);
1653 }