2 * Copyright (C) 2012, 2013, 2014
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:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
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
29 #define FOLD_STRING_UNTRANSLATE_HTSIZE 1024
30 #define FOLD_STRING_DOTRANSLATE_HTSIZE 1024
32 /* The options to use for inexact and arithmetic exceptions */
33 #define FOLD_ROUNDING SFLOAT_ROUND_NEAREST_EVEN
34 #define FOLD_TINYNESS SFLOAT_TBEFORE
37 * The constant folder is also responsible for validating if the constant
38 * expressions produce valid results. We cannot trust the FPU control
39 * unit for these exceptions because setting FPU control words might not
40 * work. Systems can set and enforce FPU modes of operation. It's also valid
41 * for libc's to simply ignore FPU exceptions. For instance ARM CPUs in
42 * glibc. We implement some trivial and IEE 754 conformant functions which
43 * emulate those operations. This is an entierly optional compiler feature
44 * which shouldn't be enabled for anything other than performing strict
45 * passes on constant expressions since it's quite slow.
47 typedef uint32_t sfloat_t;
59 SFLOAT_UNDERFLOW = 16,
61 } sfloat_exceptionflags_t;
64 SFLOAT_ROUND_NEAREST_EVEN,
68 } sfloat_roundingmode_t;
76 sfloat_roundingmode_t roundingmode;
77 sfloat_exceptionflags_t exceptionflags;
78 sfloat_tdetect_t tiny;
81 /* Count of leading zero bits before the most-significand 1 bit. */
83 /* MSVC has an intrinsic for this */
84 static GMQCC_INLINE uint32_t sfloat_clz(uint32_t x) {
86 _BitScanForward(&r, x);
89 # define SFLOAT_CLZ(X, SUB) \
90 (sfloat_clz((X)) - (SUB))
91 #elif defined(__GNUC__) || defined(__CLANG__)
92 /* Clang and GCC have a builtin for this */
93 # define SFLOAT_CLZ(X, SUB) \
94 (__builtin_clz((X)) - (SUB))
97 static GMQCC_INLINE uint32_t sfloat_popcnt(uint32_t x) {
98 x -= ((x >> 1) & 0x55555555);
99 x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
100 x = (((x >> 4) + x) & 0x0F0F0F0F);
103 return x & 0x0000003F;
105 static GMQCC_INLINE uint32_t sfloat_clz(uint32_t x) {
111 return 32 - sfloat_popcnt(x);
113 # define SFLOAT_CLZ(X, SUB) \
114 (sfloat_clz((X) - (SUB)))
117 /* The value of a NaN */
118 #define SFLOAT_NAN 0xFFC00000
120 #define SFLOAT_ISNAN(A) \
121 (0xFF000000 < (uint32_t)((A) << 1))
122 /* Test if signaling NaN */
123 #define SFLOAT_ISSNAN(A) \
124 (((((A) >> 22) & 0x1FF) == 0x1FE) && ((A) & 0x003FFFFF))
125 /* Raise exception */
126 #define SFLOAT_RAISE(STATE, FLAGS) \
127 ((STATE)->exceptionflags = (sfloat_exceptionflags_t)((STATE)->exceptionflags | (FLAGS)))
129 * Shifts `A' right `COUNT' bits. Non-zero bits are stored in LSB. Size
130 * sets the arbitrarly-large limit.
132 #define SFLOAT_SHIFT(SIZE, A, COUNT, Z) \
133 *(Z) = ((COUNT) == 0) \
135 : (((COUNT) < (SIZE)) \
136 ? ((A) >> (COUNT)) | (((A) << ((-(COUNT)) & ((SIZE) - 1))) != 0) \
138 /* Extract fractional component */
139 #define SFLOAT_EXTRACT_FRAC(X) \
140 ((uint32_t)((X) & 0x007FFFFF))
141 /* Extract exponent component */
142 #define SFLOAT_EXTRACT_EXP(X) \
143 ((int16_t)((X) >> 23) & 0xFF)
144 /* Extract sign bit */
145 #define SFLOAT_EXTRACT_SIGN(X) \
147 /* Normalize a subnormal */
148 #define SFLOAT_SUBNORMALIZE(SA, Z, SZ) \
149 (void)(*(SZ) = (SA) << SFLOAT_CLZ((SA), 8), *(SZ) = 1 - SFLOAT_CLZ((SA), 8))
151 * Pack sign, exponent and significand and produce a float.
153 * Integer portions of the significand are added to the exponent. The
154 * exponent input should be one less than the result exponent whenever
155 * the significand is normalized since normalized significand will
156 * always have an integer portion of value one.
158 #define SFLOAT_PACK(SIGN, EXP, SIG) \
159 (sfloat_t)((((uint32_t)(SIGN)) << 31) + (((uint32_t)(EXP)) << 23) + (SIG))
161 /* Calculate NaN. If either operands are signaling then raise invalid */
162 static sfloat_t sfloat_propagate_nan(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
163 bool isnan_a = SFLOAT_ISNAN(a);
164 bool issnan_a = SFLOAT_ISSNAN(a);
165 bool isnan_b = SFLOAT_ISNAN(b);
166 bool issnan_b = SFLOAT_ISSNAN(b);
171 if (issnan_a | issnan_b)
172 SFLOAT_RAISE(state, SFLOAT_INEXACT);
176 return isnan_b ? b : a;
177 } else if (isnan_a) {
178 if (issnan_b | !isnan_b)
181 if ((uint32_t)(a << 1) < (uint32_t)(b << 1)) return b;
182 if ((uint32_t)(b << 1) < (uint32_t)(a << 1)) return a;
183 return (a < b) ? a : b;
189 static sfloat_t SFLOAT_PACK_round(sfloat_state_t *state, bool sign_z, int16_t exp_z, uint32_t sig_z) {
190 sfloat_roundingmode_t mode = state->roundingmode;
191 bool even = !!(mode == SFLOAT_ROUND_NEAREST_EVEN);
192 unsigned char increment = 0x40;
193 unsigned char bits = sig_z & 0x7F;
196 if (mode == SFLOAT_ROUND_TO_ZERO)
201 if (mode == SFLOAT_ROUND_UP)
204 if (mode == SFLOAT_ROUND_DOWN)
210 if (0xFD <= (uint16_t)exp_z) {
211 if ((0xFD < exp_z) || ((exp_z == 0xFD) && ((int32_t)(sig_z + increment) < 0))) {
212 SFLOAT_RAISE(state, SFLOAT_OVERFLOW | SFLOAT_INEXACT);
213 return SFLOAT_PACK(sign_z, 0xFF, 0) - (increment == 0);
216 /* Check for underflow */
217 bool tiny = (state->tiny == SFLOAT_TBEFORE) || (exp_z < -1) || (sig_z + increment < 0x80000000);
218 SFLOAT_SHIFT(32, sig_z, -exp_z, &sig_z);
222 SFLOAT_RAISE(state, SFLOAT_UNDERFLOW);
227 * Significand has point between bits 30 and 29, 7 bits to the left of
228 * the usual place. This shifted significand has to be normalized
229 * or smaller, if it isn't the exponent must be zero, in which case
230 * no rounding occurs since the result will be a subnormal.
233 SFLOAT_RAISE(state, SFLOAT_INEXACT);
234 sig_z = (sig_z + increment) >> 7;
235 sig_z &= ~(((bits ^ 0x40) == 0) & even);
238 return SFLOAT_PACK(sign_z, exp_z, sig_z);
241 /* Normalized round and pack */
242 static sfloat_t SFLOAT_PACK_normal(sfloat_state_t *state, bool sign_z, int16_t exp_z, uint32_t sig_z) {
243 unsigned char c = SFLOAT_CLZ(sig_z, 1);
244 return SFLOAT_PACK_round(state, sign_z, exp_z - c, sig_z << c);
247 static sfloat_t sfloat_add_impl(sfloat_state_t *state, sfloat_t a, sfloat_t b, bool sign_z) {
248 int16_t exp_a = SFLOAT_EXTRACT_EXP(a);
249 int16_t exp_b = SFLOAT_EXTRACT_EXP(b);
251 int16_t exp_d = exp_a - exp_b;
252 uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a) << 6;
253 uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b) << 6;
258 return sig_a ? sfloat_propagate_nan(state, a, b) : a;
263 SFLOAT_SHIFT(32, sig_b, exp_d, &sig_b);
265 } else if (exp_d < 0) {
267 return sig_b ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z, 0xFF, 0);
272 SFLOAT_SHIFT(32, sig_a, -exp_d, &sig_a);
276 return (sig_a | sig_b) ? sfloat_propagate_nan(state, a, b) : a;
278 return SFLOAT_PACK(sign_z, 0, (sig_a + sig_b) >> 6);
279 sig_z = 0x40000000 + sig_a + sig_b;
284 sig_z = (sig_a + sig_b) << 1;
286 if ((int32_t)sig_z < 0) {
287 sig_z = sig_a + sig_b;
291 return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
294 static sfloat_t sfloat_sub_impl(sfloat_state_t *state, sfloat_t a, sfloat_t b, bool sign_z) {
295 int16_t exp_a = SFLOAT_EXTRACT_EXP(a);
296 int16_t exp_b = SFLOAT_EXTRACT_EXP(b);
298 int16_t exp_d = exp_a - exp_b;
299 uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a) << 7;
300 uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b) << 7;
303 if (0 < exp_d) goto exp_greater_a;
304 if (exp_d < 0) goto exp_greater_b;
308 return sfloat_propagate_nan(state, a, b);
309 SFLOAT_RAISE(state, SFLOAT_INVALID);
316 if (sig_b < sig_a) goto greater_a;
317 if (sig_a < sig_b) goto greater_b;
319 return SFLOAT_PACK(state->roundingmode == SFLOAT_ROUND_DOWN, 0, 0);
323 return (sig_b) ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z ^ 1, 0xFF, 0);
328 SFLOAT_SHIFT(32, sig_a, -exp_d, &sig_a);
331 sig_z = sig_b - sig_a;
338 return (sig_a) ? sfloat_propagate_nan(state, a, b) : a;
343 SFLOAT_SHIFT(32, sig_b, exp_d, &sig_b);
346 sig_z = sig_a - sig_b;
351 return SFLOAT_PACK_normal(state, sign_z, exp_z, sig_z);
354 static GMQCC_INLINE sfloat_t sfloat_add(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
355 bool sign_a = SFLOAT_EXTRACT_SIGN(a);
356 bool sign_b = SFLOAT_EXTRACT_SIGN(b);
357 return (sign_a == sign_b) ? sfloat_add_impl(state, a, b, sign_a)
358 : sfloat_sub_impl(state, a, b, sign_a);
361 static GMQCC_INLINE sfloat_t sfloat_sub(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
362 bool sign_a = SFLOAT_EXTRACT_SIGN(a);
363 bool sign_b = SFLOAT_EXTRACT_SIGN(b);
364 return (sign_a == sign_b) ? sfloat_sub_impl(state, a, b, sign_a)
365 : sfloat_add_impl(state, a, b, sign_a);
368 static sfloat_t sfloat_mul(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
369 int16_t exp_a = SFLOAT_EXTRACT_EXP(a);
370 int16_t exp_b = SFLOAT_EXTRACT_EXP(b);
372 uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a);
373 uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b);
375 uint64_t sig_z64 = 0;
376 bool sign_a = SFLOAT_EXTRACT_SIGN(a);
377 bool sign_b = SFLOAT_EXTRACT_SIGN(b);
378 bool sign_z = sign_a ^ sign_b;
381 if (sig_a || ((exp_b == 0xFF) && sig_b))
382 return sfloat_propagate_nan(state, a, b);
383 if ((exp_b | sig_b) == 0) {
384 SFLOAT_RAISE(state, SFLOAT_INVALID);
387 return SFLOAT_PACK(sign_z, 0xFF, 0);
391 return sfloat_propagate_nan(state, a, b);
392 if ((exp_a | sig_a) == 0) {
393 SFLOAT_RAISE(state, SFLOAT_INVALID);
396 return SFLOAT_PACK(sign_z, 0xFF, 0);
400 return SFLOAT_PACK(sign_z, 0, 0);
401 SFLOAT_SUBNORMALIZE(sig_a, &exp_a, &sig_a);
405 return SFLOAT_PACK(sign_z, 0, 0);
406 SFLOAT_SUBNORMALIZE(sig_b, &exp_b, &sig_b);
408 exp_z = exp_a + exp_b - 0x7F;
409 sig_a = (sig_a | 0x00800000) << 7;
410 sig_b = (sig_b | 0x00800000) << 8;
411 SFLOAT_SHIFT(64, ((uint64_t)sig_a) * sig_b, 32, &sig_z64);
413 if (0 <= (int32_t)(sig_z << 1)) {
417 return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
420 static sfloat_t sfloat_div(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
421 int16_t exp_a = SFLOAT_EXTRACT_EXP(a);
422 int16_t exp_b = SFLOAT_EXTRACT_EXP(b);
424 uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a);
425 uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b);
427 bool sign_a = SFLOAT_EXTRACT_SIGN(a);
428 bool sign_b = SFLOAT_EXTRACT_SIGN(b);
429 bool sign_z = sign_a ^ sign_b;
433 return sfloat_propagate_nan(state, a, b);
436 return sfloat_propagate_nan(state, a, b);
437 SFLOAT_RAISE(state, SFLOAT_INVALID);
440 return SFLOAT_PACK(sign_z, 0xFF, 0);
443 return (sig_b) ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z, 0, 0);
446 if ((exp_a | sig_a) == 0) {
447 SFLOAT_RAISE(state, SFLOAT_INVALID);
450 SFLOAT_RAISE(state, SFLOAT_DIVBYZERO);
451 return SFLOAT_PACK(sign_z, 0xFF, 0);
453 SFLOAT_SUBNORMALIZE(sig_b, &exp_b, &sig_b);
457 return SFLOAT_PACK(sign_z, 0, 0);
458 SFLOAT_SUBNORMALIZE(sig_a, &exp_a, &sig_a);
460 exp_z = exp_a - exp_b + 0x7D;
461 sig_a = (sig_a | 0x00800000) << 7;
462 sig_b = (sig_b | 0x00800000) << 8;
463 if (sig_b <= (sig_a + sig_a)) {
467 sig_z = (((uint64_t)sig_a) << 32) / sig_b;
468 if ((sig_z & 0x3F) == 0)
469 sig_z |= ((uint64_t)sig_b * sig_z != ((uint64_t)sig_a) << 32);
470 return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
473 static sfloat_t sfloat_neg(sfloat_state_t *state, sfloat_t a) {
476 return sfloat_mul(state, a, neg.s);
479 static GMQCC_INLINE void sfloat_check(lex_ctx_t ctx, sfloat_state_t *state, const char *vec) {
480 /* Exception comes from vector component */
482 if (state->exceptionflags & SFLOAT_DIVBYZERO)
483 compile_error(ctx, "division by zero in `%s' component", vec);
484 if (state->exceptionflags & SFLOAT_INVALID)
485 compile_error(ctx, "undefined (inf) in `%s' component", vec);
486 if (state->exceptionflags & SFLOAT_OVERFLOW)
487 compile_error(ctx, "arithmetic overflow in `%s' component", vec);
488 if (state->exceptionflags & SFLOAT_UNDERFLOW)
489 compile_error(ctx, "arithmetic underflow in `%s' component", vec);
492 if (state->exceptionflags & SFLOAT_DIVBYZERO)
493 compile_error(ctx, "division by zero");
494 if (state->exceptionflags & SFLOAT_INVALID)
495 compile_error(ctx, "undefined (inf)");
496 if (state->exceptionflags & SFLOAT_OVERFLOW)
497 compile_error(ctx, "arithmetic overflow");
498 if (state->exceptionflags & SFLOAT_UNDERFLOW)
499 compile_error(ctx, "arithmetic underflow");
502 static GMQCC_INLINE void sfloat_init(sfloat_state_t *state) {
503 state->exceptionflags = SFLOAT_NOEXCEPT;
504 state->roundingmode = FOLD_ROUNDING;
505 state->tiny = FOLD_TINYNESS;
509 * There is two stages to constant folding in GMQCC: there is the parse
510 * stage constant folding, where, witht he help of the AST, operator
511 * usages can be constant folded. Then there is the constant folding
512 * in the IR for things like eliding if statements, can occur.
514 * This file is thus, split into two parts.
517 #define isfloat(X) (((ast_expression*)(X))->vtype == TYPE_FLOAT)
518 #define isvector(X) (((ast_expression*)(X))->vtype == TYPE_VECTOR)
519 #define isstring(X) (((ast_expression*)(X))->vtype == TYPE_STRING)
520 #define isarray(X) (((ast_expression*)(X))->vtype == TYPE_ARRAY)
521 #define isfloats(X,Y) (isfloat (X) && isfloat (Y))
524 * Implementation of basic vector math for vec3_t, for trivial constant
527 * TODO: gcc/clang hinting for autovectorization
543 sfloat_state_t state[3];
546 static GMQCC_INLINE vec3_soft_t vec3_soft_convert(vec3_t vec) {
554 static GMQCC_INLINE bool vec3_soft_exception(vec3_soft_state_t *vstate, size_t index) {
555 sfloat_exceptionflags_t flags = vstate->state[index].exceptionflags;
556 if (flags & SFLOAT_DIVBYZERO) return true;
557 if (flags & SFLOAT_INVALID) return true;
558 if (flags & SFLOAT_OVERFLOW) return true;
559 if (flags & SFLOAT_UNDERFLOW) return true;
563 static GMQCC_INLINE void vec3_soft_eval(vec3_soft_state_t *state,
564 sfloat_t (*callback)(sfloat_state_t *, sfloat_t, sfloat_t),
568 vec3_soft_t sa = vec3_soft_convert(a);
569 vec3_soft_t sb = vec3_soft_convert(b);
570 callback(&state->state[0], sa.x.s, sb.x.s);
571 if (vec3_soft_exception(state, 0)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_X);
572 callback(&state->state[1], sa.y.s, sb.y.s);
573 if (vec3_soft_exception(state, 1)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_Y);
574 callback(&state->state[2], sa.z.s, sb.z.s);
575 if (vec3_soft_exception(state, 2)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_Z);
578 static GMQCC_INLINE void vec3_check_except(vec3_t a,
581 sfloat_t (*callback)(sfloat_state_t *, sfloat_t, sfloat_t))
583 vec3_soft_state_t state;
585 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
588 sfloat_init(&state.state[0]);
589 sfloat_init(&state.state[1]);
590 sfloat_init(&state.state[2]);
592 vec3_soft_eval(&state, callback, a, b);
593 if (state.faults & VEC_COMP_X) sfloat_check(ctx, &state.state[0], "x");
594 if (state.faults & VEC_COMP_Y) sfloat_check(ctx, &state.state[1], "y");
595 if (state.faults & VEC_COMP_Z) sfloat_check(ctx, &state.state[2], "z");
598 static GMQCC_INLINE vec3_t vec3_add(lex_ctx_t ctx, vec3_t a, vec3_t b) {
600 vec3_check_except(a, b, ctx, &sfloat_add);
607 static GMQCC_INLINE vec3_t vec3_sub(lex_ctx_t ctx, vec3_t a, vec3_t b) {
609 vec3_check_except(a, b, ctx, &sfloat_sub);
616 static GMQCC_INLINE vec3_t vec3_neg(lex_ctx_t ctx, vec3_t a) {
621 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
632 sfloat_neg(&s[0], v[0].s);
633 sfloat_neg(&s[1], v[1].s);
634 sfloat_neg(&s[2], v[2].s);
636 sfloat_check(ctx, &s[0], NULL);
637 sfloat_check(ctx, &s[1], NULL);
638 sfloat_check(ctx, &s[2], NULL);
647 static GMQCC_INLINE vec3_t vec3_or(vec3_t a, vec3_t b) {
649 out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b.x));
650 out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b.y));
651 out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b.z));
655 static GMQCC_INLINE vec3_t vec3_orvf(vec3_t a, qcfloat_t b) {
657 out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b));
658 out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b));
659 out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b));
663 static GMQCC_INLINE vec3_t vec3_and(vec3_t a, vec3_t b) {
665 out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b.x));
666 out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b.y));
667 out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b.z));
671 static GMQCC_INLINE vec3_t vec3_andvf(vec3_t a, qcfloat_t b) {
673 out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b));
674 out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b));
675 out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b));
679 static GMQCC_INLINE vec3_t vec3_xor(vec3_t a, vec3_t b) {
681 out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b.x));
682 out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b.y));
683 out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b.z));
687 static GMQCC_INLINE vec3_t vec3_xorvf(vec3_t a, qcfloat_t b) {
689 out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b));
690 out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b));
691 out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b));
695 static GMQCC_INLINE vec3_t vec3_not(vec3_t a) {
703 static GMQCC_INLINE qcfloat_t vec3_mulvv(lex_ctx_t ctx, vec3_t a, vec3_t b) {
709 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
712 sa = vec3_soft_convert(a);
713 sb = vec3_soft_convert(b);
721 r[0] = sfloat_mul(&s[0], sa.x.s, sb.x.s);
722 r[1] = sfloat_mul(&s[1], sa.y.s, sb.y.s);
723 r[2] = sfloat_mul(&s[2], sa.z.s, sb.z.s);
724 r[3] = sfloat_add(&s[3], r[0], r[1]);
725 r[4] = sfloat_add(&s[4], r[3], r[2]);
727 sfloat_check(ctx, &s[0], NULL);
728 sfloat_check(ctx, &s[1], NULL);
729 sfloat_check(ctx, &s[2], NULL);
730 sfloat_check(ctx, &s[3], NULL);
731 sfloat_check(ctx, &s[4], NULL);
734 return (a.x * b.x + a.y * b.y + a.z * b.z);
737 static GMQCC_INLINE vec3_t vec3_mulvf(lex_ctx_t ctx, vec3_t a, qcfloat_t b) {
743 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
746 sa = vec3_soft_convert(a);
752 sfloat_mul(&s[0], sa.x.s, sb.s);
753 sfloat_mul(&s[1], sa.y.s, sb.s);
754 sfloat_mul(&s[2], sa.z.s, sb.s);
756 sfloat_check(ctx, &s[0], "x");
757 sfloat_check(ctx, &s[1], "y");
758 sfloat_check(ctx, &s[2], "z");
767 static GMQCC_INLINE bool vec3_cmp(vec3_t a, vec3_t b) {
773 static GMQCC_INLINE vec3_t vec3_create(float x, float y, float z) {
781 static GMQCC_INLINE qcfloat_t vec3_notf(vec3_t a) {
782 return (!a.x && !a.y && !a.z);
785 static GMQCC_INLINE bool vec3_pbool(vec3_t a) {
786 return (a.x || a.y || a.z);
789 static GMQCC_INLINE vec3_t vec3_cross(lex_ctx_t ctx, vec3_t a, vec3_t b) {
796 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
799 sa = vec3_soft_convert(a);
800 sb = vec3_soft_convert(b);
812 r[0] = sfloat_mul(&s[0], sa.y.s, sb.z.s);
813 r[1] = sfloat_mul(&s[1], sa.z.s, sb.y.s);
814 r[2] = sfloat_mul(&s[2], sa.z.s, sb.x.s);
815 r[3] = sfloat_mul(&s[3], sa.x.s, sb.z.s);
816 r[4] = sfloat_mul(&s[4], sa.x.s, sb.y.s);
817 r[5] = sfloat_mul(&s[5], sa.y.s, sb.x.s);
818 r[6] = sfloat_sub(&s[6], r[0], r[1]);
819 r[7] = sfloat_sub(&s[7], r[2], r[3]);
820 r[8] = sfloat_sub(&s[8], r[4], r[5]);
822 sfloat_check(ctx, &s[0], NULL);
823 sfloat_check(ctx, &s[1], NULL);
824 sfloat_check(ctx, &s[2], NULL);
825 sfloat_check(ctx, &s[3], NULL);
826 sfloat_check(ctx, &s[4], NULL);
827 sfloat_check(ctx, &s[5], NULL);
828 sfloat_check(ctx, &s[6], "x");
829 sfloat_check(ctx, &s[7], "y");
830 sfloat_check(ctx, &s[8], "z");
833 out.x = a.y * b.z - a.z * b.y;
834 out.y = a.z * b.x - a.x * b.z;
835 out.z = a.x * b.y - a.y * b.x;
839 static lex_ctx_t fold_ctx(fold_t *fold) {
841 if (fold->parser->lex)
842 return parser_ctx(fold->parser);
844 memset(&ctx, 0, sizeof(ctx));
848 static GMQCC_INLINE bool fold_immediate_true(fold_t *fold, ast_value *v) {
849 switch (v->expression.vtype) {
851 return !!v->constval.vfloat;
853 return !!v->constval.vint;
855 if (OPTS_FLAG(CORRECT_LOGIC))
856 return vec3_pbool(v->constval.vvec);
857 return !!(v->constval.vvec.x);
859 if (!v->constval.vstring)
861 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
863 return !!v->constval.vstring[0];
865 compile_error(fold_ctx(fold), "internal error: fold_immediate_true on invalid type");
868 return !!v->constval.vfunc;
871 /* Handy macros to determine if an ast_value can be constant folded. */
872 #define fold_can_1(X) \
873 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
874 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
876 #define fold_can_2(X, Y) (fold_can_1(X) && fold_can_1(Y))
878 #define fold_immvalue_float(E) ((E)->constval.vfloat)
879 #define fold_immvalue_vector(E) ((E)->constval.vvec)
880 #define fold_immvalue_string(E) ((E)->constval.vstring)
882 fold_t *fold_init(parser_t *parser) {
883 fold_t *fold = (fold_t*)mem_a(sizeof(fold_t));
884 fold->parser = parser;
885 fold->imm_float = NULL;
886 fold->imm_vector = NULL;
887 fold->imm_string = NULL;
888 fold->imm_string_untranslate = util_htnew(FOLD_STRING_UNTRANSLATE_HTSIZE);
889 fold->imm_string_dotranslate = util_htnew(FOLD_STRING_DOTRANSLATE_HTSIZE);
892 * prime the tables with common constant values at constant
895 (void)fold_constgen_float (fold, 0.0f, false);
896 (void)fold_constgen_float (fold, 1.0f, false);
897 (void)fold_constgen_float (fold, -1.0f, false);
898 (void)fold_constgen_float (fold, 2.0f, false);
900 (void)fold_constgen_vector(fold, vec3_create(0.0f, 0.0f, 0.0f));
901 (void)fold_constgen_vector(fold, vec3_create(-1.0f, -1.0f, -1.0f));
906 bool fold_generate(fold_t *fold, ir_builder *ir) {
907 /* generate globals for immediate folded values */
911 for (i = 0; i < vec_size(fold->imm_float); ++i)
912 if (!ast_global_codegen ((cur = fold->imm_float[i]), ir, false)) goto err;
913 for (i = 0; i < vec_size(fold->imm_vector); ++i)
914 if (!ast_global_codegen((cur = fold->imm_vector[i]), ir, false)) goto err;
915 for (i = 0; i < vec_size(fold->imm_string); ++i)
916 if (!ast_global_codegen((cur = fold->imm_string[i]), ir, false)) goto err;
921 con_out("failed to generate global %s\n", cur->name);
922 ir_builder_delete(ir);
926 void fold_cleanup(fold_t *fold) {
929 for (i = 0; i < vec_size(fold->imm_float); ++i) ast_delete(fold->imm_float[i]);
930 for (i = 0; i < vec_size(fold->imm_vector); ++i) ast_delete(fold->imm_vector[i]);
931 for (i = 0; i < vec_size(fold->imm_string); ++i) ast_delete(fold->imm_string[i]);
933 vec_free(fold->imm_float);
934 vec_free(fold->imm_vector);
935 vec_free(fold->imm_string);
937 util_htdel(fold->imm_string_untranslate);
938 util_htdel(fold->imm_string_dotranslate);
943 ast_expression *fold_constgen_float(fold_t *fold, qcfloat_t value, bool inexact) {
944 ast_value *out = NULL;
947 for (i = 0; i < vec_size(fold->imm_float); i++) {
948 if (!memcmp(&fold->imm_float[i]->constval.vfloat, &value, sizeof(qcfloat_t)))
949 return (ast_expression*)fold->imm_float[i];
952 out = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_FLOAT);
954 out->hasvalue = true;
955 out->inexact = inexact;
956 out->constval.vfloat = value;
958 vec_push(fold->imm_float, out);
960 return (ast_expression*)out;
963 ast_expression *fold_constgen_vector(fold_t *fold, vec3_t value) {
967 for (i = 0; i < vec_size(fold->imm_vector); i++) {
968 if (vec3_cmp(fold->imm_vector[i]->constval.vvec, value))
969 return (ast_expression*)fold->imm_vector[i];
972 out = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_VECTOR);
974 out->hasvalue = true;
975 out->constval.vvec = value;
977 vec_push(fold->imm_vector, out);
979 return (ast_expression*)out;
982 ast_expression *fold_constgen_string(fold_t *fold, const char *str, bool translate) {
983 hash_table_t *table = (translate) ? fold->imm_string_untranslate : fold->imm_string_dotranslate;
984 ast_value *out = NULL;
985 size_t hash = util_hthash(table, str);
987 if ((out = (ast_value*)util_htgeth(table, str, hash)))
988 return (ast_expression*)out;
992 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(fold->parser->translated++));
993 out = ast_value_new(parser_ctx(fold->parser), name, TYPE_STRING);
994 out->expression.flags |= AST_FLAG_INCLUDE_DEF; /* def needs to be included for translatables */
996 out = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_STRING);
999 out->hasvalue = true;
1001 out->constval.vstring = parser_strdup(str);
1003 vec_push(fold->imm_string, out);
1004 util_htseth(table, str, hash, out);
1006 return (ast_expression*)out;
1010 void (*callback)(void);
1011 sfloat_t (*binary)(sfloat_state_t *, sfloat_t, sfloat_t);
1012 sfloat_t (*unary)(sfloat_state_t *, sfloat_t);
1013 } float_check_callback_t;
1015 static bool fold_check_except_float_impl(void (*callback)(void),
1020 float_check_callback_t call;
1024 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS) && !OPTS_WARN(WARN_INEXACT_COMPARES))
1027 call.callback = callback;
1029 ca.f = fold_immvalue_float(a);
1032 cb.f = fold_immvalue_float(b);
1033 call.binary(&s, ca.s, cb.s);
1035 call.unary(&s, ca.s);
1038 if (s.exceptionflags == 0)
1041 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
1042 goto inexact_possible;
1044 sfloat_check(fold_ctx(fold), &s, NULL);
1047 return s.exceptionflags & SFLOAT_INEXACT;
1050 #define fold_check_except_float(CALLBACK, FOLD, A, B) \
1051 fold_check_except_float_impl(((void (*)(void))(CALLBACK)), (FOLD), (A), (B))
1053 static bool fold_check_inexact_float(fold_t *fold, ast_value *a, ast_value *b) {
1054 lex_ctx_t ctx = fold_ctx(fold);
1055 if (!OPTS_WARN(WARN_INEXACT_COMPARES))
1057 if (!a->inexact && !b->inexact)
1059 return compile_warning(ctx, WARN_INEXACT_COMPARES, "inexact value in comparison");
1062 static GMQCC_INLINE ast_expression *fold_op_mul_vec(fold_t *fold, vec3_t vec, ast_value *sel, const char *set) {
1064 * vector-component constant folding works by matching the component sets
1065 * to eliminate expensive operations on whole-vectors (3 components at runtime).
1066 * to achive this effect in a clean manner this function generalizes the
1067 * values through the use of a set paramater, which is used as an indexing method
1068 * for creating the elided ast binary expression.
1070 * Consider 'n 0 0' where y, and z need to be tested for 0, and x is
1071 * used as the value in a binary operation generating an INSTR_MUL instruction,
1072 * to acomplish the indexing of the correct component value we use set[0], set[1], set[2]
1073 * as x, y, z, where the values of those operations return 'x', 'y', 'z'. Because
1074 * of how ASCII works we can easily deliniate:
1075 * vec.z is the same as set[2]-'x' for when set[2] is 'z', 'z'-'x' results in a
1076 * literal value of 2, using this 2, we know that taking the address of vec->x (float)
1077 * and indxing it with this literal will yeild the immediate address of that component
1079 * Of course more work needs to be done to generate the correct index for the ast_member_new
1080 * call, which is no problem: set[0]-'x' suffices that job.
1082 qcfloat_t x = (&vec.x)[set[0]-'x'];
1083 qcfloat_t y = (&vec.x)[set[1]-'x'];
1084 qcfloat_t z = (&vec.x)[set[2]-'x'];
1087 ast_expression *out;
1088 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
1089 out = (ast_expression*)ast_member_new(fold_ctx(fold), (ast_expression*)sel, set[0]-'x', NULL);
1090 out->node.keep = false;
1091 ((ast_member*)out)->rvalue = true;
1093 return (ast_expression*)ast_binary_new(fold_ctx(fold), INSTR_MUL_F, fold_constgen_float(fold, x, false), out);
1099 static GMQCC_INLINE ast_expression *fold_op_neg(fold_t *fold, ast_value *a) {
1101 if (fold_can_1(a)) {
1102 /* Negation can produce inexact as well */
1103 bool inexact = fold_check_except_float(&sfloat_neg, fold, a, NULL);
1104 return fold_constgen_float(fold, -fold_immvalue_float(a), inexact);
1106 } else if (isvector(a)) {
1108 return fold_constgen_vector(fold, vec3_neg(fold_ctx(fold), fold_immvalue_vector(a)));
1113 static GMQCC_INLINE ast_expression *fold_op_not(fold_t *fold, ast_value *a) {
1116 return fold_constgen_float(fold, !fold_immvalue_float(a), false);
1117 } else if (isvector(a)) {
1119 return fold_constgen_float(fold, vec3_notf(fold_immvalue_vector(a)), false);
1120 } else if (isstring(a)) {
1121 if (fold_can_1(a)) {
1122 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
1123 return fold_constgen_float(fold, !fold_immvalue_string(a), false);
1125 return fold_constgen_float(fold, !fold_immvalue_string(a) || !*fold_immvalue_string(a), false);
1131 static GMQCC_INLINE ast_expression *fold_op_add(fold_t *fold, ast_value *a, ast_value *b) {
1133 if (fold_can_2(a, b)) {
1134 bool inexact = fold_check_except_float(&sfloat_add, fold, a, b);
1135 return fold_constgen_float(fold, fold_immvalue_float(a) + fold_immvalue_float(b), inexact);
1137 } else if (isvector(a)) {
1138 if (fold_can_2(a, b))
1139 return fold_constgen_vector(fold, vec3_add(fold_ctx(fold),
1140 fold_immvalue_vector(a),
1141 fold_immvalue_vector(b)));
1146 static GMQCC_INLINE ast_expression *fold_op_sub(fold_t *fold, ast_value *a, ast_value *b) {
1148 if (fold_can_2(a, b)) {
1149 bool inexact = fold_check_except_float(&sfloat_sub, fold, a, b);
1150 return fold_constgen_float(fold, fold_immvalue_float(a) - fold_immvalue_float(b), inexact);
1152 } else if (isvector(a)) {
1153 if (fold_can_2(a, b))
1154 return fold_constgen_vector(fold, vec3_sub(fold_ctx(fold),
1155 fold_immvalue_vector(a),
1156 fold_immvalue_vector(b)));
1161 static GMQCC_INLINE ast_expression *fold_op_mul(fold_t *fold, ast_value *a, ast_value *b) {
1164 if (fold_can_2(a, b))
1165 return fold_constgen_vector(fold, vec3_mulvf(fold_ctx(fold), fold_immvalue_vector(b), fold_immvalue_float(a)));
1167 if (fold_can_2(a, b)) {
1168 bool inexact = fold_check_except_float(&sfloat_mul, fold, a, b);
1169 return fold_constgen_float(fold, fold_immvalue_float(a) * fold_immvalue_float(b), inexact);
1172 } else if (isvector(a)) {
1174 if (fold_can_2(a, b))
1175 return fold_constgen_vector(fold, vec3_mulvf(fold_ctx(fold), fold_immvalue_vector(a), fold_immvalue_float(b)));
1177 if (fold_can_2(a, b)) {
1178 return fold_constgen_float(fold, vec3_mulvv(fold_ctx(fold), fold_immvalue_vector(a), fold_immvalue_vector(b)), false);
1179 } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(a)) {
1180 ast_expression *out;
1181 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "xyz"))) return out;
1182 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "yxz"))) return out;
1183 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "zxy"))) return out;
1184 } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(b)) {
1185 ast_expression *out;
1186 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "xyz"))) return out;
1187 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "yxz"))) return out;
1188 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "zxy"))) return out;
1195 static GMQCC_INLINE ast_expression *fold_op_div(fold_t *fold, ast_value *a, ast_value *b) {
1197 if (fold_can_2(a, b)) {
1198 bool inexact = fold_check_except_float(&sfloat_div, fold, a, b);
1199 return fold_constgen_float(fold, fold_immvalue_float(a) / fold_immvalue_float(b), inexact);
1200 } else if (fold_can_1(b)) {
1201 return (ast_expression*)ast_binary_new(
1205 fold_constgen_float(fold, 1.0f / fold_immvalue_float(b), false)
1208 } else if (isvector(a)) {
1209 if (fold_can_2(a, b)) {
1210 return fold_constgen_vector(fold, vec3_mulvf(fold_ctx(fold), fold_immvalue_vector(a), 1.0f / fold_immvalue_float(b)));
1212 return (ast_expression*)ast_binary_new(
1217 ? (ast_expression*)fold_constgen_float(fold, 1.0f / fold_immvalue_float(b), false)
1218 : (ast_expression*)ast_binary_new(
1221 (ast_expression*)fold->imm_float[1],
1230 static GMQCC_INLINE ast_expression *fold_op_mod(fold_t *fold, ast_value *a, ast_value *b) {
1231 return (fold_can_2(a, b))
1232 ? fold_constgen_float(fold, fmod(fold_immvalue_float(a), fold_immvalue_float(b)), false)
1236 static GMQCC_INLINE ast_expression *fold_op_bor(fold_t *fold, ast_value *a, ast_value *b) {
1238 if (fold_can_2(a, b))
1239 return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) | ((qcint_t)fold_immvalue_float(b))), false);
1242 if (fold_can_2(a, b))
1243 return fold_constgen_vector(fold, vec3_or(fold_immvalue_vector(a), fold_immvalue_vector(b)));
1245 if (fold_can_2(a, b))
1246 return fold_constgen_vector(fold, vec3_orvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
1252 static GMQCC_INLINE ast_expression *fold_op_band(fold_t *fold, ast_value *a, ast_value *b) {
1254 if (fold_can_2(a, b))
1255 return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) & ((qcint_t)fold_immvalue_float(b))), false);
1258 if (fold_can_2(a, b))
1259 return fold_constgen_vector(fold, vec3_and(fold_immvalue_vector(a), fold_immvalue_vector(b)));
1261 if (fold_can_2(a, b))
1262 return fold_constgen_vector(fold, vec3_andvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
1268 static GMQCC_INLINE ast_expression *fold_op_xor(fold_t *fold, ast_value *a, ast_value *b) {
1270 if (fold_can_2(a, b))
1271 return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) ^ ((qcint_t)fold_immvalue_float(b))), false);
1273 if (fold_can_2(a, b)) {
1275 return fold_constgen_vector(fold, vec3_xor(fold_immvalue_vector(a), fold_immvalue_vector(b)));
1277 return fold_constgen_vector(fold, vec3_xorvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
1283 static GMQCC_INLINE ast_expression *fold_op_lshift(fold_t *fold, ast_value *a, ast_value *b) {
1284 if (fold_can_2(a, b) && isfloats(a, b))
1285 return fold_constgen_float(fold, (qcfloat_t)floorf(fold_immvalue_float(a) * powf(2.0f, fold_immvalue_float(b))), false);
1289 static GMQCC_INLINE ast_expression *fold_op_rshift(fold_t *fold, ast_value *a, ast_value *b) {
1290 if (fold_can_2(a, b) && isfloats(a, b))
1291 return fold_constgen_float(fold, (qcfloat_t)floorf(fold_immvalue_float(a) / powf(2.0f, fold_immvalue_float(b))), false);
1295 static GMQCC_INLINE ast_expression *fold_op_andor(fold_t *fold, ast_value *a, ast_value *b, float expr) {
1296 if (fold_can_2(a, b)) {
1297 if (OPTS_FLAG(PERL_LOGIC)) {
1299 return (fold_immediate_true(fold, a)) ? (ast_expression*)a : (ast_expression*)b;
1301 return (fold_immediate_true(fold, a)) ? (ast_expression*)b : (ast_expression*)a;
1303 return fold_constgen_float (
1305 ((expr) ? (fold_immediate_true(fold, a) || fold_immediate_true(fold, b))
1306 : (fold_immediate_true(fold, a) && fold_immediate_true(fold, b)))
1316 static GMQCC_INLINE ast_expression *fold_op_tern(fold_t *fold, ast_value *a, ast_value *b, ast_value *c) {
1317 if (fold_can_1(a)) {
1318 return fold_immediate_true(fold, a)
1319 ? (ast_expression*)b
1320 : (ast_expression*)c;
1325 static GMQCC_INLINE ast_expression *fold_op_exp(fold_t *fold, ast_value *a, ast_value *b) {
1326 if (fold_can_2(a, b))
1327 return fold_constgen_float(fold, (qcfloat_t)powf(fold_immvalue_float(a), fold_immvalue_float(b)), false);
1331 static GMQCC_INLINE ast_expression *fold_op_lteqgt(fold_t *fold, ast_value *a, ast_value *b) {
1332 if (fold_can_2(a,b)) {
1333 fold_check_inexact_float(fold, a, b);
1334 if (fold_immvalue_float(a) < fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[2];
1335 if (fold_immvalue_float(a) == fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[0];
1336 if (fold_immvalue_float(a) > fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[1];
1341 static GMQCC_INLINE ast_expression *fold_op_ltgt(fold_t *fold, ast_value *a, ast_value *b, bool lt) {
1342 if (fold_can_2(a, b)) {
1343 fold_check_inexact_float(fold, a, b);
1344 return (lt) ? (ast_expression*)fold->imm_float[!!(fold_immvalue_float(a) < fold_immvalue_float(b))]
1345 : (ast_expression*)fold->imm_float[!!(fold_immvalue_float(a) > fold_immvalue_float(b))];
1350 static GMQCC_INLINE ast_expression *fold_op_cmp(fold_t *fold, ast_value *a, ast_value *b, bool ne) {
1351 if (fold_can_2(a, b)) {
1352 if (isfloat(a) && isfloat(b)) {
1353 float la = fold_immvalue_float(a);
1354 float lb = fold_immvalue_float(b);
1355 fold_check_inexact_float(fold, a, b);
1356 return (ast_expression*)fold->imm_float[!(ne ? la == lb : la != lb)];
1357 } if (isvector(a) && isvector(b)) {
1358 vec3_t la = fold_immvalue_vector(a);
1359 vec3_t lb = fold_immvalue_vector(b);
1360 return (ast_expression*)fold->imm_float[!(ne ? vec3_cmp(la, lb) : !vec3_cmp(la, lb))];
1366 static GMQCC_INLINE ast_expression *fold_op_bnot(fold_t *fold, ast_value *a) {
1369 return fold_constgen_float(fold, -1-fold_immvalue_float(a), false);
1373 return fold_constgen_vector(fold, vec3_not(fold_immvalue_vector(a)));
1379 static GMQCC_INLINE ast_expression *fold_op_cross(fold_t *fold, ast_value *a, ast_value *b) {
1380 if (fold_can_2(a, b))
1381 return fold_constgen_vector(fold, vec3_cross(fold_ctx(fold),
1382 fold_immvalue_vector(a),
1383 fold_immvalue_vector(b)));
1387 static GMQCC_INLINE ast_expression *fold_op_length(fold_t *fold, ast_value *a) {
1388 if (fold_can_1(a) && isstring(a))
1389 return fold_constgen_float(fold, strlen(fold_immvalue_string(a)), false);
1391 return fold_constgen_float(fold, vec_size(a->initlist), false);
1395 ast_expression *fold_op(fold_t *fold, const oper_info *info, ast_expression **opexprs) {
1396 ast_value *a = (ast_value*)opexprs[0];
1397 ast_value *b = (ast_value*)opexprs[1];
1398 ast_value *c = (ast_value*)opexprs[2];
1399 ast_expression *e = NULL;
1401 /* can a fold operation be applied to this operator usage? */
1405 switch(info->operands) {
1406 case 3: if(!c) return NULL;
1407 case 2: if(!b) return NULL;
1410 compile_error(fold_ctx(fold), "internal error: fold_op no operands to fold\n");
1416 * we could use a boolean and default case but ironically gcc produces
1417 * invalid broken assembly from that operation. clang/tcc get it right,
1418 * but interestingly ignore compiling this to a jump-table when I do that,
1419 * this happens to be the most efficent method, since you have per-level
1420 * granularity on the pointer check happening only for the case you check
1421 * it in. Opposed to the default method which would involve a boolean and
1422 * pointer check after wards.
1424 #define fold_op_case(ARGS, ARGS_OPID, OP, ARGS_FOLD) \
1425 case opid##ARGS ARGS_OPID: \
1426 if ((e = fold_op_##OP ARGS_FOLD)) { \
1427 ++opts_optimizationcount[OPTIM_CONST_FOLD]; \
1432 fold_op_case(2, ('-', 'P'), neg, (fold, a));
1433 fold_op_case(2, ('!', 'P'), not, (fold, a));
1434 fold_op_case(1, ('+'), add, (fold, a, b));
1435 fold_op_case(1, ('-'), sub, (fold, a, b));
1436 fold_op_case(1, ('*'), mul, (fold, a, b));
1437 fold_op_case(1, ('/'), div, (fold, a, b));
1438 fold_op_case(1, ('%'), mod, (fold, a, b));
1439 fold_op_case(1, ('|'), bor, (fold, a, b));
1440 fold_op_case(1, ('&'), band, (fold, a, b));
1441 fold_op_case(1, ('^'), xor, (fold, a, b));
1442 fold_op_case(1, ('<'), ltgt, (fold, a, b, true));
1443 fold_op_case(1, ('>'), ltgt, (fold, a, b, false));
1444 fold_op_case(2, ('<', '<'), lshift, (fold, a, b));
1445 fold_op_case(2, ('>', '>'), rshift, (fold, a, b));
1446 fold_op_case(2, ('|', '|'), andor, (fold, a, b, true));
1447 fold_op_case(2, ('&', '&'), andor, (fold, a, b, false));
1448 fold_op_case(2, ('?', ':'), tern, (fold, a, b, c));
1449 fold_op_case(2, ('*', '*'), exp, (fold, a, b));
1450 fold_op_case(3, ('<','=','>'), lteqgt, (fold, a, b));
1451 fold_op_case(2, ('!', '='), cmp, (fold, a, b, true));
1452 fold_op_case(2, ('=', '='), cmp, (fold, a, b, false));
1453 fold_op_case(2, ('~', 'P'), bnot, (fold, a));
1454 fold_op_case(2, ('>', '<'), cross, (fold, a, b));
1455 fold_op_case(3, ('l', 'e', 'n'), length, (fold, a));
1458 compile_error(fold_ctx(fold), "internal error: attempted to constant-fold for unsupported operator");
1463 * Constant folding for compiler intrinsics, simaler approach to operator
1464 * folding, primarly: individual functions for each intrinsics to fold,
1465 * and a generic selection function.
1467 static GMQCC_INLINE ast_expression *fold_intrin_isfinite(fold_t *fold, ast_value *a) {
1468 return fold_constgen_float(fold, isfinite(fold_immvalue_float(a)), false);
1470 static GMQCC_INLINE ast_expression *fold_intrin_isinf(fold_t *fold, ast_value *a) {
1471 return fold_constgen_float(fold, isinf(fold_immvalue_float(a)), false);
1473 static GMQCC_INLINE ast_expression *fold_intrin_isnan(fold_t *fold, ast_value *a) {
1474 return fold_constgen_float(fold, isnan(fold_immvalue_float(a)), false);
1476 static GMQCC_INLINE ast_expression *fold_intrin_isnormal(fold_t *fold, ast_value *a) {
1477 return fold_constgen_float(fold, isnormal(fold_immvalue_float(a)), false);
1479 static GMQCC_INLINE ast_expression *fold_intrin_signbit(fold_t *fold, ast_value *a) {
1480 return fold_constgen_float(fold, signbit(fold_immvalue_float(a)), false);
1482 static GMQCC_INLINE ast_expression *fold_intirn_acosh(fold_t *fold, ast_value *a) {
1483 return fold_constgen_float(fold, acoshf(fold_immvalue_float(a)), false);
1485 static GMQCC_INLINE ast_expression *fold_intrin_asinh(fold_t *fold, ast_value *a) {
1486 return fold_constgen_float(fold, asinhf(fold_immvalue_float(a)), false);
1488 static GMQCC_INLINE ast_expression *fold_intrin_atanh(fold_t *fold, ast_value *a) {
1489 return fold_constgen_float(fold, (float)atanh(fold_immvalue_float(a)), false);
1491 static GMQCC_INLINE ast_expression *fold_intrin_exp(fold_t *fold, ast_value *a) {
1492 return fold_constgen_float(fold, expf(fold_immvalue_float(a)), false);
1494 static GMQCC_INLINE ast_expression *fold_intrin_exp2(fold_t *fold, ast_value *a) {
1495 return fold_constgen_float(fold, exp2f(fold_immvalue_float(a)), false);
1497 static GMQCC_INLINE ast_expression *fold_intrin_expm1(fold_t *fold, ast_value *a) {
1498 return fold_constgen_float(fold, expm1f(fold_immvalue_float(a)), false);
1500 static GMQCC_INLINE ast_expression *fold_intrin_mod(fold_t *fold, ast_value *lhs, ast_value *rhs) {
1501 return fold_constgen_float(fold, fmodf(fold_immvalue_float(lhs), fold_immvalue_float(rhs)), false);
1503 static GMQCC_INLINE ast_expression *fold_intrin_pow(fold_t *fold, ast_value *lhs, ast_value *rhs) {
1504 return fold_constgen_float(fold, powf(fold_immvalue_float(lhs), fold_immvalue_float(rhs)), false);
1506 static GMQCC_INLINE ast_expression *fold_intrin_fabs(fold_t *fold, ast_value *a) {
1507 return fold_constgen_float(fold, fabsf(fold_immvalue_float(a)), false);
1511 ast_expression *fold_intrin(fold_t *fold, const char *intrin, ast_expression **arg) {
1512 ast_expression *ret = NULL;
1513 ast_value *a = (ast_value*)arg[0];
1514 ast_value *b = (ast_value*)arg[1];
1516 if (!strcmp(intrin, "isfinite")) ret = fold_intrin_isfinite(fold, a);
1517 if (!strcmp(intrin, "isinf")) ret = fold_intrin_isinf(fold, a);
1518 if (!strcmp(intrin, "isnan")) ret = fold_intrin_isnan(fold, a);
1519 if (!strcmp(intrin, "isnormal")) ret = fold_intrin_isnormal(fold, a);
1520 if (!strcmp(intrin, "signbit")) ret = fold_intrin_signbit(fold, a);
1521 if (!strcmp(intrin, "acosh")) ret = fold_intirn_acosh(fold, a);
1522 if (!strcmp(intrin, "asinh")) ret = fold_intrin_asinh(fold, a);
1523 if (!strcmp(intrin, "atanh")) ret = fold_intrin_atanh(fold, a);
1524 if (!strcmp(intrin, "exp")) ret = fold_intrin_exp(fold, a);
1525 if (!strcmp(intrin, "exp2")) ret = fold_intrin_exp2(fold, a);
1526 if (!strcmp(intrin, "expm1")) ret = fold_intrin_expm1(fold, a);
1527 if (!strcmp(intrin, "mod")) ret = fold_intrin_mod(fold, a, b);
1528 if (!strcmp(intrin, "pow")) ret = fold_intrin_pow(fold, a, b);
1529 if (!strcmp(intrin, "fabs")) ret = fold_intrin_fabs(fold, a);
1532 ++opts_optimizationcount[OPTIM_CONST_FOLD];
1538 * These are all the actual constant folding methods that happen in between
1539 * the AST/IR stage of the compiler , i.e eliminating branches for const
1540 * expressions, which is the only supported thing so far. We undefine the
1541 * testing macros here because an ir_value is differant than an ast_value.
1547 #undef fold_immvalue_float
1548 #undef fold_immvalue_string
1549 #undef fold_immvalue_vector
1553 #define isfloat(X) ((X)->vtype == TYPE_FLOAT)
1554 /*#define isstring(X) ((X)->vtype == TYPE_STRING)*/
1555 /*#define isvector(X) ((X)->vtype == TYPE_VECTOR)*/
1556 #define fold_immvalue_float(X) ((X)->constval.vfloat)
1557 #define fold_immvalue_vector(X) ((X)->constval.vvec)
1558 /*#define fold_immvalue_string(X) ((X)->constval.vstring)*/
1559 #define fold_can_1(X) ((X)->hasvalue && (X)->cvq == CV_CONST)
1560 /*#define fold_can_2(X,Y) (fold_can_1(X) && fold_can_1(Y))*/
1562 static ast_expression *fold_superfluous(ast_expression *left, ast_expression *right, int op) {
1563 ast_expression *swapped = NULL; /* using this as bool */
1566 if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right))) {
1572 if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right)))
1580 if (fold_immvalue_float(load) == 1.0f) {
1581 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1592 if (fold_immvalue_float(load) == 0.0f) {
1593 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1600 if (vec3_cmp(fold_immvalue_vector(load), vec3_create(1, 1, 1))) {
1601 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1611 if (vec3_cmp(fold_immvalue_vector(load), vec3_create(0, 0, 0))) {
1612 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1622 ast_expression *fold_binary(lex_ctx_t ctx, int op, ast_expression *left, ast_expression *right) {
1623 ast_expression *ret = fold_superfluous(left, right, op);
1626 return (ast_expression*)ast_binary_new(ctx, op, left, right);
1629 static GMQCC_INLINE int fold_cond(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1630 if (isfloat(condval) && fold_can_1(condval) && OPTS_OPTIMIZATION(OPTIM_CONST_FOLD_DCE)) {
1631 ast_expression_codegen *cgen;
1634 bool istrue = (fold_immvalue_float(condval) != 0.0f && branch->on_true);
1635 bool isfalse = (fold_immvalue_float(condval) == 0.0f && branch->on_false);
1636 ast_expression *path = (istrue) ? branch->on_true :
1637 (isfalse) ? branch->on_false : NULL;
1640 * no path to take implies that the evaluation is if(0) and there
1641 * is no else block. so eliminate all the code.
1643 ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1647 if (!(elide = ir_function_create_block(ast_ctx(branch), func->ir_func, ast_function_label(func, ((istrue) ? "ontrue" : "onfalse")))))
1649 if (!(*(cgen = path->codegen))((ast_expression*)path, func, false, &dummy))
1651 if (!ir_block_create_jump(func->curblock, ast_ctx(branch), elide))
1654 * now the branch has been eliminated and the correct block for the constant evaluation
1655 * is expanded into the current block for the function.
1657 func->curblock = elide;
1658 ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1661 return -1; /* nothing done */
1664 int fold_cond_ternary(ir_value *condval, ast_function *func, ast_ternary *branch) {
1665 return fold_cond(condval, func, (ast_ifthen*)branch);
1668 int fold_cond_ifthen(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1669 return fold_cond(condval, func, branch);