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