]> de.git.xonotic.org Git - xonotic/gmqcc.git/blob - fold.c
ffa0f655b3d4d34317b98649889a6f51ec3453cf
[xonotic/gmqcc.git] / fold.c
1 /*
2  * Copyright (C) 2012, 2013
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  * There is two stages to constant folding in GMQCC: there is the parse
34  * stage constant folding, where, witht he help of the AST, operator
35  * usages can be constant folded. Then there is the constant folding
36  * in the IR for things like eliding if statements, can occur.
37  *
38  * This file is thus, split into two parts.
39  */
40
41 #define isfloat(X)      (((ast_expression*)(X))->vtype == TYPE_FLOAT)
42 #define isvector(X)     (((ast_expression*)(X))->vtype == TYPE_VECTOR)
43 #define isstring(X)     (((ast_expression*)(X))->vtype == TYPE_STRING)
44 #define isfloats(X,Y)   (isfloat  (X) && isfloat (Y))
45
46 /*
47  * Implementation of basic vector math for vec3_t, for trivial constant
48  * folding.
49  *
50  * TODO: gcc/clang hinting for autovectorization
51  */
52 static GMQCC_INLINE vec3_t vec3_add(vec3_t a, vec3_t b) {
53     vec3_t out;
54     out.x = a.x + b.x;
55     out.y = a.y + b.y;
56     out.z = a.z + b.z;
57     return out;
58 }
59
60 static GMQCC_INLINE vec3_t vec3_sub(vec3_t a, vec3_t b) {
61     vec3_t out;
62     out.x = a.x + b.x;
63     out.y = a.y + b.y;
64     out.z = a.z + b.z;
65     return out;
66 }
67
68 static GMQCC_INLINE vec3_t vec3_neg(vec3_t a) {
69     vec3_t out;
70     out.x = -a.x;
71     out.y = -a.y;
72     out.z = -a.z;
73     return out;
74 }
75
76 static GMQCC_INLINE vec3_t vec3_or(vec3_t a, vec3_t b) {
77     vec3_t out;
78     out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b.x));
79     out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b.y));
80     out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b.z));
81     return out;
82 }
83
84 static GMQCC_INLINE vec3_t vec3_orvf(vec3_t a, qcfloat_t b) {
85     vec3_t out;
86     out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b));
87     out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b));
88     out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b));
89     return out;
90 }
91
92 static GMQCC_INLINE vec3_t vec3_and(vec3_t a, vec3_t b) {
93     vec3_t out;
94     out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b.x));
95     out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b.y));
96     out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b.z));
97     return out;
98 }
99
100 static GMQCC_INLINE vec3_t vec3_andvf(vec3_t a, qcfloat_t b) {
101     vec3_t out;
102     out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b));
103     out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b));
104     out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b));
105     return out;
106 }
107
108 static GMQCC_INLINE vec3_t vec3_xor(vec3_t a, vec3_t b) {
109     vec3_t out;
110     out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b.x));
111     out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b.y));
112     out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b.z));
113     return out;
114 }
115
116 static GMQCC_INLINE vec3_t vec3_xorvf(vec3_t a, qcfloat_t b) {
117     vec3_t out;
118     out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b));
119     out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b));
120     out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b));
121     return out;
122 }
123
124 static GMQCC_INLINE vec3_t vec3_not(vec3_t a) {
125     vec3_t out;
126     out.x = (qcfloat_t)(~((qcint_t)a.x));
127     out.y = (qcfloat_t)(~((qcint_t)a.y));
128     out.z = (qcfloat_t)(~((qcint_t)a.z));
129     return out;
130 }
131
132 static GMQCC_INLINE qcfloat_t vec3_mulvv(vec3_t a, vec3_t b) {
133     return (a.x * b.x + a.y * b.y + a.z * b.z);
134 }
135
136 static GMQCC_INLINE vec3_t vec3_mulvf(vec3_t a, qcfloat_t b) {
137     vec3_t out;
138     out.x = a.x * b;
139     out.y = a.y * b;
140     out.z = a.z * b;
141     return out;
142 }
143
144 static GMQCC_INLINE bool vec3_cmp(vec3_t a, vec3_t b) {
145     return a.x == b.x &&
146            a.y == b.y &&
147            a.z == b.z;
148 }
149
150 static GMQCC_INLINE vec3_t vec3_create(float x, float y, float z) {
151     vec3_t out;
152     out.x = x;
153     out.y = y;
154     out.z = z;
155     return out;
156 }
157
158 static GMQCC_INLINE qcfloat_t vec3_notf(vec3_t a) {
159     return (!a.x && !a.y && !a.z);
160 }
161
162 static GMQCC_INLINE bool vec3_pbool(vec3_t a) {
163     return (a.x && a.y && a.z);
164 }
165
166 static GMQCC_INLINE vec3_t vec3_cross(vec3_t a, vec3_t b) {
167     vec3_t out;
168     out.x = a.y * b.z - a.z * b.y;
169     out.y = a.z * b.x - a.x * b.z;
170     out.z = a.x * b.y - a.y * b.x;
171     return out;
172 }
173
174 static lex_ctx_t fold_ctx(fold_t *fold) {
175     lex_ctx_t ctx;
176     if (fold->parser->lex)
177         return parser_ctx(fold->parser);
178
179     memset(&ctx, 0, sizeof(ctx));
180     return ctx;
181 }
182
183 static GMQCC_INLINE bool fold_immediate_true(fold_t *fold, ast_value *v) {
184     switch (v->expression.vtype) {
185         case TYPE_FLOAT:
186             return !!v->constval.vfloat;
187         case TYPE_INTEGER:
188             return !!v->constval.vint;
189         case TYPE_VECTOR:
190             if (OPTS_FLAG(CORRECT_LOGIC))
191                 return vec3_pbool(v->constval.vvec);
192             return !!(v->constval.vvec.x);
193         case TYPE_STRING:
194             if (!v->constval.vstring)
195                 return false;
196             if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
197                 return true;
198             return !!v->constval.vstring[0];
199         default:
200             compile_error(fold_ctx(fold), "internal error: fold_immediate_true on invalid type");
201             break;
202     }
203     return !!v->constval.vfunc;
204 }
205
206 /* Handy macros to determine if an ast_value can be constant folded. */
207 #define fold_can_1(X)  \
208     (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
209                 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
210
211 #define fold_can_2(X, Y) (fold_can_1(X) && fold_can_1(Y))
212 #define fold_can_div(X) (fold_immvalue_float(X) != 0.0f)
213
214 #define fold_immvalue_float(E)  ((E)->constval.vfloat)
215 #define fold_immvalue_vector(E) ((E)->constval.vvec)
216 #define fold_immvalue_string(E) ((E)->constval.vstring)
217
218 #ifdef INFINITY
219 #   define fold_infinity_float  INFINITY
220 #else
221 #   define fold_infinity_float  (1.0 / 0.0)
222 #endif /*! INFINITY */
223
224 #define fold_infinity_vector \
225     vec3_create(             \
226         fold_infinity_float, \
227         fold_infinity_float, \
228         fold_infinity_float  \
229     )
230
231 fold_t *fold_init(parser_t *parser) {
232     fold_t *fold                 = (fold_t*)mem_a(sizeof(fold_t));
233     fold->parser                 = parser;
234     fold->imm_float              = NULL;
235     fold->imm_vector             = NULL;
236     fold->imm_string             = NULL;
237     fold->imm_string_untranslate = util_htnew(FOLD_STRING_UNTRANSLATE_HTSIZE);
238     fold->imm_string_dotranslate = util_htnew(FOLD_STRING_DOTRANSLATE_HTSIZE);
239
240     /*
241      * prime the tables with common constant values at constant
242      * locations.
243      */
244     (void)fold_constgen_float (fold,  0.0f);
245     (void)fold_constgen_float (fold,  1.0f);
246     (void)fold_constgen_float (fold, -1.0f);
247     (void)fold_constgen_float (fold,  fold_infinity_float); /* +inf */
248
249     (void)fold_constgen_vector(fold, vec3_create(0.0f, 0.0f, 0.0f));
250     (void)fold_constgen_vector(fold, vec3_create(-1.0f, -1.0f, -1.0f));
251     (void)fold_constgen_vector(fold, fold_infinity_vector); /* +inf */
252
253     return fold;
254 }
255
256 bool fold_generate(fold_t *fold, ir_builder *ir) {
257     /* generate globals for immediate folded values */
258     size_t     i;
259     ast_value *cur;
260
261     for (i = 0; i < vec_size(fold->imm_float);   ++i)
262         if (!ast_global_codegen ((cur = fold->imm_float[i]), ir, false)) goto err;
263     for (i = 0; i < vec_size(fold->imm_vector);  ++i)
264         if (!ast_global_codegen((cur = fold->imm_vector[i]), ir, false)) goto err;
265     for (i = 0; i < vec_size(fold->imm_string);  ++i)
266         if (!ast_global_codegen((cur = fold->imm_string[i]), ir, false)) goto err;
267
268     return true;
269
270 err:
271     con_out("failed to generate global %s\n", cur->name);
272     ir_builder_delete(ir);
273     return false;
274 }
275
276 void fold_cleanup(fold_t *fold) {
277     size_t i;
278
279     for (i = 0; i < vec_size(fold->imm_float);  ++i) ast_delete(fold->imm_float[i]);
280     for (i = 0; i < vec_size(fold->imm_vector); ++i) ast_delete(fold->imm_vector[i]);
281     for (i = 0; i < vec_size(fold->imm_string); ++i) ast_delete(fold->imm_string[i]);
282
283     vec_free(fold->imm_float);
284     vec_free(fold->imm_vector);
285     vec_free(fold->imm_string);
286
287     util_htdel(fold->imm_string_untranslate);
288     util_htdel(fold->imm_string_dotranslate);
289
290     mem_d(fold);
291 }
292
293 ast_expression *fold_constgen_float(fold_t *fold, qcfloat_t value) {
294     ast_value  *out = NULL;
295     size_t      i;
296
297     for (i = 0; i < vec_size(fold->imm_float); i++) {
298         if (fold->imm_float[i]->constval.vfloat == value)
299             return (ast_expression*)fold->imm_float[i];
300     }
301
302     out                  = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_FLOAT);
303     out->cvq             = CV_CONST;
304     out->hasvalue        = true;
305     out->constval.vfloat = value;
306
307     vec_push(fold->imm_float, out);
308
309     return (ast_expression*)out;
310 }
311
312 ast_expression *fold_constgen_vector(fold_t *fold, vec3_t value) {
313     ast_value *out;
314     size_t     i;
315
316     for (i = 0; i < vec_size(fold->imm_vector); i++) {
317         if (vec3_cmp(fold->imm_vector[i]->constval.vvec, value))
318             return (ast_expression*)fold->imm_vector[i];
319     }
320
321     out                = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_VECTOR);
322     out->cvq           = CV_CONST;
323     out->hasvalue      = true;
324     out->constval.vvec = value;
325
326     vec_push(fold->imm_vector, out);
327
328     return (ast_expression*)out;
329 }
330
331 ast_expression *fold_constgen_string(fold_t *fold, const char *str, bool translate) {
332     hash_table_t *table = (translate) ? fold->imm_string_untranslate : fold->imm_string_dotranslate;
333     ast_value    *out   = NULL;
334     size_t        hash  = util_hthash(table, str);
335
336     if ((out = (ast_value*)util_htgeth(table, str, hash)))
337         return (ast_expression*)out;
338
339     if (translate) {
340         char name[32];
341         util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(fold->parser->translated++));
342         out                    = ast_value_new(parser_ctx(fold->parser), name, TYPE_STRING);
343         out->expression.flags |= AST_FLAG_INCLUDE_DEF; /* def needs to be included for translatables */
344     } else
345         out                    = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_STRING);
346
347     out->cvq              = CV_CONST;
348     out->hasvalue         = true;
349     out->isimm            = true;
350     out->constval.vstring = parser_strdup(str);
351
352     vec_push(fold->imm_string, out);
353     util_htseth(table, str, hash, out);
354
355     return (ast_expression*)out;
356 }
357
358
359 static GMQCC_INLINE ast_expression *fold_op_mul_vec(fold_t *fold, vec3_t vec, ast_value *sel, const char *set) {
360     /*
361      * vector-component constant folding works by matching the component sets
362      * to eliminate expensive operations on whole-vectors (3 components at runtime).
363      * to achive this effect in a clean manner this function generalizes the
364      * values through the use of a set paramater, which is used as an indexing method
365      * for creating the elided ast binary expression.
366      *
367      * Consider 'n 0 0' where y, and z need to be tested for 0, and x is
368      * used as the value in a binary operation generating an INSTR_MUL instruction,
369      * to acomplish the indexing of the correct component value we use set[0], set[1], set[2]
370      * as x, y, z, where the values of those operations return 'x', 'y', 'z'. Because
371      * of how ASCII works we can easily deliniate:
372      * vec.z is the same as set[2]-'x' for when set[2] is 'z', 'z'-'x' results in a
373      * literal value of 2, using this 2, we know that taking the address of vec->x (float)
374      * and indxing it with this literal will yeild the immediate address of that component
375      *
376      * Of course more work needs to be done to generate the correct index for the ast_member_new
377      * call, which is no problem: set[0]-'x' suffices that job.
378      */
379     qcfloat_t x = (&vec.x)[set[0]-'x'];
380     qcfloat_t y = (&vec.x)[set[1]-'x'];
381     qcfloat_t z = (&vec.x)[set[2]-'x'];
382
383     if (!y && !z) {
384         ast_expression *out;
385         ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
386         out                        = (ast_expression*)ast_member_new(fold_ctx(fold), (ast_expression*)sel, set[0]-'x', NULL);
387         out->node.keep             = false;
388         ((ast_member*)out)->rvalue = true;
389         if (x != -1.0f)
390             return (ast_expression*)ast_binary_new(fold_ctx(fold), INSTR_MUL_F, fold_constgen_float(fold, x), out);
391     }
392     return NULL;
393 }
394
395
396 static GMQCC_INLINE ast_expression *fold_op_neg(fold_t *fold, ast_value *a) {
397     if (isfloat(a)) {
398         if (fold_can_1(a))
399             return fold_constgen_float(fold, -fold_immvalue_float(a));
400     } else if (isvector(a)) {
401         if (fold_can_1(a))
402             return fold_constgen_vector(fold, vec3_neg(fold_immvalue_vector(a)));
403     }
404     return NULL;
405 }
406
407 static GMQCC_INLINE ast_expression *fold_op_not(fold_t *fold, ast_value *a) {
408     if (isfloat(a)) {
409         if (fold_can_1(a))
410             return fold_constgen_float(fold, !fold_immvalue_float(a));
411     } else if (isvector(a)) {
412         if (fold_can_1(a))
413             return fold_constgen_float(fold, vec3_notf(fold_immvalue_vector(a)));
414     } else if (isstring(a)) {
415         if (fold_can_1(a)) {
416             if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
417                 return fold_constgen_float(fold, !fold_immvalue_string(a));
418             else
419                 return fold_constgen_float(fold, !fold_immvalue_string(a) || !*fold_immvalue_string(a));
420         }
421     }
422     return NULL;
423 }
424
425 static GMQCC_INLINE ast_expression *fold_op_add(fold_t *fold, ast_value *a, ast_value *b) {
426     if (isfloat(a)) {
427         if (fold_can_2(a, b))
428             return fold_constgen_float(fold, fold_immvalue_float(a) + fold_immvalue_float(b));
429     } else if (isvector(a)) {
430         if (fold_can_2(a, b))
431             return fold_constgen_vector(fold, vec3_add(fold_immvalue_vector(a), fold_immvalue_vector(b)));
432     }
433     return NULL;
434 }
435
436 static GMQCC_INLINE ast_expression *fold_op_sub(fold_t *fold, ast_value *a, ast_value *b) {
437     if (isfloat(a)) {
438         if (fold_can_2(a, b))
439             return fold_constgen_float(fold, fold_immvalue_float(a) - fold_immvalue_float(b));
440     } else if (isvector(a)) {
441         if (fold_can_2(a, b))
442             return fold_constgen_vector(fold, vec3_sub(fold_immvalue_vector(a), fold_immvalue_vector(b)));
443     }
444     return NULL;
445 }
446
447 static GMQCC_INLINE ast_expression *fold_op_mul(fold_t *fold, ast_value *a, ast_value *b) {
448     if (isfloat(a)) {
449         if (isvector(b)) {
450             if (fold_can_2(a, b))
451                 return fold_constgen_vector(fold, vec3_mulvf(fold_immvalue_vector(b), fold_immvalue_float(a)));
452         } else {
453             if (fold_can_2(a, b))
454                 return fold_constgen_float(fold, fold_immvalue_float(a) * fold_immvalue_float(b));
455         }
456     } else if (isvector(a)) {
457         if (isfloat(b)) {
458             if (fold_can_2(a, b))
459                 return fold_constgen_vector(fold, vec3_mulvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
460         } else {
461             if (fold_can_2(a, b)) {
462                 return fold_constgen_float(fold, vec3_mulvv(fold_immvalue_vector(a), fold_immvalue_vector(b)));
463             } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(a)) {
464                 ast_expression *out;
465                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "xyz"))) return out;
466                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "yxz"))) return out;
467                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "zxy"))) return out;
468             } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(b)) {
469                 ast_expression *out;
470                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "xyz"))) return out;
471                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "yxz"))) return out;
472                 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "zxy"))) return out;
473             }
474         }
475     }
476     return NULL;
477 }
478
479 static GMQCC_INLINE ast_expression *fold_op_div(fold_t *fold, ast_value *a, ast_value *b) {
480     if (isfloat(a)) {
481         if (fold_can_2(a, b)) {
482             if (fold_can_div(b))
483                 return fold_constgen_float(fold, fold_immvalue_float(a) / fold_immvalue_float(b));
484             else
485                 return (ast_expression*)fold->imm_float[3]; /* inf */
486         } else if (fold_can_1(b)) {
487             return (ast_expression*)ast_binary_new(
488                 fold_ctx(fold),
489                 INSTR_MUL_F,
490                 (ast_expression*)a,
491                 fold_constgen_float(fold, 1.0f / fold_immvalue_float(b))
492             );
493         }
494     } else if (isvector(a)) {
495         if (fold_can_2(a, b)) {
496             if (fold_can_div(b)) {
497                 return fold_constgen_vector(fold, vec3_mulvf(fold_immvalue_vector(a), 1.0f / fold_immvalue_float(b)));
498             }
499             else {
500                 return (ast_expression*)fold->imm_vector[2]; /* inf */
501             }
502         } else {
503             return (ast_expression*)ast_binary_new(
504                 fold_ctx(fold),
505                 INSTR_MUL_VF,
506                 (ast_expression*)a,
507                 (fold_can_1(b))
508                     ? (ast_expression*)fold_constgen_float(fold, 1.0f / fold_immvalue_float(b))
509                     : (ast_expression*)ast_binary_new(
510                                             fold_ctx(fold),
511                                             INSTR_DIV_F,
512                                             (ast_expression*)fold->imm_float[1],
513                                             (ast_expression*)b
514                     )
515             );
516         }
517     }
518     return NULL;
519 }
520
521 static GMQCC_INLINE ast_expression *fold_op_mod(fold_t *fold, ast_value *a, ast_value *b) {
522     if (fold_can_2(a, b)) {
523         if (fold_can_div(b))
524             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) % ((qcint_t)fold_immvalue_float(b))));
525         else
526             return (ast_expression*)fold->imm_float[3]; /* inf */
527     }
528     return NULL;
529 }
530
531 static GMQCC_INLINE ast_expression *fold_op_bor(fold_t *fold, ast_value *a, ast_value *b) {
532     if (isfloat(a)) {
533         if (fold_can_2(a, b))
534             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) | ((qcint_t)fold_immvalue_float(b))));
535     } else {
536         if (isvector(b)) {
537             if (fold_can_2(a, b))
538                 return fold_constgen_vector(fold, vec3_or(fold_immvalue_vector(a), fold_immvalue_vector(b)));
539         } else {
540             if (fold_can_2(a, b))
541                 return fold_constgen_vector(fold, vec3_orvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
542         }
543     }
544     return NULL;
545 }
546
547 static GMQCC_INLINE ast_expression *fold_op_band(fold_t *fold, ast_value *a, ast_value *b) {
548     if (isfloat(a)) {
549         if (fold_can_2(a, b))
550             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) & ((qcint_t)fold_immvalue_float(b))));
551     } else {
552         if (isvector(b)) {
553             if (fold_can_2(a, b))
554                 return fold_constgen_vector(fold, vec3_and(fold_immvalue_vector(a), fold_immvalue_vector(b)));
555         } else {
556             if (fold_can_2(a, b))
557                 return fold_constgen_vector(fold, vec3_andvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
558         }
559     }
560     return NULL;
561 }
562
563 static GMQCC_INLINE ast_expression *fold_op_xor(fold_t *fold, ast_value *a, ast_value *b) {
564     if (isfloat(a)) {
565         if (fold_can_2(a, b))
566             return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) ^ ((qcint_t)fold_immvalue_float(b))));
567     } else {
568         if (isvector(b)) {
569             if (fold_can_2(a, b))
570                 return fold_constgen_vector(fold, vec3_xor(fold_immvalue_vector(a), fold_immvalue_vector(b)));
571         } else {
572             if (fold_can_2(a, b))
573                 return fold_constgen_vector(fold, vec3_xorvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
574         }
575     }
576     return NULL;
577 }
578
579 static GMQCC_INLINE ast_expression *fold_op_lshift(fold_t *fold, ast_value *a, ast_value *b) {
580     if (fold_can_2(a, b) && isfloats(a, b))
581         return fold_constgen_float(fold, (qcfloat_t)((qcuint_t)(fold_immvalue_float(a)) << (qcuint_t)(fold_immvalue_float(b))));
582     return NULL;
583 }
584
585 static GMQCC_INLINE ast_expression *fold_op_rshift(fold_t *fold, ast_value *a, ast_value *b) {
586     if (fold_can_2(a, b) && isfloats(a, b))
587         return fold_constgen_float(fold, (qcfloat_t)((qcuint_t)(fold_immvalue_float(a)) >> (qcuint_t)(fold_immvalue_float(b))));
588     return NULL;
589 }
590
591 static GMQCC_INLINE ast_expression *fold_op_andor(fold_t *fold, ast_value *a, ast_value *b, float expr) {
592     if (fold_can_2(a, b)) {
593         if (OPTS_FLAG(PERL_LOGIC)) {
594             if (fold_immediate_true(fold, a))
595                 return (ast_expression*)b;
596         } else {
597             return fold_constgen_float (
598                 fold,
599                 ((expr) ? (fold_immediate_true(fold, a) || fold_immediate_true(fold, b))
600                         : (fold_immediate_true(fold, a) && fold_immediate_true(fold, b)))
601                             ? 1
602                             : 0
603             );
604         }
605     }
606     return NULL;
607 }
608
609 static GMQCC_INLINE ast_expression *fold_op_tern(fold_t *fold, ast_value *a, ast_value *b, ast_value *c) {
610     if (fold_can_1(a)) {
611         return fold_immediate_true(fold, a)
612                     ? (ast_expression*)b
613                     : (ast_expression*)c;
614     }
615     return NULL;
616 }
617
618 static GMQCC_INLINE ast_expression *fold_op_exp(fold_t *fold, ast_value *a, ast_value *b) {
619     if (fold_can_2(a, b))
620         return fold_constgen_float(fold, (qcfloat_t)powf(fold_immvalue_float(a), fold_immvalue_float(b)));
621     return NULL;
622 }
623
624 static GMQCC_INLINE ast_expression *fold_op_lteqgt(fold_t *fold, ast_value *a, ast_value *b) {
625     if (fold_can_2(a,b)) {
626         if (fold_immvalue_float(a) <  fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[2];
627         if (fold_immvalue_float(a) == fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[0];
628         if (fold_immvalue_float(a) >  fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[1];
629     }
630     return NULL;
631 }
632
633 static GMQCC_INLINE ast_expression *fold_op_cmp(fold_t *fold, ast_value *a, ast_value *b, bool ne) {
634     if (fold_can_2(a, b)) {
635         return fold_constgen_float(
636                     fold,
637                     (ne) ? (fold_immvalue_float(a) != fold_immvalue_float(b))
638                          : (fold_immvalue_float(a) == fold_immvalue_float(b))
639                 );
640     }
641     return NULL;
642 }
643
644 static GMQCC_INLINE ast_expression *fold_op_bnot(fold_t *fold, ast_value *a) {
645     if (isfloat(a)) {
646         if (fold_can_1(a))
647             return fold_constgen_float(fold, ~((qcint_t)fold_immvalue_float(a)));
648     } else {
649         if (isvector(a)) {
650             if (fold_can_1(a))
651                 return fold_constgen_vector(fold, vec3_not(fold_immvalue_vector(a)));
652         }
653     }
654     return NULL;
655 }
656
657 static GMQCC_INLINE ast_expression *fold_op_cross(fold_t *fold, ast_value *a, ast_value *b) {
658     if (fold_can_2(a, b))
659         return fold_constgen_vector(fold, vec3_cross(fold_immvalue_vector(a), fold_immvalue_vector(b)));
660     return NULL;
661 }
662
663 ast_expression *fold_op(fold_t *fold, const oper_info *info, ast_expression **opexprs) {
664     ast_value      *a = (ast_value*)opexprs[0];
665     ast_value      *b = (ast_value*)opexprs[1];
666     ast_value      *c = (ast_value*)opexprs[2];
667     ast_expression *e = NULL;
668
669     /* can a fold operation be applied to this operator usage? */
670     if (!info->folds)
671         return NULL;
672
673     switch(info->operands) {
674         case 3: if(!c) return NULL;
675         case 2: if(!b) return NULL;
676         case 1:
677         if(!a) {
678             compile_error(fold_ctx(fold), "internal error: fold_op no operands to fold\n");
679             return NULL;
680         }
681     }
682
683     /*
684      * we could use a boolean and default case but ironically gcc produces
685      * invalid broken assembly from that operation. clang/tcc get it right,
686      * but interestingly ignore compiling this to a jump-table when I do that,
687      * this happens to be the most efficent method, since you have per-level
688      * granularity on the pointer check happening only for the case you check
689      * it in. Opposed to the default method which would involve a boolean and
690      * pointer check after wards.
691      */
692     #define fold_op_case(ARGS, ARGS_OPID, OP, ARGS_FOLD)    \
693         case opid##ARGS ARGS_OPID:                          \
694             if ((e = fold_op_##OP ARGS_FOLD)) {             \
695                 ++opts_optimizationcount[OPTIM_CONST_FOLD]; \
696             }                                               \
697             return e
698
699     switch(info->id) {
700         fold_op_case(2, ('-', 'P'),    neg,    (fold, a));
701         fold_op_case(2, ('!', 'P'),    not,    (fold, a));
702         fold_op_case(1, ('+'),         add,    (fold, a, b));
703         fold_op_case(1, ('-'),         sub,    (fold, a, b));
704         fold_op_case(1, ('*'),         mul,    (fold, a, b));
705         fold_op_case(1, ('/'),         div,    (fold, a, b));
706         fold_op_case(1, ('%'),         mod,    (fold, a, b));
707         fold_op_case(1, ('|'),         bor,    (fold, a, b));
708         fold_op_case(1, ('&'),         band,   (fold, a, b));
709         fold_op_case(1, ('^'),         xor,    (fold, a, b));
710         fold_op_case(2, ('<', '<'),    lshift, (fold, a, b));
711         fold_op_case(2, ('>', '>'),    rshift, (fold, a, b));
712         fold_op_case(2, ('|', '|'),    andor,  (fold, a, b, true));
713         fold_op_case(2, ('&', '&'),    andor,  (fold, a, b, false));
714         fold_op_case(2, ('?', ':'),    tern,   (fold, a, b, c));
715         fold_op_case(2, ('*', '*'),    exp,    (fold, a, b));
716         fold_op_case(3, ('<','=','>'), lteqgt, (fold, a, b));
717         fold_op_case(2, ('!', '='),    cmp,    (fold, a, b, true));
718         fold_op_case(2, ('=', '='),    cmp,    (fold, a, b, false));
719         fold_op_case(2, ('~', 'P'),    bnot,   (fold, a));
720         fold_op_case(2, ('>', '<'),    cross,  (fold, a, b));
721     }
722     #undef fold_op_case
723     compile_error(fold_ctx(fold), "internal error: attempted to constant-fold for unsupported operator");
724     return NULL;
725 }
726
727 /*
728  * Constant folding for compiler intrinsics, simaler approach to operator
729  * folding, primarly: individual functions for each intrinsics to fold,
730  * and a generic selection function.
731  */
732 static GMQCC_INLINE ast_expression *fold_intrin_mod(fold_t *fold, ast_value *lhs, ast_value *rhs) {
733     return fold_constgen_float(
734                 fold,
735                 fmodf(
736                     fold_immvalue_float(lhs),
737                     fold_immvalue_float(rhs)
738                 )
739             );
740 }
741
742 static GMQCC_INLINE ast_expression *fold_intrin_pow(fold_t *fold, ast_value *lhs, ast_value *rhs) {
743     return fold_constgen_float(
744                 fold,
745                 powf(
746                     fold_immvalue_float(lhs),
747                     fold_immvalue_float(rhs)
748                 )
749             );
750 }
751
752 static GMQCC_INLINE ast_expression *fold_intrin_exp(fold_t *fold, ast_value *value) {
753     return fold_constgen_float(fold, exp(fold_immvalue_float(value)));
754 }
755
756 static GMQCC_INLINE ast_expression *fold_intrin_isnan(fold_t *fold, ast_value *value) {
757     return fold_constgen_float(fold, isnan(fold_immvalue_float(value)) != 0.0f);
758 }
759
760 static GMQCC_INLINE ast_expression *fold_intrin_fabs(fold_t *fold, ast_value *value) {
761     return fold_constgen_float(fold, fabs(fold_immvalue_float(value)));
762 }
763
764 ast_expression *fold_intrin(fold_t *fold, const char *intrin, ast_expression **arg) {
765     if (!strcmp(intrin, "mod"))   return fold_intrin_mod  (fold, (ast_value*)arg[0], (ast_value*)arg[1]);
766     if (!strcmp(intrin, "pow"))   return fold_intrin_pow  (fold, (ast_value*)arg[0], (ast_value*)arg[1]);
767     if (!strcmp(intrin, "exp"))   return fold_intrin_exp  (fold, (ast_value*)arg[0]);
768     if (!strcmp(intrin, "isnan")) return fold_intrin_isnan(fold, (ast_value*)arg[0]);
769     if (!strcmp(intrin, "fabs"))  return fold_intrin_fabs (fold, (ast_value*)arg[0]);
770
771     return NULL;
772 }
773
774 /*
775  * These are all the actual constant folding methods that happen in between
776  * the AST/IR stage of the compiler , i.e eliminating branches for const
777  * expressions, which is the only supported thing so far. We undefine the
778  * testing macros here because an ir_value is differant than an ast_value.
779  */
780 #undef expect
781 #undef isfloat
782 #undef isstring
783 #undef isvector
784 #undef fold_immvalue_float
785 #undef fold_immvalue_string
786 #undef fold_immvalue_vector
787 #undef fold_can_1
788 #undef fold_can_2
789
790 #define isfloat(X)              ((X)->vtype == TYPE_FLOAT)
791 /*#define isstring(X)             ((X)->vtype == TYPE_STRING)*/
792 /*#define isvector(X)             ((X)->vtype == TYPE_VECTOR)*/
793 #define fold_immvalue_float(X)  ((X)->constval.vfloat)
794 #define fold_immvalue_vector(X) ((X)->constval.vvec)
795 /*#define fold_immvalue_string(X) ((X)->constval.vstring)*/
796 #define fold_can_1(X)           ((X)->hasvalue && (X)->cvq == CV_CONST)
797 /*#define fold_can_2(X,Y)         (fold_can_1(X) && fold_can_1(Y))*/
798
799 ast_expression *fold_superfluous(ast_expression *left, ast_expression *right, int op) {
800     ast_value *load;
801
802     if (!ast_istype(left, ast_value) || !fold_can_1((load = (ast_value*)right)))
803         return NULL;
804
805     switch (op) {
806         case INSTR_MUL_F:
807         case INSTR_DIV_F:
808             if (fold_immvalue_float(load) == 1.0f) {
809                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
810                 return (ast_expression*)left;
811             }
812             break;
813
814
815         case INSTR_ADD_F:
816         case INSTR_SUB_F:
817             if (fold_immvalue_float(load) == 0.0f) {
818                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
819                 return (ast_expression*)left;
820             }
821             break;
822
823         case INSTR_MUL_V:
824             if (vec3_cmp(fold_immvalue_vector(load), vec3_create(1, 1, 1))) {
825                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
826                 return (ast_expression*)left;
827             }
828             break;
829
830         case INSTR_ADD_V:
831         case INSTR_SUB_V:
832             if (vec3_cmp(fold_immvalue_vector(load), vec3_create(0, 0, 0))) {
833                 ++opts_optimizationcount[OPTIM_PEEPHOLE];
834                 return (ast_expression*)left;
835             }
836             break;
837     }
838
839     return NULL;
840 }
841
842 static GMQCC_INLINE int fold_cond(ir_value *condval, ast_function *func, ast_ifthen *branch) {
843     if (isfloat(condval) && fold_can_1(condval) && OPTS_OPTIMIZATION(OPTIM_CONST_FOLD_DCE)) {
844         ast_expression_codegen *cgen;
845         ir_block               *elide;
846         ir_value               *dummy;
847         bool                    istrue  = (fold_immvalue_float(condval) != 0.0f && branch->on_true);
848         bool                    isfalse = (fold_immvalue_float(condval) == 0.0f && branch->on_false);
849         ast_expression         *path    = (istrue)  ? branch->on_true  :
850                                           (isfalse) ? branch->on_false : NULL;
851         if (!path) {
852             /*
853              * no path to take implies that the evaluation is if(0) and there
854              * is no else block. so eliminate all the code.
855              */
856             ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
857             return true;
858         }
859
860         if (!(elide = ir_function_create_block(ast_ctx(branch), func->ir_func, ast_function_label(func, ((istrue) ? "ontrue" : "onfalse")))))
861             return false;
862         if (!(*(cgen = path->codegen))((ast_expression*)path, func, false, &dummy))
863             return false;
864         if (!ir_block_create_jump(func->curblock, ast_ctx(branch), elide))
865             return false;
866         /*
867          * now the branch has been eliminated and the correct block for the constant evaluation
868          * is expanded into the current block for the function.
869          */
870         func->curblock = elide;
871         ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
872         return true;
873     }
874     return -1; /* nothing done */
875 }
876
877 int fold_cond_ternary(ir_value *condval, ast_function *func, ast_ternary *branch) {
878     return fold_cond(condval, func, (ast_ifthen*)branch);
879 }
880
881 int fold_cond_ifthen(ir_value *condval, ast_function *func, ast_ifthen *branch) {
882     return fold_cond(condval, func, branch);
883 }