]> git.xonotic.org Git - xonotic/gmqcc.git/blob - fold.c
Mage inexact travel across constants.
[xonotic/gmqcc.git] / fold.c
1 /*
2  * Copyright (C) 2012, 2013, 2014
3  *     Dale Weiler
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is furnished to do
10  * so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  */
23 #include <string.h>
24 #include <math.h>
25
26 #include "ast.h"
27 #include "parser.h"
28
29 #define FOLD_STRING_UNTRANSLATE_HTSIZE 1024
30 #define FOLD_STRING_DOTRANSLATE_HTSIZE 1024
31
32 /*
33  * The constant folder is also responsible for validating if the constant
34  * expressions produce valid results. We cannot trust the FPU control
35  * unit for these exceptions because setting FPU control words might not
36  * work. Systems can set and enforce FPU modes of operation. It's also valid
37  * for libc's to simply ignore FPU exceptions. For instance ARM CPUs in
38  * glibc. We implement some trivial and IEE 754 conformant functions which
39  * emulate those operations. This is an entierly optional compiler feature
40  * which shouldn't be enabled for anything other than performing strict
41  * passes on constant expressions since it's quite slow.
42  */
43 typedef uint32_t sfloat_t;
44
45 typedef union {
46     qcfloat_t f;
47     sfloat_t  s;
48 } sfloat_cast_t;
49
50 typedef enum {
51     SFLOAT_INVALID   = 1,
52     SFLOAT_DIVBYZERO = 4,
53     SFLOAT_OVERFLOW  = 8,
54     SFLOAT_UNDERFLOW = 16,
55     SFLOAT_INEXACT   = 32
56 } sfloat_exceptionflags_t;
57
58 typedef enum {
59     SFLOAT_ROUND_NEAREST_EVEN,
60     SFLOAT_ROUND_DOWN,
61     SFLOAT_ROUND_UP,
62     SFLOAT_ROUND_TO_ZERO
63 } sfloat_roundingmode_t;
64
65 typedef enum {
66     SFLOAT_TAFTER,
67     SFLOAT_TBEFORE
68 } sfloat_tdetect_t;
69
70 typedef struct {
71     sfloat_roundingmode_t   roundingmode;
72     sfloat_exceptionflags_t exceptionflags;
73     sfloat_tdetect_t        tiny;
74 } sfloat_state_t;
75
76 /* The value of a NaN */
77 #define SFLOAT_NAN 0xFFC00000
78 /* Count of leading zero bits before the most-significand 1 bit. */
79 #define SFLOAT_CLZ(X, SUB) \
80     (__builtin_clz((X)) - (SUB))
81 /* Test if NaN */
82 #define SFLOAT_ISNAN(A) \
83     (0xFF000000 < (uint32_t)((A) << 1))
84 /* Test if signaling NaN */
85 #define SFLOAT_ISSNAN(A) \
86     (((((A) >> 22) & 0x1FF) == 0x1FE) && ((A) & 0x003FFFFF))
87 /* Raise exception */
88 #define SFLOAT_RAISE(STATE, FLAGS) \
89     ((STATE)->exceptionflags |= (FLAGS))
90 /*
91  * Shifts `A' right `COUNT' bits. Non-zero bits are stored in LSB. Size
92  * sets the arbitrarly-large limit.
93  */
94 #define SFLOAT_SHIFT(SIZE, A, COUNT, Z)                                      \
95     *(Z) = ((COUNT) == 0)                                                    \
96         ? 1                                                                  \
97         : (((COUNT) < (SIZE))                                                \
98             ? ((A) >> (COUNT)) | (((A) << ((-(COUNT)) & ((SIZE) - 1))) != 0) \
99             : ((A) != 0))
100 /* Extract fractional component */
101 #define SFLOAT_EXTRACT_FRAC(X) \
102     ((uint32_t)((X) & 0x007FFFFF))
103 /* Extract exponent component */
104 #define SFLOAT_EXTRACT_EXP(X) \
105     ((int16_t)((X) >> 23) & 0xFF)
106 /* Extract sign bit */
107 #define SFLOAT_EXTRACT_SIGN(X) \
108     ((X) >> 31)
109 /* Normalize a subnormal */
110 #define SFLOAT_SUBNORMALIZE(SA, Z, SZ) \
111     (void)(*(SZ) = (SA) << SFLOAT_CLZ((SA), 8), *(SZ) = 1 - SFLOAT_CLZ((SA), 8))
112 /*
113  * Pack sign, exponent and significand and produce a float.
114  *
115  * Integer portions of the significand are added to the exponent. The
116  * exponent input should be one less than the result exponent whenever
117  * the significand is normalized since normalized significand will
118  * always have an integer portion of value one.
119  */
120 #define SFLOAT_PACK(SIGN, EXP, SIG) \
121     (sfloat_t)((((uint32_t)(SIGN)) << 31) + (((uint32_t)(EXP)) << 23) + (SIG))
122
123 /* Calculate NaN. If either operands are signaling then raise invalid */
124 static sfloat_t sfloat_propagate_nan(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
125     bool isnan_a  = SFLOAT_ISNAN(a);
126     bool issnan_a = SFLOAT_ISSNAN(a);
127     bool isnan_b  = SFLOAT_ISNAN(b);
128     bool issnan_b = SFLOAT_ISSNAN(b);
129
130     a |= 0x00400000;
131     b |= 0x00400000;
132
133     if (issnan_a | issnan_b)
134         SFLOAT_RAISE(state, SFLOAT_INEXACT);
135     if (issnan_a) {
136         if (issnan_b)
137             goto larger;
138         return isnan_b ? b : a;
139     } else if (isnan_a) {
140         if (issnan_b | !isnan_b)
141             return a;
142 larger:
143         if ((uint32_t)(a << 1) < (uint32_t)(b << 1)) return b;
144         if ((uint32_t)(b << 1) < (uint32_t)(a << 1)) return a;
145         return (a < b) ? a : b;
146     }
147     return b;
148 }
149
150 /* Round and pack */
151 static sfloat_t SFLOAT_PACK_round(sfloat_state_t *state, bool sign_z, int16_t exp_z, uint32_t sig_z) {
152     sfloat_roundingmode_t mode      = state->roundingmode;
153     bool                  even      = !!(mode == SFLOAT_ROUND_NEAREST_EVEN);
154     unsigned char         increment = 0x40;
155     unsigned char         bits      = sig_z & 0x7F;
156
157     if (!even) {
158         if (mode == SFLOAT_ROUND_TO_ZERO)
159             increment = 0;
160         else {
161             increment = 0x7F;
162             if (sign_z) {
163                 if (mode == SFLOAT_ROUND_UP)
164                     increment = 0;
165             } else {
166                 if (mode == SFLOAT_ROUND_DOWN)
167                     increment = 0;
168             }
169         }
170     }
171
172     if (0xFD <= (uint16_t)exp_z) {
173         if ((0xFD < exp_z) || ((exp_z == 0xFD) && ((int32_t)(sig_z + increment) < 0))) {
174             SFLOAT_RAISE(state, SFLOAT_OVERFLOW | SFLOAT_INEXACT);
175             return SFLOAT_PACK(sign_z, 0xFF, 0) - (increment == 0);
176         }
177         if (exp_z < 0) {
178             /* Check for underflow */
179             bool tiny = (state->tiny == SFLOAT_TBEFORE) || (exp_z < -1) || (sig_z + increment < 0x80000000);
180             SFLOAT_SHIFT(32, sig_z, -exp_z, &sig_z);
181             exp_z = 0;
182             bits = sig_z & 0x7F;
183             if (tiny && bits)
184                 SFLOAT_RAISE(state, SFLOAT_UNDERFLOW);
185         }
186     }
187
188     /*
189      * Significand has point between bits 30 and 29, 7 bits to the left of
190      * the usual place. This shifted significand has to be normalized
191      * or smaller, if it isn't the exponent must be zero, in which case
192      * no rounding occurs since the result will be a subnormal.
193      */
194     if (bits)
195         SFLOAT_RAISE(state, SFLOAT_INEXACT);
196     sig_z = (sig_z + increment) >> 7;
197     sig_z &= ~(((bits ^ 0x40) == 0) & even);
198     if (sig_z == 0)
199         exp_z = 0;
200     return SFLOAT_PACK(sign_z, exp_z, sig_z);
201 }
202
203 /* Normalized round and pack */
204 static sfloat_t SFLOAT_PACK_normal(sfloat_state_t *state, bool sign_z, int16_t exp_z, uint32_t sig_z) {
205     unsigned char c = SFLOAT_CLZ(sig_z, 1);
206     return SFLOAT_PACK_round(state, sign_z, exp_z - c, sig_z << c);
207 }
208
209 static sfloat_t sfloat_add_impl(sfloat_state_t *state, sfloat_t a, sfloat_t b, bool sign_z) {
210     int16_t  exp_a = SFLOAT_EXTRACT_EXP(a);
211     int16_t  exp_b = SFLOAT_EXTRACT_EXP(b);
212     int16_t  exp_z = 0;
213     int16_t  exp_d = exp_a - exp_b;
214     uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a) << 6;
215     uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b) << 6;
216     uint32_t sig_z = 0;
217
218     if (0 < exp_d) {
219         if (exp_a == 0xFF)
220             return sig_a ? sfloat_propagate_nan(state, a, b) : a;
221         if (exp_b == 0)
222             --exp_d;
223         else
224             sig_b |= 0x20000000;
225         SFLOAT_SHIFT(32, sig_b, exp_d, &sig_b);
226         exp_z = exp_a;
227     } else if (exp_d < 0) {
228         if (exp_b == 0xFF)
229             return sig_b ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z, 0xFF, 0);
230         if (exp_a == 0)
231             ++exp_d;
232         else
233             sig_a |= 0x20000000;
234         SFLOAT_SHIFT(32, sig_a, -exp_d, &sig_a);
235         exp_z = exp_b;
236     } else {
237         if (exp_a == 0xFF)
238             return (sig_a | sig_b) ? sfloat_propagate_nan(state, a, b) : a;
239         if (exp_a == 0)
240             return SFLOAT_PACK(sign_z, 0, (sig_a + sig_b) >> 6);
241         sig_z = 0x40000000 + sig_a + sig_b;
242         exp_z = exp_a;
243         goto end;
244     }
245     sig_a |= 0x20000000;
246     sig_z = (sig_a + sig_b) << 1;
247     --exp_z;
248     if ((int32_t)sig_z < 0) {
249         sig_z = sig_a + sig_b;
250         ++exp_z;
251     }
252 end:
253     return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
254 }
255
256 static sfloat_t sfloat_sub_impl(sfloat_state_t *state, sfloat_t a, sfloat_t b, bool sign_z) {
257     int16_t  exp_a = SFLOAT_EXTRACT_EXP(a);
258     int16_t  exp_b = SFLOAT_EXTRACT_EXP(b);
259     int16_t  exp_z = 0;
260     int16_t  exp_d = exp_a - exp_b;
261     uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a) << 7;
262     uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b) << 7;
263     uint32_t sig_z = 0;
264
265     if (0 < exp_d) goto exp_greater_a;
266     if (exp_d < 0) goto exp_greater_b;
267
268     if (exp_a == 0xFF) {
269         if (sig_a | sig_b)
270             return sfloat_propagate_nan(state, a, b);
271         SFLOAT_RAISE(state, SFLOAT_INVALID);
272         return SFLOAT_NAN;
273     }
274
275     if (exp_a == 0)
276         exp_a = exp_b = 1;
277
278     if (sig_b < sig_a) goto greater_a;
279     if (sig_a < sig_b) goto greater_b;
280
281     return SFLOAT_PACK(state->roundingmode == SFLOAT_ROUND_DOWN, 0, 0);
282
283 exp_greater_b:
284     if (exp_b == 0xFF)
285         return (sig_b) ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z ^ 1, 0xFF, 0);
286     if (exp_a == 0)
287         ++exp_d;
288     else
289         sig_a |= 0x40000000;
290     SFLOAT_SHIFT(32, sig_a, -exp_d, &sig_a);
291     sig_b |= 0x40000000;
292 greater_b:
293     sig_z = sig_b - sig_a;
294     exp_z = exp_b;
295     sign_z ^= 1;
296     goto end;
297
298 exp_greater_a:
299     if (exp_a == 0xFF)
300         return (sig_a) ? sfloat_propagate_nan(state, a, b) : a;
301     if (exp_b == 0)
302         --exp_d;
303     else
304         sig_b |= 0x40000000;
305     SFLOAT_SHIFT(32, sig_b, exp_d, &sig_b);
306     sig_a |= 0x40000000;
307 greater_a:
308     sig_z = sig_a - sig_b;
309     exp_z = exp_a;
310
311 end:
312     --exp_z;
313     return SFLOAT_PACK_normal(state, sign_z, exp_z, sig_z);
314 }
315
316 static GMQCC_INLINE sfloat_t sfloat_add(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
317     bool sign_a = SFLOAT_EXTRACT_SIGN(a);
318     bool sign_b = SFLOAT_EXTRACT_SIGN(b);
319     return (sign_a == sign_b) ? sfloat_add_impl(state, a, b, sign_a)
320                               : sfloat_sub_impl(state, a, b, sign_a);
321 }
322
323 static GMQCC_INLINE sfloat_t sfloat_sub(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
324     bool sign_a = SFLOAT_EXTRACT_SIGN(a);
325     bool sign_b = SFLOAT_EXTRACT_SIGN(b);
326     return (sign_a == sign_b) ? sfloat_sub_impl(state, a, b, sign_a)
327                               : sfloat_add_impl(state, a, b, sign_a);
328 }
329
330 static sfloat_t sfloat_mul(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
331     int16_t  exp_a   = SFLOAT_EXTRACT_EXP(a);
332     int16_t  exp_b   = SFLOAT_EXTRACT_EXP(b);
333     int16_t  exp_z   = 0;
334     uint32_t sig_a   = SFLOAT_EXTRACT_FRAC(a);
335     uint32_t sig_b   = SFLOAT_EXTRACT_FRAC(b);
336     uint32_t sig_z   = 0;
337     uint64_t sig_z64 = 0;
338     bool     sign_a  = SFLOAT_EXTRACT_SIGN(a);
339     bool     sign_b  = SFLOAT_EXTRACT_SIGN(b);
340     bool     sign_z  = sign_a ^ sign_b;
341
342     if (exp_a == 0xFF) {
343         if (sig_a || ((exp_b == 0xFF) && sig_b))
344             return sfloat_propagate_nan(state, a, b);
345         if ((exp_b | sig_b) == 0) {
346             SFLOAT_RAISE(state, SFLOAT_INVALID);
347             return SFLOAT_NAN;
348         }
349         return SFLOAT_PACK(sign_z, 0xFF, 0);
350     }
351     if (exp_b == 0xFF) {
352         if (sig_b)
353             return sfloat_propagate_nan(state, a, b);
354         if ((exp_a | sig_a) == 0) {
355             SFLOAT_RAISE(state, SFLOAT_INVALID);
356             return SFLOAT_NAN;
357         }
358         return SFLOAT_PACK(sign_z, 0xFF, 0);
359     }
360     if (exp_a == 0) {
361         if (sig_a == 0)
362             return SFLOAT_PACK(sign_z, 0, 0);
363         SFLOAT_SUBNORMALIZE(sig_a, &exp_a, &sig_a);
364     }
365     if (exp_b == 0) {
366         if (sig_b == 0)
367             return SFLOAT_PACK(sign_z, 0, 0);
368         SFLOAT_SUBNORMALIZE(sig_b, &exp_b, &sig_b);
369     }
370     exp_z = exp_a + exp_b - 0x7F;
371     sig_a = (sig_a | 0x00800000) << 7;
372     sig_b = (sig_b | 0x00800000) << 8;
373     SFLOAT_SHIFT(64, ((uint64_t)sig_a) * sig_b, 32, &sig_z64);
374     sig_z = sig_z64;
375     if (0 <= (int32_t)(sig_z << 1)) {
376         sig_z <<= 1;
377         --exp_z;
378     }
379     return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
380 }
381
382 static sfloat_t sfloat_div(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
383     int16_t  exp_a   = SFLOAT_EXTRACT_EXP(a);
384     int16_t  exp_b   = SFLOAT_EXTRACT_EXP(b);
385     int16_t  exp_z   = 0;
386     uint32_t sig_a   = SFLOAT_EXTRACT_FRAC(a);
387     uint32_t sig_b   = SFLOAT_EXTRACT_FRAC(b);
388     uint32_t sig_z   = 0;
389     bool     sign_a  = SFLOAT_EXTRACT_SIGN(a);
390     bool     sign_b  = SFLOAT_EXTRACT_SIGN(b);
391     bool     sign_z  = sign_a ^ sign_b;
392
393     if (exp_a == 0xFF) {
394         if (sig_a)
395             return sfloat_propagate_nan(state, a, b);
396         if (exp_b == 0xFF) {
397             if (sig_b)
398                 return sfloat_propagate_nan(state, a, b);
399             SFLOAT_RAISE(state, SFLOAT_INVALID);
400             return SFLOAT_NAN;
401         }
402         return SFLOAT_PACK(sign_z, 0xFF, 0);
403     }
404     if (exp_b == 0xFF)
405         return (sig_b) ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z, 0, 0);
406     if (exp_b == 0) {
407         if (sig_b == 0) {
408             if ((exp_a | sig_a) == 0) {
409                 SFLOAT_RAISE(state, SFLOAT_INVALID);
410                 return SFLOAT_NAN;
411             }
412             SFLOAT_RAISE(state, SFLOAT_DIVBYZERO);
413             return SFLOAT_PACK(sign_z, 0xFF, 0);
414         }
415         SFLOAT_SUBNORMALIZE(sig_b, &exp_b, &sig_b);
416     }
417     if (exp_a == 0) {
418         if (sig_a == 0)
419             return SFLOAT_PACK(sign_z, 0, 0);
420         SFLOAT_SUBNORMALIZE(sig_a, &exp_a, &sig_a);
421     }
422     exp_z = exp_a - exp_b + 0x7D;
423     sig_a = (sig_a | 0x00800000) << 7;
424     sig_b = (sig_b | 0x00800000) << 8;
425     if (sig_b <= (sig_a + sig_a)) {
426         sig_a >>= 1;
427         ++exp_z;
428     }
429     sig_z = (((uint64_t)sig_a) << 32) / sig_b;
430     if ((sig_z & 0x3F) == 0)
431         sig_z |= ((uint64_t)sig_b * sig_z != ((uint64_t)sig_a) << 32);
432     return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
433 }
434
435 /*
436  * There is two stages to constant folding in GMQCC: there is the parse
437  * stage constant folding, where, witht he help of the AST, operator
438  * usages can be constant folded. Then there is the constant folding
439  * in the IR for things like eliding if statements, can occur.
440  *
441  * This file is thus, split into two parts.
442  */
443
444 #define isfloat(X)      (((ast_expression*)(X))->vtype == TYPE_FLOAT)
445 #define isvector(X)     (((ast_expression*)(X))->vtype == TYPE_VECTOR)
446 #define isstring(X)     (((ast_expression*)(X))->vtype == TYPE_STRING)
447 #define isfloats(X,Y)   (isfloat  (X) && isfloat (Y))
448
449 /*
450  * Implementation of basic vector math for vec3_t, for trivial constant
451  * folding.
452  *
453  * TODO: gcc/clang hinting for autovectorization
454  */
455 static GMQCC_INLINE vec3_t vec3_add(vec3_t a, vec3_t b) {
456     vec3_t out;
457     out.x = a.x + b.x;
458     out.y = a.y + b.y;
459     out.z = a.z + b.z;
460     return out;
461 }
462
463 static GMQCC_INLINE vec3_t vec3_sub(vec3_t a, vec3_t b) {
464     vec3_t out;
465     out.x = a.x - b.x;
466     out.y = a.y - b.y;
467     out.z = a.z - b.z;
468     return out;
469 }
470
471 static GMQCC_INLINE vec3_t vec3_neg(vec3_t a) {
472     vec3_t out;
473     out.x = -a.x;
474     out.y = -a.y;
475     out.z = -a.z;
476     return out;
477 }
478
479 static GMQCC_INLINE vec3_t vec3_or(vec3_t a, vec3_t b) {
480     vec3_t out;
481     out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b.x));
482     out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b.y));
483     out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b.z));
484     return out;
485 }
486
487 static GMQCC_INLINE vec3_t vec3_orvf(vec3_t a, qcfloat_t b) {
488     vec3_t out;
489     out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b));
490     out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b));
491     out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b));
492     return out;
493 }
494
495 static GMQCC_INLINE vec3_t vec3_and(vec3_t a, vec3_t b) {
496     vec3_t out;
497     out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b.x));
498     out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b.y));
499     out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b.z));
500     return out;
501 }
502
503 static GMQCC_INLINE vec3_t vec3_andvf(vec3_t a, qcfloat_t b) {
504     vec3_t out;
505     out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b));
506     out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b));
507     out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b));
508     return out;
509 }
510
511 static GMQCC_INLINE vec3_t vec3_xor(vec3_t a, vec3_t b) {
512     vec3_t out;
513     out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b.x));
514     out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b.y));
515     out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b.z));
516     return out;
517 }
518
519 static GMQCC_INLINE vec3_t vec3_xorvf(vec3_t a, qcfloat_t b) {
520     vec3_t out;
521     out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b));
522     out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b));
523     out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b));
524     return out;
525 }
526
527 static GMQCC_INLINE vec3_t vec3_not(vec3_t a) {
528     vec3_t out;
529     out.x = -1-a.x;
530     out.y = -1-a.y;
531     out.z = -1-a.z;
532     return out;
533 }
534
535 static GMQCC_INLINE qcfloat_t vec3_mulvv(vec3_t a, vec3_t b) {
536     return (a.x * b.x + a.y * b.y + a.z * b.z);
537 }
538
539 static GMQCC_INLINE vec3_t vec3_mulvf(vec3_t a, qcfloat_t b) {
540     vec3_t out;
541     out.x = a.x * b;
542     out.y = a.y * b;
543     out.z = a.z * b;
544     return out;
545 }
546
547 static GMQCC_INLINE bool vec3_cmp(vec3_t a, vec3_t b) {
548     return a.x == b.x &&
549            a.y == b.y &&
550            a.z == b.z;
551 }
552
553 static GMQCC_INLINE vec3_t vec3_create(float x, float y, float z) {
554     vec3_t out;
555     out.x = x;
556     out.y = y;
557     out.z = z;
558     return out;
559 }
560
561 static GMQCC_INLINE qcfloat_t vec3_notf(vec3_t a) {
562     return (!a.x && !a.y && !a.z);
563 }
564
565 static GMQCC_INLINE bool vec3_pbool(vec3_t a) {
566     return (a.x || a.y || a.z);
567 }
568
569 static GMQCC_INLINE vec3_t vec3_cross(vec3_t a, vec3_t b) {
570     vec3_t out;
571     out.x = a.y * b.z - a.z * b.y;
572     out.y = a.z * b.x - a.x * b.z;
573     out.z = a.x * b.y - a.y * b.x;
574     return out;
575 }
576
577 static lex_ctx_t fold_ctx(fold_t *fold) {
578     lex_ctx_t ctx;
579     if (fold->parser->lex)
580         return parser_ctx(fold->parser);
581
582     memset(&ctx, 0, sizeof(ctx));
583     return ctx;
584 }
585
586 static GMQCC_INLINE bool fold_immediate_true(fold_t *fold, ast_value *v) {
587     switch (v->expression.vtype) {
588         case TYPE_FLOAT:
589             return !!v->constval.vfloat;
590         case TYPE_INTEGER:
591             return !!v->constval.vint;
592         case TYPE_VECTOR:
593             if (OPTS_FLAG(CORRECT_LOGIC))
594                 return vec3_pbool(v->constval.vvec);
595             return !!(v->constval.vvec.x);
596         case TYPE_STRING:
597             if (!v->constval.vstring)
598                 return false;
599             if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
600                 return true;
601             return !!v->constval.vstring[0];
602         default:
603             compile_error(fold_ctx(fold), "internal error: fold_immediate_true on invalid type");
604             break;
605     }
606     return !!v->constval.vfunc;
607 }
608
609 /* Handy macros to determine if an ast_value can be constant folded. */
610 #define fold_can_1(X)  \
611     (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
612                 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
613
614 #define fold_can_2(X, Y) (fold_can_1(X) && fold_can_1(Y))
615
616 #define fold_immvalue_float(E)  ((E)->constval.vfloat)
617 #define fold_immvalue_vector(E) ((E)->constval.vvec)
618 #define fold_immvalue_string(E) ((E)->constval.vstring)
619
620 fold_t *fold_init(parser_t *parser) {
621     fold_t *fold                 = (fold_t*)mem_a(sizeof(fold_t));
622     fold->parser                 = parser;
623     fold->imm_float              = NULL;
624     fold->imm_vector             = NULL;
625     fold->imm_string             = NULL;
626     fold->imm_string_untranslate = util_htnew(FOLD_STRING_UNTRANSLATE_HTSIZE);
627     fold->imm_string_dotranslate = util_htnew(FOLD_STRING_DOTRANSLATE_HTSIZE);
628
629     /*
630      * prime the tables with common constant values at constant
631      * locations.
632      */
633     (void)fold_constgen_float (fold,  0.0f, false);
634     (void)fold_constgen_float (fold,  1.0f, false);
635     (void)fold_constgen_float (fold, -1.0f, false);
636     (void)fold_constgen_float (fold,  2.0f, false);
637
638     (void)fold_constgen_vector(fold, vec3_create(0.0f, 0.0f, 0.0f));
639     (void)fold_constgen_vector(fold, vec3_create(-1.0f, -1.0f, -1.0f));
640
641     return fold;
642 }
643
644 bool fold_generate(fold_t *fold, ir_builder *ir) {
645     /* generate globals for immediate folded values */
646     size_t     i;
647     ast_value *cur;
648
649     for (i = 0; i < vec_size(fold->imm_float);   ++i)
650         if (!ast_global_codegen ((cur = fold->imm_float[i]), ir, false)) goto err;
651     for (i = 0; i < vec_size(fold->imm_vector);  ++i)
652         if (!ast_global_codegen((cur = fold->imm_vector[i]), ir, false)) goto err;
653     for (i = 0; i < vec_size(fold->imm_string);  ++i)
654         if (!ast_global_codegen((cur = fold->imm_string[i]), ir, false)) goto err;
655
656     return true;
657
658 err:
659     con_out("failed to generate global %s\n", cur->name);
660     ir_builder_delete(ir);
661     return false;
662 }
663
664 void fold_cleanup(fold_t *fold) {
665     size_t i;
666
667     for (i = 0; i < vec_size(fold->imm_float);  ++i) ast_delete(fold->imm_float[i]);
668     for (i = 0; i < vec_size(fold->imm_vector); ++i) ast_delete(fold->imm_vector[i]);
669     for (i = 0; i < vec_size(fold->imm_string); ++i) ast_delete(fold->imm_string[i]);
670
671     vec_free(fold->imm_float);
672     vec_free(fold->imm_vector);
673     vec_free(fold->imm_string);
674
675     util_htdel(fold->imm_string_untranslate);
676     util_htdel(fold->imm_string_dotranslate);
677
678     mem_d(fold);
679 }
680
681 ast_expression *fold_constgen_float(fold_t *fold, qcfloat_t value, bool inexact) {
682     ast_value  *out = NULL;
683     size_t      i;
684
685     for (i = 0; i < vec_size(fold->imm_float); i++) {
686         if (!memcmp(&fold->imm_float[i]->constval.vfloat, &value, sizeof(qcfloat_t)))
687             return (ast_expression*)fold->imm_float[i];
688     }
689
690     out                  = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_FLOAT);
691     out->cvq             = CV_CONST;
692     out->hasvalue        = true;
693     out->inexact         = inexact;
694     out->constval.vfloat = value;
695
696     vec_push(fold->imm_float, out);
697
698     return (ast_expression*)out;
699 }
700
701 ast_expression *fold_constgen_vector(fold_t *fold, vec3_t value) {
702     ast_value *out;
703     size_t     i;
704
705     for (i = 0; i < vec_size(fold->imm_vector); i++) {
706         if (vec3_cmp(fold->imm_vector[i]->constval.vvec, value))
707             return (ast_expression*)fold->imm_vector[i];
708     }
709
710     out                = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_VECTOR);
711     out->cvq           = CV_CONST;
712     out->hasvalue      = true;
713     out->constval.vvec = value;
714
715     vec_push(fold->imm_vector, out);
716
717     return (ast_expression*)out;
718 }
719
720 ast_expression *fold_constgen_string(fold_t *fold, const char *str, bool translate) {
721     hash_table_t *table = (translate) ? fold->imm_string_untranslate : fold->imm_string_dotranslate;
722     ast_value    *out   = NULL;
723     size_t        hash  = util_hthash(table, str);
724
725     if ((out = (ast_value*)util_htgeth(table, str, hash)))
726         return (ast_expression*)out;
727
728     if (translate) {
729         char name[32];
730         util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(fold->parser->translated++));
731         out                    = ast_value_new(parser_ctx(fold->parser), name, TYPE_STRING);
732         out->expression.flags |= AST_FLAG_INCLUDE_DEF; /* def needs to be included for translatables */
733     } else
734         out                    = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_STRING);
735
736     out->cvq              = CV_CONST;
737     out->hasvalue         = true;
738     out->isimm            = true;
739     out->constval.vstring = parser_strdup(str);
740
741     vec_push(fold->imm_string, out);
742     util_htseth(table, str, hash, out);
743
744     return (ast_expression*)out;
745 }
746
747
748 static GMQCC_INLINE ast_expression *fold_op_mul_vec(fold_t *fold, vec3_t vec, ast_value *sel, const char *set) {
749     /*
750      * vector-component constant folding works by matching the component sets
751      * to eliminate expensive operations on whole-vectors (3 components at runtime).
752      * to achive this effect in a clean manner this function generalizes the
753      * values through the use of a set paramater, which is used as an indexing method
754      * for creating the elided ast binary expression.
755      *
756      * Consider 'n 0 0' where y, and z need to be tested for 0, and x is
757      * used as the value in a binary operation generating an INSTR_MUL instruction,
758      * to acomplish the indexing of the correct component value we use set[0], set[1], set[2]
759      * as x, y, z, where the values of those operations return 'x', 'y', 'z'. Because
760      * of how ASCII works we can easily deliniate:
761      * vec.z is the same as set[2]-'x' for when set[2] is 'z', 'z'-'x' results in a
762      * literal value of 2, using this 2, we know that taking the address of vec->x (float)
763      * and indxing it with this literal will yeild the immediate address of that component
764      *
765      * Of course more work needs to be done to generate the correct index for the ast_member_new
766      * call, which is no problem: set[0]-'x' suffices that job.
767      */
768     qcfloat_t x = (&vec.x)[set[0]-'x'];
769     qcfloat_t y = (&vec.x)[set[1]-'x'];
770     qcfloat_t z = (&vec.x)[set[2]-'x'];
771
772     if (!y && !z) {
773         ast_expression *out;
774         ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
775         out                        = (ast_expression*)ast_member_new(fold_ctx(fold), (ast_expression*)sel, set[0]-'x', NULL);
776         out->node.keep             = false;
777         ((ast_member*)out)->rvalue = true;
778         if (x != -1.0f)
779             return (ast_expression*)ast_binary_new(fold_ctx(fold), INSTR_MUL_F, fold_constgen_float(fold, x, false), out);
780     }
781     return NULL;
782 }
783
784
785 static GMQCC_INLINE ast_expression *fold_op_neg(fold_t *fold, ast_value *a) {
786     if (isfloat(a)) {
787         if (fold_can_1(a))
788             return fold_constgen_float(fold, -fold_immvalue_float(a), false);
789     } else if (isvector(a)) {
790         if (fold_can_1(a))
791             return fold_constgen_vector(fold, vec3_neg(fold_immvalue_vector(a)));
792     }
793     return NULL;
794 }
795
796 static GMQCC_INLINE ast_expression *fold_op_not(fold_t *fold, ast_value *a) {
797     if (isfloat(a)) {
798         if (fold_can_1(a))
799             return fold_constgen_float(fold, !fold_immvalue_float(a), false);
800     } else if (isvector(a)) {
801         if (fold_can_1(a))
802             return fold_constgen_float(fold, vec3_notf(fold_immvalue_vector(a)), false);
803     } else if (isstring(a)) {
804         if (fold_can_1(a)) {
805             if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
806                 return fold_constgen_float(fold, !fold_immvalue_string(a), false);
807             else
808                 return fold_constgen_float(fold, !fold_immvalue_string(a) || !*fold_immvalue_string(a), false);
809         }
810     }
811     return NULL;
812 }
813
814 static bool fold_check_except_float(sfloat_t (*callback)(sfloat_state_t *, sfloat_t, sfloat_t),
815                                     fold_t    *fold,
816                                     ast_value *a,
817                                     ast_value *b)
818 {
819     sfloat_state_t s;
820     sfloat_cast_t ca;
821     sfloat_cast_t cb;
822
823     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS) && !OPTS_WARN(WARN_INEXACT_COMPARES))
824         return false;
825
826     s.roundingmode   = SFLOAT_ROUND_NEAREST_EVEN;
827     s.tiny           = SFLOAT_TBEFORE;
828     s.exceptionflags = 0;
829     ca.f             = fold_immvalue_float(a);
830     cb.f             = fold_immvalue_float(b);
831
832     callback(&s, ca.s, cb.s);
833     if (s.exceptionflags == 0)
834         return false;
835
836     if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
837         goto inexact_possible;
838
839     if (s.exceptionflags & SFLOAT_DIVBYZERO)
840         compile_error(fold_ctx(fold), "division by zero");
841     if (s.exceptionflags & SFLOAT_INVALID)
842         compile_error(fold_ctx(fold), "undefined (inf)");
843     if (s.exceptionflags & SFLOAT_OVERFLOW)
844         compile_error(fold_ctx(fold), "arithmetic overflow");
845     if (s.exceptionflags & SFLOAT_UNDERFLOW)
846         compile_error(fold_ctx(fold), "arithmetic underflow");
847
848 inexact_possible:
849     return s.exceptionflags & SFLOAT_INEXACT;
850 }
851
852 static bool fold_check_inexact_float(fold_t *fold, ast_value *a, ast_value *b) {
853     lex_ctx_t ctx = fold_ctx(fold);
854     if (!OPTS_WARN(WARN_INEXACT_COMPARES))
855         return false;
856     if (!a->inexact && !b->inexact)
857         return false;
858     return compile_warning(ctx, WARN_INEXACT_COMPARES, "inexact value in comparison");
859 }
860
861 static GMQCC_INLINE ast_expression *fold_op_add(fold_t *fold, ast_value *a, ast_value *b) {
862     if (isfloat(a)) {
863         if (fold_can_2(a, b)) {
864             bool inexact = fold_check_except_float(&sfloat_add, fold, a, b);
865             return fold_constgen_float(fold, fold_immvalue_float(a) + fold_immvalue_float(b), inexact);
866         }
867     } else if (isvector(a)) {
868         if (fold_can_2(a, b))
869             return fold_constgen_vector(fold, vec3_add(fold_immvalue_vector(a), fold_immvalue_vector(b)));
870     }
871     return NULL;
872 }
873
874 static GMQCC_INLINE ast_expression *fold_op_sub(fold_t *fold, ast_value *a, ast_value *b) {
875     if (isfloat(a)) {
876         if (fold_can_2(a, b)) {
877             bool inexact = fold_check_except_float(&sfloat_sub, fold, a, b);
878             return fold_constgen_float(fold, fold_immvalue_float(a) - fold_immvalue_float(b), inexact);
879         }
880     } else if (isvector(a)) {
881         if (fold_can_2(a, b))
882             return fold_constgen_vector(fold, vec3_sub(fold_immvalue_vector(a), fold_immvalue_vector(b)));
883     }
884     return NULL;
885 }
886
887 static GMQCC_INLINE ast_expression *fold_op_mul(fold_t *fold, ast_value *a, ast_value *b) {
888     if (isfloat(a)) {
889         if (isvector(b)) {
890             if (fold_can_2(a, b))
891                 return fold_constgen_vector(fold, vec3_mulvf(fold_immvalue_vector(b), fold_immvalue_float(a)));
892         } else {
893             if (fold_can_2(a, b)) {
894                 bool inexact = fold_check_except_float(&sfloat_mul, fold, a, b);
895                 return fold_constgen_float(fold, fold_immvalue_float(a) * fold_immvalue_float(b), inexact);
896             }
897         }
898     } else if (isvector(a)) {
899         if (isfloat(b)) {
900             if (fold_can_2(a, b))
901                 return fold_constgen_vector(fold, vec3_mulvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
902         } else {
903             if (fold_can_2(a, b)) {
904                 return fold_constgen_float(fold, vec3_mulvv(fold_immvalue_vector(a), fold_immvalue_vector(b)), false);
905             } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(a)) {
906                 ast_expression *out;
907                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "xyz"))) return out;
908                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "yxz"))) return out;
909                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "zxy"))) return out;
910             } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(b)) {
911                 ast_expression *out;
912                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "xyz"))) return out;
913                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "yxz"))) return out;
914                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "zxy"))) return out;
915             }
916         }
917     }
918     return NULL;
919 }
920
921 static GMQCC_INLINE ast_expression *fold_op_div(fold_t *fold, ast_value *a, ast_value *b) {
922     if (isfloat(a)) {
923         if (fold_can_2(a, b)) {
924             bool inexact = fold_check_except_float(&sfloat_div, fold, a, b);
925             return fold_constgen_float(fold, fold_immvalue_float(a) / fold_immvalue_float(b), inexact);
926         } else if (fold_can_1(b)) {
927             return (ast_expression*)ast_binary_new(
928                 fold_ctx(fold),
929                 INSTR_MUL_F,
930                 (ast_expression*)a,
931                 fold_constgen_float(fold, 1.0f / fold_immvalue_float(b), false)
932             );
933         }
934     } else if (isvector(a)) {
935         if (fold_can_2(a, b)) {
936             return fold_constgen_vector(fold, vec3_mulvf(fold_immvalue_vector(a), 1.0f / fold_immvalue_float(b)));
937         } else {
938             return (ast_expression*)ast_binary_new(
939                 fold_ctx(fold),
940                 INSTR_MUL_VF,
941                 (ast_expression*)a,
942                 (fold_can_1(b))
943                     ? (ast_expression*)fold_constgen_float(fold, 1.0f / fold_immvalue_float(b), false)
944                     : (ast_expression*)ast_binary_new(
945                                             fold_ctx(fold),
946                                             INSTR_DIV_F,
947                                             (ast_expression*)fold->imm_float[1],
948                                             (ast_expression*)b
949                     )
950             );
951         }
952     }
953     return NULL;
954 }
955
956 static GMQCC_INLINE ast_expression *fold_op_mod(fold_t *fold, ast_value *a, ast_value *b) {
957     return (fold_can_2(a, b))
958                 ? fold_constgen_float(fold, fmod(fold_immvalue_float(a), fold_immvalue_float(b)), false)
959                 : NULL;
960 }
961
962 static GMQCC_INLINE ast_expression *fold_op_bor(fold_t *fold, ast_value *a, ast_value *b) {
963     if (isfloat(a)) {
964         if (fold_can_2(a, b))
965             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) | ((qcint_t)fold_immvalue_float(b))), false);
966     } else {
967         if (isvector(b)) {
968             if (fold_can_2(a, b))
969                 return fold_constgen_vector(fold, vec3_or(fold_immvalue_vector(a), fold_immvalue_vector(b)));
970         } else {
971             if (fold_can_2(a, b))
972                 return fold_constgen_vector(fold, vec3_orvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
973         }
974     }
975     return NULL;
976 }
977
978 static GMQCC_INLINE ast_expression *fold_op_band(fold_t *fold, ast_value *a, ast_value *b) {
979     if (isfloat(a)) {
980         if (fold_can_2(a, b))
981             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) & ((qcint_t)fold_immvalue_float(b))), false);
982     } else {
983         if (isvector(b)) {
984             if (fold_can_2(a, b))
985                 return fold_constgen_vector(fold, vec3_and(fold_immvalue_vector(a), fold_immvalue_vector(b)));
986         } else {
987             if (fold_can_2(a, b))
988                 return fold_constgen_vector(fold, vec3_andvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
989         }
990     }
991     return NULL;
992 }
993
994 static GMQCC_INLINE ast_expression *fold_op_xor(fold_t *fold, ast_value *a, ast_value *b) {
995     if (isfloat(a)) {
996         if (fold_can_2(a, b))
997             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) ^ ((qcint_t)fold_immvalue_float(b))), false);
998     } else {
999         if (fold_can_2(a, b)) {
1000             if (isvector(b))
1001                 return fold_constgen_vector(fold, vec3_xor(fold_immvalue_vector(a), fold_immvalue_vector(b)));
1002             else
1003                 return fold_constgen_vector(fold, vec3_xorvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
1004         }
1005     }
1006     return NULL;
1007 }
1008
1009 static GMQCC_INLINE ast_expression *fold_op_lshift(fold_t *fold, ast_value *a, ast_value *b) {
1010     if (fold_can_2(a, b) && isfloats(a, b))
1011         return fold_constgen_float(fold, (qcfloat_t)floorf(fold_immvalue_float(a) * powf(2.0f, fold_immvalue_float(b))), false);
1012     return NULL;
1013 }
1014
1015 static GMQCC_INLINE ast_expression *fold_op_rshift(fold_t *fold, ast_value *a, ast_value *b) {
1016     if (fold_can_2(a, b) && isfloats(a, b))
1017         return fold_constgen_float(fold, (qcfloat_t)floorf(fold_immvalue_float(a) / powf(2.0f, fold_immvalue_float(b))), false);
1018     return NULL;
1019 }
1020
1021 static GMQCC_INLINE ast_expression *fold_op_andor(fold_t *fold, ast_value *a, ast_value *b, float expr) {
1022     if (fold_can_2(a, b)) {
1023         if (OPTS_FLAG(PERL_LOGIC)) {
1024             if (expr)
1025                 return (fold_immediate_true(fold, a)) ? (ast_expression*)a : (ast_expression*)b;
1026             else
1027                 return (fold_immediate_true(fold, a)) ? (ast_expression*)b : (ast_expression*)a;
1028         } else {
1029             return fold_constgen_float (
1030                 fold,
1031                 ((expr) ? (fold_immediate_true(fold, a) || fold_immediate_true(fold, b))
1032                         : (fold_immediate_true(fold, a) && fold_immediate_true(fold, b)))
1033                             ? 1
1034                             : 0,
1035                 false
1036             );
1037         }
1038     }
1039     return NULL;
1040 }
1041
1042 static GMQCC_INLINE ast_expression *fold_op_tern(fold_t *fold, ast_value *a, ast_value *b, ast_value *c) {
1043     if (fold_can_1(a)) {
1044         return fold_immediate_true(fold, a)
1045                     ? (ast_expression*)b
1046                     : (ast_expression*)c;
1047     }
1048     return NULL;
1049 }
1050
1051 static GMQCC_INLINE ast_expression *fold_op_exp(fold_t *fold, ast_value *a, ast_value *b) {
1052     if (fold_can_2(a, b))
1053         return fold_constgen_float(fold, (qcfloat_t)powf(fold_immvalue_float(a), fold_immvalue_float(b)), false);
1054     return NULL;
1055 }
1056
1057 static GMQCC_INLINE ast_expression *fold_op_lteqgt(fold_t *fold, ast_value *a, ast_value *b) {
1058     if (fold_can_2(a,b)) {
1059         fold_check_inexact_float(fold, a, b);
1060         if (fold_immvalue_float(a) <  fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[2];
1061         if (fold_immvalue_float(a) == fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[0];
1062         if (fold_immvalue_float(a) >  fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[1];
1063     }
1064     return NULL;
1065 }
1066
1067 static GMQCC_INLINE ast_expression *fold_op_ltgt(fold_t *fold, ast_value *a, ast_value *b, bool lt) {
1068     if (fold_can_2(a, b)) {
1069         fold_check_inexact_float(fold, a, b);
1070         return (lt) ? (ast_expression*)fold->imm_float[!!(fold_immvalue_float(a) < fold_immvalue_float(b))]
1071                     : (ast_expression*)fold->imm_float[!!(fold_immvalue_float(a) > fold_immvalue_float(b))];
1072     }
1073     return NULL;
1074 }
1075
1076 static GMQCC_INLINE ast_expression *fold_op_cmp(fold_t *fold, ast_value *a, ast_value *b, bool ne) {
1077     if (fold_can_2(a, b)) {
1078         if (isfloat(a) && isfloat(b)) {
1079             float la = fold_immvalue_float(a);
1080             float lb = fold_immvalue_float(b);
1081             fold_check_inexact_float(fold, a, b);
1082             return (ast_expression*)fold->imm_float[!(ne ? la == lb : la != lb)];
1083         } if (isvector(a) && isvector(b)) {
1084             vec3_t la = fold_immvalue_vector(a);
1085             vec3_t lb = fold_immvalue_vector(b);
1086             return (ast_expression*)fold->imm_float[!(ne ? vec3_cmp(la, lb) : !vec3_cmp(la, lb))];
1087         }
1088     }
1089     return NULL;
1090 }
1091
1092 static GMQCC_INLINE ast_expression *fold_op_bnot(fold_t *fold, ast_value *a) {
1093     if (isfloat(a)) {
1094         if (fold_can_1(a))
1095             return fold_constgen_float(fold, -1-fold_immvalue_float(a), false);
1096     } else {
1097         if (isvector(a)) {
1098             if (fold_can_1(a))
1099                 return fold_constgen_vector(fold, vec3_not(fold_immvalue_vector(a)));
1100         }
1101     }
1102     return NULL;
1103 }
1104
1105 static GMQCC_INLINE ast_expression *fold_op_cross(fold_t *fold, ast_value *a, ast_value *b) {
1106     if (fold_can_2(a, b))
1107         return fold_constgen_vector(fold, vec3_cross(fold_immvalue_vector(a), fold_immvalue_vector(b)));
1108     return NULL;
1109 }
1110
1111 ast_expression *fold_op(fold_t *fold, const oper_info *info, ast_expression **opexprs) {
1112     ast_value      *a = (ast_value*)opexprs[0];
1113     ast_value      *b = (ast_value*)opexprs[1];
1114     ast_value      *c = (ast_value*)opexprs[2];
1115     ast_expression *e = NULL;
1116
1117     /* can a fold operation be applied to this operator usage? */
1118     if (!info->folds)
1119         return NULL;
1120
1121     switch(info->operands) {
1122         case 3: if(!c) return NULL;
1123         case 2: if(!b) return NULL;
1124         case 1:
1125         if(!a) {
1126             compile_error(fold_ctx(fold), "internal error: fold_op no operands to fold\n");
1127             return NULL;
1128         }
1129     }
1130
1131     /*
1132      * we could use a boolean and default case but ironically gcc produces
1133      * invalid broken assembly from that operation. clang/tcc get it right,
1134      * but interestingly ignore compiling this to a jump-table when I do that,
1135      * this happens to be the most efficent method, since you have per-level
1136      * granularity on the pointer check happening only for the case you check
1137      * it in. Opposed to the default method which would involve a boolean and
1138      * pointer check after wards.
1139      */
1140     #define fold_op_case(ARGS, ARGS_OPID, OP, ARGS_FOLD)    \
1141         case opid##ARGS ARGS_OPID:                          \
1142             if ((e = fold_op_##OP ARGS_FOLD)) {             \
1143                 ++opts_optimizationcount[OPTIM_CONST_FOLD]; \
1144             }                                               \
1145             return e
1146
1147     switch(info->id) {
1148         fold_op_case(2, ('-', 'P'),    neg,    (fold, a));
1149         fold_op_case(2, ('!', 'P'),    not,    (fold, a));
1150         fold_op_case(1, ('+'),         add,    (fold, a, b));
1151         fold_op_case(1, ('-'),         sub,    (fold, a, b));
1152         fold_op_case(1, ('*'),         mul,    (fold, a, b));
1153         fold_op_case(1, ('/'),         div,    (fold, a, b));
1154         fold_op_case(1, ('%'),         mod,    (fold, a, b));
1155         fold_op_case(1, ('|'),         bor,    (fold, a, b));
1156         fold_op_case(1, ('&'),         band,   (fold, a, b));
1157         fold_op_case(1, ('^'),         xor,    (fold, a, b));
1158         fold_op_case(1, ('<'),         ltgt,   (fold, a, b, true));
1159         fold_op_case(1, ('>'),         ltgt,   (fold, a, b, false));
1160         fold_op_case(2, ('<', '<'),    lshift, (fold, a, b));
1161         fold_op_case(2, ('>', '>'),    rshift, (fold, a, b));
1162         fold_op_case(2, ('|', '|'),    andor,  (fold, a, b, true));
1163         fold_op_case(2, ('&', '&'),    andor,  (fold, a, b, false));
1164         fold_op_case(2, ('?', ':'),    tern,   (fold, a, b, c));
1165         fold_op_case(2, ('*', '*'),    exp,    (fold, a, b));
1166         fold_op_case(3, ('<','=','>'), lteqgt, (fold, a, b));
1167         fold_op_case(2, ('!', '='),    cmp,    (fold, a, b, true));
1168         fold_op_case(2, ('=', '='),    cmp,    (fold, a, b, false));
1169         fold_op_case(2, ('~', 'P'),    bnot,   (fold, a));
1170         fold_op_case(2, ('>', '<'),    cross,  (fold, a, b));
1171     }
1172     #undef fold_op_case
1173     compile_error(fold_ctx(fold), "internal error: attempted to constant-fold for unsupported operator");
1174     return NULL;
1175 }
1176
1177 /*
1178  * Constant folding for compiler intrinsics, simaler approach to operator
1179  * folding, primarly: individual functions for each intrinsics to fold,
1180  * and a generic selection function.
1181  */
1182 static GMQCC_INLINE ast_expression *fold_intrin_isfinite(fold_t *fold, ast_value *a) {
1183     return fold_constgen_float(fold, isfinite(fold_immvalue_float(a)), false);
1184 }
1185 static GMQCC_INLINE ast_expression *fold_intrin_isinf(fold_t *fold, ast_value *a) {
1186     return fold_constgen_float(fold, isinf(fold_immvalue_float(a)), false);
1187 }
1188 static GMQCC_INLINE ast_expression *fold_intrin_isnan(fold_t *fold, ast_value *a) {
1189     return fold_constgen_float(fold, isnan(fold_immvalue_float(a)), false);
1190 }
1191 static GMQCC_INLINE ast_expression *fold_intrin_isnormal(fold_t *fold, ast_value *a) {
1192     return fold_constgen_float(fold, isnormal(fold_immvalue_float(a)), false);
1193 }
1194 static GMQCC_INLINE ast_expression *fold_intrin_signbit(fold_t *fold, ast_value *a) {
1195     return fold_constgen_float(fold, signbit(fold_immvalue_float(a)), false);
1196 }
1197 static GMQCC_INLINE ast_expression *fold_intirn_acosh(fold_t *fold, ast_value *a) {
1198     return fold_constgen_float(fold, acoshf(fold_immvalue_float(a)), false);
1199 }
1200 static GMQCC_INLINE ast_expression *fold_intrin_asinh(fold_t *fold, ast_value *a) {
1201     return fold_constgen_float(fold, asinhf(fold_immvalue_float(a)), false);
1202 }
1203 static GMQCC_INLINE ast_expression *fold_intrin_atanh(fold_t *fold, ast_value *a) {
1204     return fold_constgen_float(fold, (float)atanh(fold_immvalue_float(a)), false);
1205 }
1206 static GMQCC_INLINE ast_expression *fold_intrin_exp(fold_t *fold, ast_value *a) {
1207     return fold_constgen_float(fold, expf(fold_immvalue_float(a)), false);
1208 }
1209 static GMQCC_INLINE ast_expression *fold_intrin_exp2(fold_t *fold, ast_value *a) {
1210     return fold_constgen_float(fold, exp2f(fold_immvalue_float(a)), false);
1211 }
1212 static GMQCC_INLINE ast_expression *fold_intrin_expm1(fold_t *fold, ast_value *a) {
1213     return fold_constgen_float(fold, expm1f(fold_immvalue_float(a)), false);
1214 }
1215 static GMQCC_INLINE ast_expression *fold_intrin_mod(fold_t *fold, ast_value *lhs, ast_value *rhs) {
1216     return fold_constgen_float(fold, fmodf(fold_immvalue_float(lhs), fold_immvalue_float(rhs)), false);
1217 }
1218 static GMQCC_INLINE ast_expression *fold_intrin_pow(fold_t *fold, ast_value *lhs, ast_value *rhs) {
1219     return fold_constgen_float(fold, powf(fold_immvalue_float(lhs), fold_immvalue_float(rhs)), false);
1220 }
1221 static GMQCC_INLINE ast_expression *fold_intrin_fabs(fold_t *fold, ast_value *a) {
1222     return fold_constgen_float(fold, fabsf(fold_immvalue_float(a)), false);
1223 }
1224
1225
1226 ast_expression *fold_intrin(fold_t *fold, const char *intrin, ast_expression **arg) {
1227     ast_expression *ret = NULL;
1228     ast_value      *a   = (ast_value*)arg[0];
1229     ast_value      *b   = (ast_value*)arg[1];
1230
1231     if (!strcmp(intrin, "isfinite")) ret = fold_intrin_isfinite(fold, a);
1232     if (!strcmp(intrin, "isinf"))    ret = fold_intrin_isinf(fold, a);
1233     if (!strcmp(intrin, "isnan"))    ret = fold_intrin_isnan(fold, a);
1234     if (!strcmp(intrin, "isnormal")) ret = fold_intrin_isnormal(fold, a);
1235     if (!strcmp(intrin, "signbit"))  ret = fold_intrin_signbit(fold, a);
1236     if (!strcmp(intrin, "acosh"))    ret = fold_intirn_acosh(fold, a);
1237     if (!strcmp(intrin, "asinh"))    ret = fold_intrin_asinh(fold, a);
1238     if (!strcmp(intrin, "atanh"))    ret = fold_intrin_atanh(fold, a);
1239     if (!strcmp(intrin, "exp"))      ret = fold_intrin_exp(fold, a);
1240     if (!strcmp(intrin, "exp2"))     ret = fold_intrin_exp2(fold, a);
1241     if (!strcmp(intrin, "expm1"))    ret = fold_intrin_expm1(fold, a);
1242     if (!strcmp(intrin, "mod"))      ret = fold_intrin_mod(fold, a, b);
1243     if (!strcmp(intrin, "pow"))      ret = fold_intrin_pow(fold, a, b);
1244     if (!strcmp(intrin, "fabs"))     ret = fold_intrin_fabs(fold, a);
1245
1246     if (ret)
1247         ++opts_optimizationcount[OPTIM_CONST_FOLD];
1248
1249     return ret;
1250 }
1251
1252 /*
1253  * These are all the actual constant folding methods that happen in between
1254  * the AST/IR stage of the compiler , i.e eliminating branches for const
1255  * expressions, which is the only supported thing so far. We undefine the
1256  * testing macros here because an ir_value is differant than an ast_value.
1257  */
1258 #undef expect
1259 #undef isfloat
1260 #undef isstring
1261 #undef isvector
1262 #undef fold_immvalue_float
1263 #undef fold_immvalue_string
1264 #undef fold_immvalue_vector
1265 #undef fold_can_1
1266 #undef fold_can_2
1267
1268 #define isfloat(X)              ((X)->vtype == TYPE_FLOAT)
1269 /*#define isstring(X)             ((X)->vtype == TYPE_STRING)*/
1270 /*#define isvector(X)             ((X)->vtype == TYPE_VECTOR)*/
1271 #define fold_immvalue_float(X)  ((X)->constval.vfloat)
1272 #define fold_immvalue_vector(X) ((X)->constval.vvec)
1273 /*#define fold_immvalue_string(X) ((X)->constval.vstring)*/
1274 #define fold_can_1(X)           ((X)->hasvalue && (X)->cvq == CV_CONST)
1275 /*#define fold_can_2(X,Y)         (fold_can_1(X) && fold_can_1(Y))*/
1276
1277 static ast_expression *fold_superfluous(ast_expression *left, ast_expression *right, int op) {
1278     ast_expression *swapped = NULL; /* using this as bool */
1279     ast_value *load;
1280
1281     if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right))) {
1282         swapped = left;
1283         left    = right;
1284         right   = swapped;
1285     }
1286
1287     if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right)))
1288         return NULL;
1289
1290     switch (op) {
1291         case INSTR_DIV_F:
1292             if (swapped)
1293                 return NULL;
1294         case INSTR_MUL_F:
1295             if (fold_immvalue_float(load) == 1.0f) {
1296                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1297                 ast_unref(right);
1298                 return left;
1299             }
1300             break;
1301
1302
1303         case INSTR_SUB_F:
1304             if (swapped)
1305                 return NULL;
1306         case INSTR_ADD_F:
1307             if (fold_immvalue_float(load) == 0.0f) {
1308                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1309                 ast_unref(right);
1310                 return left;
1311             }
1312             break;
1313
1314         case INSTR_MUL_V:
1315             if (vec3_cmp(fold_immvalue_vector(load), vec3_create(1, 1, 1))) {
1316                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1317                 ast_unref(right);
1318                 return left;
1319             }
1320             break;
1321
1322         case INSTR_SUB_V:
1323             if (swapped)
1324                 return NULL;
1325         case INSTR_ADD_V:
1326             if (vec3_cmp(fold_immvalue_vector(load), vec3_create(0, 0, 0))) {
1327                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1328                 ast_unref(right);
1329                 return left;
1330             }
1331             break;
1332     }
1333
1334     return NULL;
1335 }
1336
1337 ast_expression *fold_binary(lex_ctx_t ctx, int op, ast_expression *left, ast_expression *right) {
1338     ast_expression *ret = fold_superfluous(left, right, op);
1339     if (ret)
1340         return ret;
1341     return (ast_expression*)ast_binary_new(ctx, op, left, right);
1342 }
1343
1344 static GMQCC_INLINE int fold_cond(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1345     if (isfloat(condval) && fold_can_1(condval) && OPTS_OPTIMIZATION(OPTIM_CONST_FOLD_DCE)) {
1346         ast_expression_codegen *cgen;
1347         ir_block               *elide;
1348         ir_value               *dummy;
1349         bool                    istrue  = (fold_immvalue_float(condval) != 0.0f && branch->on_true);
1350         bool                    isfalse = (fold_immvalue_float(condval) == 0.0f && branch->on_false);
1351         ast_expression         *path    = (istrue)  ? branch->on_true  :
1352                                           (isfalse) ? branch->on_false : NULL;
1353         if (!path) {
1354             /*
1355              * no path to take implies that the evaluation is if(0) and there
1356              * is no else block. so eliminate all the code.
1357              */
1358             ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1359             return true;
1360         }
1361
1362         if (!(elide = ir_function_create_block(ast_ctx(branch), func->ir_func, ast_function_label(func, ((istrue) ? "ontrue" : "onfalse")))))
1363             return false;
1364         if (!(*(cgen = path->codegen))((ast_expression*)path, func, false, &dummy))
1365             return false;
1366         if (!ir_block_create_jump(func->curblock, ast_ctx(branch), elide))
1367             return false;
1368         /*
1369          * now the branch has been eliminated and the correct block for the constant evaluation
1370          * is expanded into the current block for the function.
1371          */
1372         func->curblock = elide;
1373         ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1374         return true;
1375     }
1376     return -1; /* nothing done */
1377 }
1378
1379 int fold_cond_ternary(ir_value *condval, ast_function *func, ast_ternary *branch) {
1380     return fold_cond(condval, func, (ast_ifthen*)branch);
1381 }
1382
1383 int fold_cond_ifthen(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1384     return fold_cond(condval, func, branch);
1385 }