]> git.xonotic.org Git - xonotic/gmqcc.git/blob - fold.cpp
Constant folding for string comparisons too
[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)      (((ast_expression*)(X))->vtype == TYPE_FLOAT)
539 #define isvector(X)     (((ast_expression*)(X))->vtype == TYPE_VECTOR)
540 #define isstring(X)     (((ast_expression*)(X))->vtype == TYPE_STRING)
541 #define isarray(X)      (((ast_expression*)(X))->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->constval.vfloat;
862 }
863
864 vec3_t fold::immvalue_vector(ast_value *value) {
865     return value->constval.vvec;
866 }
867
868 const char *fold::immvalue_string(ast_value *value) {
869     return value->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->expression.vtype) {
882         case TYPE_FLOAT:
883             return !!v->constval.vfloat;
884         case TYPE_INTEGER:
885             return !!v->constval.vint;
886         case TYPE_VECTOR:
887             if (OPTS_FLAG(CORRECT_LOGIC))
888                 return vec3_pbool(v->constval.vvec);
889             return !!(v->constval.vvec.x);
890         case TYPE_STRING:
891             if (!v->constval.vstring)
892                 return false;
893             if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
894                 return true;
895             return !!v->constval.vstring[0];
896         default:
897             compile_error(ctx(), "internal error: fold_immediate_true on invalid type");
898             break;
899     }
900     return !!v->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(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
906                 ((ast_expression*)(X))->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 (!ast_global_codegen((cur = it), ir, false)) goto err;
935     for (auto &it : m_imm_vector)
936         if (!ast_global_codegen((cur = it), ir, false)) goto err;
937     for (auto &it : m_imm_string)
938         if (!ast_global_codegen((cur = it), ir, false)) goto err;
939     return true;
940 err:
941     con_out("failed to generate global %s\n", cur->name);
942     ir_builder_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->constval.vfloat, &value, sizeof(qcfloat_t)))
961             return (ast_expression*)it;
962
963     ast_value *out  = ast_value_new(ctx(), "#IMMEDIATE", TYPE_FLOAT);
964     out->cvq = CV_CONST;
965     out->hasvalue = true;
966     out->inexact = inexact;
967     out->constval.vfloat = value;
968
969     m_imm_float.push_back(out);
970
971     return (ast_expression*)out;
972 }
973
974 ast_expression *fold::constgen_vector(vec3_t value) {
975     for (auto &it : m_imm_vector)
976         if (vec3_cmp(it->constval.vvec, value))
977             return (ast_expression*)it;
978
979     ast_value *out = ast_value_new(ctx(), "#IMMEDIATE", TYPE_VECTOR);
980     out->cvq = CV_CONST;
981     out->hasvalue = true;
982     out->constval.vvec = value;
983
984     m_imm_vector.push_back(out);
985
986     return (ast_expression*)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 (ast_expression*)out;
996
997     if (translate) {
998         char name[32];
999         util_snprintf(name, sizeof(name), "dotranslate_%zu", m_parser->translated++);
1000         out = ast_value_new(ctx(), name, TYPE_STRING);
1001         out->expression.flags |= AST_FLAG_INCLUDE_DEF; /* def needs to be included for translatables */
1002     } else {
1003         out = ast_value_new(ctx(), "#IMMEDIATE", TYPE_STRING);
1004     }
1005
1006     out->cvq = CV_CONST;
1007     out->hasvalue = true;
1008     out->isimm = true;
1009     out->constval.vstring = parser_strdup(str);
1010
1011     m_imm_string.push_back(out);
1012     util_htseth(table, str, hash, out);
1013
1014     return (ast_expression*)out;
1015 }
1016
1017 typedef union {
1018     void (*callback)(void);
1019     sfloat_t (*binary)(sfloat_state_t *, sfloat_t, sfloat_t);
1020     sfloat_t (*unary)(sfloat_state_t *, sfloat_t);
1021 } float_check_callback_t;
1022
1023 bool fold::check_except_float_impl(void (*callback)(void), ast_value *a, ast_value *b) {
1024     float_check_callback_t call;
1025     sfloat_state_t s;
1026     sfloat_cast_t ca;
1027
1028     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS) && !OPTS_WARN(WARN_INEXACT_COMPARES))
1029         return false;
1030
1031     call.callback = callback;
1032     sfloat_init(&s);
1033     ca.f = immvalue_float(a);
1034     if (b) {
1035         sfloat_cast_t cb;
1036         cb.f = immvalue_float(b);
1037         call.binary(&s, ca.s, cb.s);
1038     } else {
1039         call.unary(&s, ca.s);
1040     }
1041
1042     if (s.exceptionflags == 0)
1043         return false;
1044
1045     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
1046         goto inexact_possible;
1047
1048     sfloat_check(ctx(), &s, nullptr);
1049
1050 inexact_possible:
1051     return s.exceptionflags & SFLOAT_INEXACT;
1052 }
1053
1054 #define check_except_float(CALLBACK, A, B) \
1055     check_except_float_impl(((void (*)(void))(CALLBACK)), (A), (B))
1056
1057 bool fold::check_inexact_float(ast_value *a, ast_value *b) {
1058     if (!OPTS_WARN(WARN_INEXACT_COMPARES))
1059         return false;
1060     if (!a->inexact && !b->inexact)
1061         return false;
1062     return compile_warning(ctx(), WARN_INEXACT_COMPARES, "inexact value in comparison");
1063 }
1064
1065 ast_expression *fold::op_mul_vec(vec3_t vec, ast_value *sel, const char *set) {
1066     qcfloat_t x = (&vec.x)[set[0]-'x'];
1067     qcfloat_t y = (&vec.x)[set[1]-'x'];
1068     qcfloat_t z = (&vec.x)[set[2]-'x'];
1069     if (!y && !z) {
1070         ast_expression *out;
1071         ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
1072         out = (ast_expression*)ast_member_new(ctx(), (ast_expression*)sel, set[0]-'x', nullptr);
1073         out->node.keep = false;
1074         ((ast_member*)out)->rvalue = true;
1075         if (x != -1.0f)
1076             return (ast_expression*)ast_binary_new(ctx(), INSTR_MUL_F, constgen_float(x, false), out);
1077     }
1078     return nullptr;
1079 }
1080
1081
1082 ast_expression *fold::op_neg(ast_value *a) {
1083     if (isfloat(a)) {
1084         if (fold_can_1(a)) {
1085             /* Negation can produce inexact as well */
1086             bool inexact = check_except_float(&sfloat_neg, a, nullptr);
1087             return constgen_float(-immvalue_float(a), inexact);
1088         }
1089     } else if (isvector(a)) {
1090         if (fold_can_1(a))
1091             return constgen_vector(vec3_neg(ctx(), immvalue_vector(a)));
1092     }
1093     return nullptr;
1094 }
1095
1096 ast_expression *fold::op_not(ast_value *a) {
1097     if (isfloat(a)) {
1098         if (fold_can_1(a))
1099             return constgen_float(!immvalue_float(a), false);
1100     } else if (isvector(a)) {
1101         if (fold_can_1(a))
1102             return constgen_float(vec3_notf(immvalue_vector(a)), false);
1103     } else if (isstring(a)) {
1104         if (fold_can_1(a)) {
1105             if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
1106                 return constgen_float(!immvalue_string(a), false);
1107             else
1108                 return constgen_float(!immvalue_string(a) || !*immvalue_string(a), false);
1109         }
1110     }
1111     return nullptr;
1112 }
1113
1114 ast_expression *fold::op_add(ast_value *a, ast_value *b) {
1115     if (isfloat(a)) {
1116         if (fold_can_2(a, b)) {
1117             bool inexact = check_except_float(&sfloat_add, a, b);
1118             return constgen_float(immvalue_float(a) + immvalue_float(b), inexact);
1119         }
1120     } else if (isvector(a)) {
1121         if (fold_can_2(a, b))
1122             return constgen_vector(vec3_add(ctx(),
1123                                                        immvalue_vector(a),
1124                                                        immvalue_vector(b)));
1125     }
1126     return nullptr;
1127 }
1128
1129 ast_expression *fold::op_sub(ast_value *a, ast_value *b) {
1130     if (isfloat(a)) {
1131         if (fold_can_2(a, b)) {
1132             bool inexact = check_except_float(&sfloat_sub, a, b);
1133             return constgen_float(immvalue_float(a) - immvalue_float(b), inexact);
1134         }
1135     } else if (isvector(a)) {
1136         if (fold_can_2(a, b))
1137             return constgen_vector(vec3_sub(ctx(),
1138                                                        immvalue_vector(a),
1139                                                        immvalue_vector(b)));
1140     }
1141     return nullptr;
1142 }
1143
1144 ast_expression *fold::op_mul(ast_value *a, ast_value *b) {
1145     if (isfloat(a)) {
1146         if (isvector(b)) {
1147             if (fold_can_2(a, b))
1148                 return constgen_vector(vec3_mulvf(ctx(), immvalue_vector(b), immvalue_float(a)));
1149         } else {
1150             if (fold_can_2(a, b)) {
1151                 bool inexact = check_except_float(&sfloat_mul, a, b);
1152                 return constgen_float(immvalue_float(a) * immvalue_float(b), inexact);
1153             }
1154         }
1155     } else if (isvector(a)) {
1156         if (isfloat(b)) {
1157             if (fold_can_2(a, b))
1158                 return constgen_vector(vec3_mulvf(ctx(), immvalue_vector(a), immvalue_float(b)));
1159         } else {
1160             if (fold_can_2(a, b)) {
1161                 return constgen_float(vec3_mulvv(ctx(), immvalue_vector(a), immvalue_vector(b)), false);
1162             } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(a)) {
1163                 ast_expression *out;
1164                 if ((out = op_mul_vec(immvalue_vector(a), b, "xyz"))) return out;
1165                 if ((out = op_mul_vec(immvalue_vector(a), b, "yxz"))) return out;
1166                 if ((out = op_mul_vec(immvalue_vector(a), b, "zxy"))) return out;
1167             } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(b)) {
1168                 ast_expression *out;
1169                 if ((out = op_mul_vec(immvalue_vector(b), a, "xyz"))) return out;
1170                 if ((out = op_mul_vec(immvalue_vector(b), a, "yxz"))) return out;
1171                 if ((out = op_mul_vec(immvalue_vector(b), a, "zxy"))) return out;
1172             }
1173         }
1174     }
1175     return nullptr;
1176 }
1177
1178 ast_expression *fold::op_div(ast_value *a, ast_value *b) {
1179     if (isfloat(a)) {
1180         if (fold_can_2(a, b)) {
1181             bool inexact = check_except_float(&sfloat_div, a, b);
1182             return constgen_float(immvalue_float(a) / immvalue_float(b), inexact);
1183         } else if (fold_can_1(b)) {
1184             return (ast_expression*)ast_binary_new(
1185                 ctx(),
1186                 INSTR_MUL_F,
1187                 (ast_expression*)a,
1188                 constgen_float(1.0f / immvalue_float(b), false)
1189             );
1190         }
1191     } else if (isvector(a)) {
1192         if (fold_can_2(a, b)) {
1193             return constgen_vector(vec3_mulvf(ctx(), immvalue_vector(a), 1.0f / immvalue_float(b)));
1194         } else {
1195             return (ast_expression*)ast_binary_new(
1196                 ctx(),
1197                 INSTR_MUL_VF,
1198                 (ast_expression*)a,
1199                 (fold_can_1(b))
1200                     ? (ast_expression*)constgen_float(1.0f / immvalue_float(b), false)
1201                     : (ast_expression*)ast_binary_new(
1202                                             ctx(),
1203                                             INSTR_DIV_F,
1204                                             (ast_expression*)m_imm_float[1],
1205                                             (ast_expression*)b
1206                     )
1207             );
1208         }
1209     }
1210     return nullptr;
1211 }
1212
1213 ast_expression *fold::op_mod(ast_value *a, ast_value *b) {
1214     return (fold_can_2(a, b))
1215                 ? constgen_float(fmod(immvalue_float(a), immvalue_float(b)), false)
1216                 : nullptr;
1217 }
1218
1219 ast_expression *fold::op_bor(ast_value *a, ast_value *b) {
1220     if (isfloat(a)) {
1221         if (fold_can_2(a, b))
1222             return constgen_float((qcfloat_t)(((qcint_t)immvalue_float(a)) | ((qcint_t)immvalue_float(b))), false);
1223     } else {
1224         if (isvector(b)) {
1225             if (fold_can_2(a, b))
1226                 return constgen_vector(vec3_or(immvalue_vector(a), immvalue_vector(b)));
1227         } else {
1228             if (fold_can_2(a, b))
1229                 return constgen_vector(vec3_orvf(immvalue_vector(a), immvalue_float(b)));
1230         }
1231     }
1232     return nullptr;
1233 }
1234
1235 ast_expression *fold::op_band(ast_value *a, ast_value *b) {
1236     if (isfloat(a)) {
1237         if (fold_can_2(a, b))
1238             return constgen_float((qcfloat_t)(((qcint_t)immvalue_float(a)) & ((qcint_t)immvalue_float(b))), false);
1239     } else {
1240         if (isvector(b)) {
1241             if (fold_can_2(a, b))
1242                 return constgen_vector(vec3_and(immvalue_vector(a), immvalue_vector(b)));
1243         } else {
1244             if (fold_can_2(a, b))
1245                 return constgen_vector(vec3_andvf(immvalue_vector(a), immvalue_float(b)));
1246         }
1247     }
1248     return nullptr;
1249 }
1250
1251 ast_expression *fold::op_xor(ast_value *a, ast_value *b) {
1252     if (isfloat(a)) {
1253         if (fold_can_2(a, b))
1254             return constgen_float((qcfloat_t)(((qcint_t)immvalue_float(a)) ^ ((qcint_t)immvalue_float(b))), false);
1255     } else {
1256         if (fold_can_2(a, b)) {
1257             if (isvector(b))
1258                 return constgen_vector(vec3_xor(immvalue_vector(a), immvalue_vector(b)));
1259             else
1260                 return constgen_vector(vec3_xorvf(immvalue_vector(a), immvalue_float(b)));
1261         }
1262     }
1263     return nullptr;
1264 }
1265
1266 ast_expression *fold::op_lshift(ast_value *a, ast_value *b) {
1267     if (fold_can_2(a, b) && isfloats(a, b))
1268         return constgen_float((qcfloat_t)floorf(immvalue_float(a) * powf(2.0f, immvalue_float(b))), false);
1269     return nullptr;
1270 }
1271
1272 ast_expression *fold::op_rshift(ast_value *a, ast_value *b) {
1273     if (fold_can_2(a, b) && isfloats(a, b))
1274         return constgen_float((qcfloat_t)floorf(immvalue_float(a) / powf(2.0f, immvalue_float(b))), false);
1275     return nullptr;
1276 }
1277
1278 ast_expression *fold::op_andor(ast_value *a, ast_value *b, float expr) {
1279     if (fold_can_2(a, b)) {
1280         if (OPTS_FLAG(PERL_LOGIC)) {
1281             if (expr)
1282                 return immediate_true(a) ? (ast_expression*)a : (ast_expression*)b;
1283             else
1284                 return immediate_true(a) ? (ast_expression*)b : (ast_expression*)a;
1285         } else {
1286             return constgen_float(
1287                 ((expr) ? (immediate_true(a) || immediate_true(b))
1288                         : (immediate_true(a) && immediate_true(b)))
1289                             ? 1
1290                             : 0,
1291                 false
1292             );
1293         }
1294     }
1295     return nullptr;
1296 }
1297
1298 ast_expression *fold::op_tern(ast_value *a, ast_value *b, ast_value *c) {
1299     if (fold_can_1(a)) {
1300         return immediate_true(a)
1301                     ? (ast_expression*)b
1302                     : (ast_expression*)c;
1303     }
1304     return nullptr;
1305 }
1306
1307 ast_expression *fold::op_exp(ast_value *a, ast_value *b) {
1308     if (fold_can_2(a, b))
1309         return constgen_float((qcfloat_t)powf(immvalue_float(a), immvalue_float(b)), false);
1310     return nullptr;
1311 }
1312
1313 ast_expression *fold::op_lteqgt(ast_value *a, ast_value *b) {
1314     if (fold_can_2(a,b)) {
1315         check_inexact_float(a, b);
1316         if (immvalue_float(a) <  immvalue_float(b)) return (ast_expression*)m_imm_float[2];
1317         if (immvalue_float(a) == immvalue_float(b)) return (ast_expression*)m_imm_float[0];
1318         if (immvalue_float(a) >  immvalue_float(b)) return (ast_expression*)m_imm_float[1];
1319     }
1320     return nullptr;
1321 }
1322
1323 ast_expression *fold::op_ltgt(ast_value *a, ast_value *b, bool lt) {
1324     if (fold_can_2(a, b)) {
1325         check_inexact_float(a, b);
1326         return (lt) ? (ast_expression*)m_imm_float[!!(immvalue_float(a) < immvalue_float(b))]
1327                     : (ast_expression*)m_imm_float[!!(immvalue_float(a) > immvalue_float(b))];
1328     }
1329     return nullptr;
1330 }
1331
1332 ast_expression *fold::op_cmp(ast_value *a, ast_value *b, bool ne) {
1333     if (fold_can_2(a, b)) {
1334         if (isfloat(a) && isfloat(b)) {
1335             float la = immvalue_float(a);
1336             float lb = immvalue_float(b);
1337             check_inexact_float(a, b);
1338             return (ast_expression*)m_imm_float[ne ? la != lb : la == lb];
1339         } else if (isvector(a) && isvector(b)) {
1340             vec3_t la = immvalue_vector(a);
1341             vec3_t lb = immvalue_vector(b);
1342             bool compare = vec3_cmp(la, lb);
1343             return (ast_expression*)m_imm_float[ne ? !compare : compare];
1344         } else if (isstring(a) && isstring(b)) {
1345             bool compare = !strcmp(immvalue_string(a), immvalue_string(b));
1346             return (ast_expression*)m_imm_float[ne ? !compare : compare];
1347         }
1348     }
1349     return nullptr;
1350 }
1351
1352 ast_expression *fold::op_bnot(ast_value *a) {
1353     if (isfloat(a)) {
1354         if (fold_can_1(a))
1355             return constgen_float(-1-immvalue_float(a), false);
1356     } else {
1357         if (isvector(a)) {
1358             if (fold_can_1(a))
1359                 return constgen_vector(vec3_not(immvalue_vector(a)));
1360         }
1361     }
1362     return nullptr;
1363 }
1364
1365 ast_expression *fold::op_cross(ast_value *a, ast_value *b) {
1366     if (fold_can_2(a, b))
1367         return constgen_vector(vec3_cross(ctx(),
1368                                           immvalue_vector(a),
1369                                           immvalue_vector(b)));
1370     return nullptr;
1371 }
1372
1373 ast_expression *fold::op_length(ast_value *a) {
1374     if (fold_can_1(a) && isstring(a))
1375         return constgen_float(strlen(immvalue_string(a)), false);
1376     if (isarray(a))
1377         return constgen_float(a->initlist.size(), false);
1378     return nullptr;
1379 }
1380
1381 ast_expression *fold::op(const oper_info *info, ast_expression **opexprs) {
1382     ast_value *a = (ast_value*)opexprs[0];
1383     ast_value *b = (ast_value*)opexprs[1];
1384     ast_value *c = (ast_value*)opexprs[2];
1385     ast_expression *e = nullptr;
1386
1387     /* can a fold operation be applied to this operator usage? */
1388     if (!info->folds)
1389         return nullptr;
1390
1391     switch(info->operands) {
1392         case 3: if(!c) return nullptr;
1393         case 2: if(!b) return nullptr;
1394         case 1:
1395         if(!a) {
1396             compile_error(ctx(), "internal error: fold_op no operands to fold\n");
1397             return nullptr;
1398         }
1399     }
1400
1401     #define fold_op_case(ARGS, ARGS_OPID, OP, ARGS_FOLD)    \
1402         case opid##ARGS ARGS_OPID:                          \
1403             if ((e = op_##OP ARGS_FOLD)) {                  \
1404                 ++opts_optimizationcount[OPTIM_CONST_FOLD]; \
1405             }                                               \
1406             return e
1407
1408     switch(info->id) {
1409         fold_op_case(2, ('-', 'P'),      neg,    (a));
1410         fold_op_case(2, ('!', 'P'),      not,    (a));
1411         fold_op_case(1, ('+'),           add,    (a, b));
1412         fold_op_case(1, ('-'),           sub,    (a, b));
1413         fold_op_case(1, ('*'),           mul,    (a, b));
1414         fold_op_case(1, ('/'),           div,    (a, b));
1415         fold_op_case(1, ('%'),           mod,    (a, b));
1416         fold_op_case(1, ('|'),           bor,    (a, b));
1417         fold_op_case(1, ('&'),           band,   (a, b));
1418         fold_op_case(1, ('^'),           xor,    (a, b));
1419         fold_op_case(1, ('<'),           ltgt,   (a, b, true));
1420         fold_op_case(1, ('>'),           ltgt,   (a, b, false));
1421         fold_op_case(2, ('<', '<'),      lshift, (a, b));
1422         fold_op_case(2, ('>', '>'),      rshift, (a, b));
1423         fold_op_case(2, ('|', '|'),      andor,  (a, b, true));
1424         fold_op_case(2, ('&', '&'),      andor,  (a, b, false));
1425         fold_op_case(2, ('?', ':'),      tern,   (a, b, c));
1426         fold_op_case(2, ('*', '*'),      exp,    (a, b));
1427         fold_op_case(3, ('<','=','>'),   lteqgt, (a, b));
1428         fold_op_case(2, ('!', '='),      cmp,    (a, b, true));
1429         fold_op_case(2, ('=', '='),      cmp,    (a, b, false));
1430         fold_op_case(2, ('~', 'P'),      bnot,   (a));
1431         fold_op_case(2, ('>', '<'),      cross,  (a, b));
1432         fold_op_case(3, ('l', 'e', 'n'), length, (a));
1433     }
1434     #undef fold_op_case
1435     compile_error(ctx(), "internal error: attempted to constant-fold for unsupported operator");
1436     return nullptr;
1437 }
1438
1439 /*
1440  * Constant folding for compiler intrinsics, similar approach to operator
1441  * folding, primarily: individual functions for each intrinsics to fold,
1442  * and a generic selection function.
1443  */
1444 ast_expression *fold::intrinsic_isfinite(ast_value *a) {
1445     return constgen_float(isfinite(immvalue_float(a)), false);
1446 }
1447 ast_expression *fold::intrinsic_isinf(ast_value *a) {
1448     return constgen_float(isinf(immvalue_float(a)), false);
1449 }
1450 ast_expression *fold::intrinsic_isnan(ast_value *a) {
1451     return constgen_float(isnan(immvalue_float(a)), false);
1452 }
1453 ast_expression *fold::intrinsic_isnormal(ast_value *a) {
1454     return constgen_float(isnormal(immvalue_float(a)), false);
1455 }
1456 ast_expression *fold::intrinsic_signbit(ast_value *a) {
1457     return constgen_float(signbit(immvalue_float(a)), false);
1458 }
1459 ast_expression *fold::intrinsic_acosh(ast_value *a) {
1460     return constgen_float(acoshf(immvalue_float(a)), false);
1461 }
1462 ast_expression *fold::intrinsic_asinh(ast_value *a) {
1463     return constgen_float(asinhf(immvalue_float(a)), false);
1464 }
1465 ast_expression *fold::intrinsic_atanh(ast_value *a) {
1466     return constgen_float((float)atanh(immvalue_float(a)), false);
1467 }
1468 ast_expression *fold::intrinsic_exp(ast_value *a) {
1469     return constgen_float(expf(immvalue_float(a)), false);
1470 }
1471 ast_expression *fold::intrinsic_exp2(ast_value *a) {
1472     return constgen_float(exp2f(immvalue_float(a)), false);
1473 }
1474 ast_expression *fold::intrinsic_expm1(ast_value *a) {
1475     return constgen_float(expm1f(immvalue_float(a)), false);
1476 }
1477 ast_expression *fold::intrinsic_mod(ast_value *lhs, ast_value *rhs) {
1478     return constgen_float(fmodf(immvalue_float(lhs), immvalue_float(rhs)), false);
1479 }
1480 ast_expression *fold::intrinsic_pow(ast_value *lhs, ast_value *rhs) {
1481     return constgen_float(powf(immvalue_float(lhs), immvalue_float(rhs)), false);
1482 }
1483 ast_expression *fold::intrinsic_fabs(ast_value *a) {
1484     return constgen_float(fabsf(immvalue_float(a)), false);
1485 }
1486
1487 ast_expression *fold::intrinsic(const char *intrinsic, ast_expression **arg) {
1488     ast_expression *ret = nullptr;
1489     ast_value *a = (ast_value*)arg[0];
1490     ast_value *b = (ast_value*)arg[1];
1491
1492     if (!strcmp(intrinsic, "isfinite")) ret = intrinsic_isfinite(a);
1493     if (!strcmp(intrinsic, "isinf"))    ret = intrinsic_isinf(a);
1494     if (!strcmp(intrinsic, "isnan"))    ret = intrinsic_isnan(a);
1495     if (!strcmp(intrinsic, "isnormal")) ret = intrinsic_isnormal(a);
1496     if (!strcmp(intrinsic, "signbit"))  ret = intrinsic_signbit(a);
1497     if (!strcmp(intrinsic, "acosh"))    ret = intrinsic_acosh(a);
1498     if (!strcmp(intrinsic, "asinh"))    ret = intrinsic_asinh(a);
1499     if (!strcmp(intrinsic, "atanh"))    ret = intrinsic_atanh(a);
1500     if (!strcmp(intrinsic, "exp"))      ret = intrinsic_exp(a);
1501     if (!strcmp(intrinsic, "exp2"))     ret = intrinsic_exp2(a);
1502     if (!strcmp(intrinsic, "expm1"))    ret = intrinsic_expm1(a);
1503     if (!strcmp(intrinsic, "mod"))      ret = intrinsic_mod(a, b);
1504     if (!strcmp(intrinsic, "pow"))      ret = intrinsic_pow(a, b);
1505     if (!strcmp(intrinsic, "fabs"))     ret = intrinsic_fabs(a);
1506
1507     if (ret)
1508         ++opts_optimizationcount[OPTIM_CONST_FOLD];
1509
1510     return ret;
1511 }
1512
1513 /*
1514  * These are all the actual constant folding methods that happen in between
1515  * the AST/IR stage of the compiler , i.e eliminating branches for const
1516  * expressions, which is the only supported thing so far. We undefine the
1517  * testing macros here because an ir_value is differant than an ast_value.
1518  */
1519 #undef expect
1520 #undef isfloat
1521 #undef isstring
1522 #undef isvector
1523 #undef fold__immvalue_float
1524 #undef fold__immvalue_string
1525 #undef fold__immvalue_vector
1526 #undef fold_can_1
1527 #undef fold_can_2
1528
1529 #define isfloat(X)              ((X)->vtype == TYPE_FLOAT)
1530 /*#define isstring(X)             ((X)->vtype == TYPE_STRING)*/
1531 /*#define isvector(X)             ((X)->vtype == TYPE_VECTOR)*/
1532 #define fold_can_1(X)           ((X)->hasvalue && (X)->cvq == CV_CONST)
1533 /*#define fold_can_2(X,Y)         (fold_can_1(X) && fold_can_1(Y))*/
1534
1535 qcfloat_t fold::immvalue_float(ir_value *value) {
1536     return value->constval.vfloat;
1537 }
1538
1539 vec3_t fold::immvalue_vector(ir_value *value) {
1540     return value->constval.vvec;
1541 }
1542
1543 ast_expression *fold::superfluous(ast_expression *left, ast_expression *right, int op) {
1544     ast_expression *swapped = nullptr; /* using this as bool */
1545     ast_value *load;
1546
1547     if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right))) {
1548         swapped = left;
1549         left    = right;
1550         right   = swapped;
1551     }
1552
1553     if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right)))
1554         return nullptr;
1555
1556     switch (op) {
1557         case INSTR_DIV_F:
1558             if (swapped)
1559                 return nullptr;
1560         case INSTR_MUL_F:
1561             if (immvalue_float(load) == 1.0f) {
1562                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1563                 ast_unref(right);
1564                 return left;
1565             }
1566             break;
1567
1568
1569         case INSTR_SUB_F:
1570             if (swapped)
1571                 return nullptr;
1572         case INSTR_ADD_F:
1573             if (immvalue_float(load) == 0.0f) {
1574                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1575                 ast_unref(right);
1576                 return left;
1577             }
1578             break;
1579
1580         case INSTR_MUL_V:
1581             if (vec3_cmp(immvalue_vector(load), vec3_create(1, 1, 1))) {
1582                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1583                 ast_unref(right);
1584                 return left;
1585             }
1586             break;
1587
1588         case INSTR_SUB_V:
1589             if (swapped)
1590                 return nullptr;
1591         case INSTR_ADD_V:
1592             if (vec3_cmp(immvalue_vector(load), vec3_create(0, 0, 0))) {
1593                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1594                 ast_unref(right);
1595                 return left;
1596             }
1597             break;
1598     }
1599
1600     return nullptr;
1601 }
1602
1603 ast_expression *fold::binary(lex_ctx_t ctx, int op, ast_expression *left, ast_expression *right) {
1604     ast_expression *ret = superfluous(left, right, op);
1605     if (ret)
1606         return ret;
1607     return (ast_expression*)ast_binary_new(ctx, op, left, right);
1608 }
1609
1610 int fold::cond(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1611     if (isfloat(condval) && fold_can_1(condval) && OPTS_OPTIMIZATION(OPTIM_CONST_FOLD_DCE)) {
1612         ast_expression_codegen *cgen;
1613         ir_block               *elide;
1614         ir_value               *dummy;
1615         bool                    istrue  = (immvalue_float(condval) != 0.0f && branch->on_true);
1616         bool                    isfalse = (immvalue_float(condval) == 0.0f && branch->on_false);
1617         ast_expression         *path    = (istrue)  ? branch->on_true  :
1618                                           (isfalse) ? branch->on_false : nullptr;
1619         if (!path) {
1620             /*
1621              * no path to take implies that the evaluation is if(0) and there
1622              * is no else block. so eliminate all the code.
1623              */
1624             ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1625             return true;
1626         }
1627
1628         if (!(elide = ir_function_create_block(ast_ctx(branch), func->ir_func, ast_function_label(func, ((istrue) ? "ontrue" : "onfalse")))))
1629             return false;
1630         if (!(*(cgen = path->codegen))((ast_expression*)path, func, false, &dummy))
1631             return false;
1632         if (!ir_block_create_jump(func->curblock, ast_ctx(branch), elide))
1633             return false;
1634         /*
1635          * now the branch has been eliminated and the correct block for the constant evaluation
1636          * is expanded into the current block for the function.
1637          */
1638         func->curblock = elide;
1639         ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1640         return true;
1641     }
1642     return -1; /* nothing done */
1643 }
1644
1645 int fold::cond_ternary(ir_value *condval, ast_function *func, ast_ternary *branch) {
1646     return cond(condval, func, (ast_ifthen*)branch);
1647 }
1648
1649 int fold::cond_ifthen(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1650     return cond(condval, func, branch);
1651 }