2 * Copyright (C) 2012, 2013, 2014, 2015
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 * Comparing float values is an unsafe operation when the operands to the
38 * comparison are floating point values that are inexact. For instance 1/3 is an
39 * inexact value. The FPU is meant to raise exceptions when these sorts of things
40 * happen, including division by zero, underflows and overflows. The C standard
41 * library provides us with the <fenv.h> header to gain access to the floating-
42 * point environment and lets us set the rounding mode and check for these exceptions.
43 * The problem is the standard C library allows an implementation to leave these
44 * stubbed out and does not require they be implemented. Furthermore, depending
45 * on implementations there is no control over the FPU. This is an IEE 754
46 * conforming implementation in software to compensate.
48 typedef uint32_t sfloat_t;
61 SFLOAT_UNDERFLOW = 16,
63 } sfloat_exceptionflags_t;
67 SFLOAT_ROUND_NEAREST_EVEN,
71 } sfloat_roundingmode_t;
73 /* Underflow tininess-detection mode */
80 sfloat_roundingmode_t roundingmode;
81 sfloat_exceptionflags_t exceptionflags;
82 sfloat_tdetect_t tiny;
85 /* Counts the number of leading zero bits before the most-significand one bit. */
87 /* MSVC has an intrinsic for this */
88 static GMQCC_INLINE uint32_t sfloat_clz(uint32_t x) {
90 _BitScanForward(&r, x);
93 # define SFLOAT_CLZ(X, SUB) \
94 (sfloat_clz((X)) - (SUB))
95 #elif defined(__GNUC__) || defined(__CLANG__)
96 /* Clang and GCC have a builtin for this */
97 # define SFLOAT_CLZ(X, SUB) \
98 (__builtin_clz((X)) - (SUB))
100 /* Native fallback */
101 static GMQCC_INLINE uint32_t sfloat_popcnt(uint32_t x) {
102 x -= ((x >> 1) & 0x55555555);
103 x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
104 x = (((x >> 4) + x) & 0x0F0F0F0F);
107 return x & 0x0000003F;
109 static GMQCC_INLINE uint32_t sfloat_clz(uint32_t x) {
115 return 32 - sfloat_popcnt(x);
117 # define SFLOAT_CLZ(X, SUB) \
118 (sfloat_clz((X) - (SUB)))
121 /* The value of a NaN */
122 #define SFLOAT_NAN 0xFFFFFFFF
124 #define SFLOAT_ISNAN(A) \
125 (0xFF000000 < (uint32_t)((A) << 1))
126 /* Test if signaling NaN */
127 #define SFLOAT_ISSNAN(A) \
128 (((((A) >> 22) & 0x1FF) == 0x1FE) && ((A) & 0x003FFFFF))
129 /* Raise exception */
130 #define SFLOAT_RAISE(STATE, FLAGS) \
131 ((STATE)->exceptionflags = (sfloat_exceptionflags_t)((STATE)->exceptionflags | (FLAGS)))
133 * Shifts `A' right by the number of bits given in `COUNT'. If any non-zero bits
134 * are shifted off they are forced into the least significand bit of the result
135 * by setting it to one. As a result of this, the value of `COUNT' can be
136 * arbitrarily large; if `COUNT' is greater than 32, the result will be either
137 * zero or one, depending on whether `A' is a zero or non-zero. The result is
138 * stored into the value pointed by `Z'.
140 #define SFLOAT_SHIFT(SIZE, A, COUNT, Z) \
141 *(Z) = ((COUNT) == 0) \
143 : (((COUNT) < (SIZE)) \
144 ? ((A) >> (COUNT)) | (((A) << ((-(COUNT)) & ((SIZE) - 1))) != 0) \
147 /* Extract fractional component */
148 #define SFLOAT_EXTRACT_FRAC(X) \
149 ((uint32_t)((X) & 0x007FFFFF))
150 /* Extract exponent component */
151 #define SFLOAT_EXTRACT_EXP(X) \
152 ((int16_t)((X) >> 23) & 0xFF)
153 /* Extract sign bit */
154 #define SFLOAT_EXTRACT_SIGN(X) \
157 * Normalizes the subnormal value represented by the denormalized significand
158 * `SA'. The normalized exponent and significand are stored at the locations
159 * pointed by `Z' and `SZ' respectively.
161 #define SFLOAT_SUBNORMALIZE(SA, Z, SZ) \
162 (void)(*(SZ) = (SA) << SFLOAT_CLZ((SA), 8), *(Z) = 1 - SFLOAT_CLZ((SA), 8))
164 * Packs the sign `SIGN', exponent `EXP' and significand `SIG' into the value
167 * After the shifting into their proper positions, the fields are added together
168 * to form the result. This means any integer portion of `SIG' will be added
169 * to the exponent. Similarly, because a properly normalized significand will
170 * always have an integer portion equal to one, the exponent input `EXP' should
171 * be one less than the desired result exponent whenever the significant input
172 * `SIG' is a complete, normalized significand.
174 #define SFLOAT_PACK(SIGN, EXP, SIG) \
175 (sfloat_t)((((uint32_t)(SIGN)) << 31) + (((uint32_t)(EXP)) << 23) + (SIG))
178 * Takes two values `a' and `b', one of which is a NaN, and returns the appropriate
179 * NaN result. If either `a' or `b' is a signaling NaN than an invalid exception is
182 static sfloat_t sfloat_propagate_nan(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
183 bool isnan_a = SFLOAT_ISNAN(a);
184 bool issnan_a = SFLOAT_ISSNAN(a);
185 bool isnan_b = SFLOAT_ISNAN(b);
186 bool issnan_b = SFLOAT_ISSNAN(b);
191 if (issnan_a | issnan_b)
192 SFLOAT_RAISE(state, SFLOAT_INVALID);
194 return (issnan_a & isnan_b) ? b : a;
199 * Takes an abstract value having sign `sign_z', exponent `exp_z', and significand
200 * `sig_z' and returns the appropriate value corresponding to the abstract input.
202 * The abstract value is simply rounded and packed into the format. If the abstract
203 * input cannot be represented exactly an inexact exception is raised. If the
204 * abstract input is too large, the overflow and inexact exceptions are both raised
205 * and an infinity or maximal finite value is returned. If the abstract value is
206 * too small, the value is rounded to a subnormal and the underflow and inexact
207 * exceptions are only raised if the value cannot be represented exactly with
210 * The input significand `sig_z' has it's binary point between bits 30 and 29,
211 * this is seven bits to the left of its usual location. The shifted significand
212 * must be normalized or smaller than this. If it's not normalized then the exponent
213 * `exp_z' must be zero; in that case, the result returned is a subnormal number
214 * which must not require rounding. In the more usual case where the significand
215 * is normalized, the exponent must be one less than the *true* exponent.
217 * The handling of underflow and overflow is otherwise in alignment with IEC/IEEE.
219 static sfloat_t SFLOAT_PACK_round(sfloat_state_t *state, bool sign_z, int16_t exp_z, uint32_t sig_z) {
220 sfloat_roundingmode_t mode = state->roundingmode;
221 bool even = !!(mode == SFLOAT_ROUND_NEAREST_EVEN);
222 unsigned char increment = 0x40;
223 unsigned char bits = sig_z & 0x7F;
226 if (mode == SFLOAT_ROUND_TO_ZERO)
231 if (mode == SFLOAT_ROUND_UP)
234 if (mode == SFLOAT_ROUND_DOWN)
240 if (0xFD <= (uint16_t)exp_z) {
241 if ((0xFD < exp_z) || ((exp_z == 0xFD) && ((int32_t)(sig_z + increment) < 0))) {
242 SFLOAT_RAISE(state, SFLOAT_OVERFLOW | SFLOAT_INEXACT);
243 return SFLOAT_PACK(sign_z, 0xFF, 0) - (increment == 0);
246 /* Check for underflow */
247 bool tiny = (state->tiny == SFLOAT_TBEFORE) || (exp_z < -1) || (sig_z + increment < 0x80000000);
248 SFLOAT_SHIFT(32, sig_z, -exp_z, &sig_z);
252 SFLOAT_RAISE(state, SFLOAT_UNDERFLOW);
256 SFLOAT_RAISE(state, SFLOAT_INEXACT);
257 sig_z = (sig_z + increment) >> 7;
258 sig_z &= ~(((bits ^ 0x40) == 0) & even);
261 return SFLOAT_PACK(sign_z, exp_z, sig_z);
265 * Takes an abstract value having sign `sign_z', exponent `exp_z' and significand
266 * `sig_z' and returns the appropriate value corresponding to the abstract input.
267 * This function is exactly like `PACK_round' except the significand does not have
270 * Bit 31 of the significand must be zero and the exponent must be one less than
271 * the *true* exponent.
273 static sfloat_t SFLOAT_PACK_normal(sfloat_state_t *state, bool sign_z, int16_t exp_z, uint32_t sig_z) {
274 unsigned char c = SFLOAT_CLZ(sig_z, 1);
275 return SFLOAT_PACK_round(state, sign_z, exp_z - c, sig_z << c);
279 * Returns the result of adding the absolute values of `a' and `b'. The sign
280 * `sign_z' is ignored if the result is a NaN.
282 static sfloat_t sfloat_add_impl(sfloat_state_t *state, sfloat_t a, sfloat_t b, bool sign_z) {
283 int16_t exp_a = SFLOAT_EXTRACT_EXP(a);
284 int16_t exp_b = SFLOAT_EXTRACT_EXP(b);
286 int16_t exp_d = exp_a - exp_b;
287 uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a) << 6;
288 uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b) << 6;
293 return sig_a ? sfloat_propagate_nan(state, a, b) : a;
298 SFLOAT_SHIFT(32, sig_b, exp_d, &sig_b);
300 } else if (exp_d < 0) {
302 return sig_b ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z, 0xFF, 0);
307 SFLOAT_SHIFT(32, sig_a, -exp_d, &sig_a);
311 return (sig_a | sig_b) ? sfloat_propagate_nan(state, a, b) : a;
313 return SFLOAT_PACK(sign_z, 0, (sig_a + sig_b) >> 6);
314 sig_z = 0x40000000 + sig_a + sig_b;
319 sig_z = (sig_a + sig_b) << 1;
321 if ((int32_t)sig_z < 0) {
322 sig_z = sig_a + sig_b;
326 return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
330 * Returns the result of subtracting the absolute values of `a' and `b'. If the
331 * sign `sign_z' is one, the difference is negated before being returned. The
332 * sign is ignored if the result is a NaN.
334 static sfloat_t sfloat_sub_impl(sfloat_state_t *state, sfloat_t a, sfloat_t b, bool sign_z) {
335 int16_t exp_a = SFLOAT_EXTRACT_EXP(a);
336 int16_t exp_b = SFLOAT_EXTRACT_EXP(b);
338 int16_t exp_d = exp_a - exp_b;
339 uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a) << 7;
340 uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b) << 7;
343 if (0 < exp_d) goto exp_greater_a;
344 if (exp_d < 0) goto exp_greater_b;
348 return sfloat_propagate_nan(state, a, b);
349 SFLOAT_RAISE(state, SFLOAT_INVALID);
356 if (sig_b < sig_a) goto greater_a;
357 if (sig_a < sig_b) goto greater_b;
359 return SFLOAT_PACK(state->roundingmode == SFLOAT_ROUND_DOWN, 0, 0);
363 return (sig_b) ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z ^ 1, 0xFF, 0);
368 SFLOAT_SHIFT(32, sig_a, -exp_d, &sig_a);
371 sig_z = sig_b - sig_a;
378 return (sig_a) ? sfloat_propagate_nan(state, a, b) : a;
383 SFLOAT_SHIFT(32, sig_b, exp_d, &sig_b);
386 sig_z = sig_a - sig_b;
391 return SFLOAT_PACK_normal(state, sign_z, exp_z, sig_z);
394 static GMQCC_INLINE sfloat_t sfloat_add(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
395 bool sign_a = SFLOAT_EXTRACT_SIGN(a);
396 bool sign_b = SFLOAT_EXTRACT_SIGN(b);
397 return (sign_a == sign_b) ? sfloat_add_impl(state, a, b, sign_a)
398 : sfloat_sub_impl(state, a, b, sign_a);
401 static GMQCC_INLINE sfloat_t sfloat_sub(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
402 bool sign_a = SFLOAT_EXTRACT_SIGN(a);
403 bool sign_b = SFLOAT_EXTRACT_SIGN(b);
404 return (sign_a == sign_b) ? sfloat_sub_impl(state, a, b, sign_a)
405 : sfloat_add_impl(state, a, b, sign_a);
408 static sfloat_t sfloat_mul(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
409 int16_t exp_a = SFLOAT_EXTRACT_EXP(a);
410 int16_t exp_b = SFLOAT_EXTRACT_EXP(b);
412 uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a);
413 uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b);
415 uint64_t sig_z64 = 0;
416 bool sign_a = SFLOAT_EXTRACT_SIGN(a);
417 bool sign_b = SFLOAT_EXTRACT_SIGN(b);
418 bool sign_z = sign_a ^ sign_b;
421 if (sig_a || ((exp_b == 0xFF) && sig_b))
422 return sfloat_propagate_nan(state, a, b);
423 if ((exp_b | sig_b) == 0) {
424 SFLOAT_RAISE(state, SFLOAT_INVALID);
427 return SFLOAT_PACK(sign_z, 0xFF, 0);
431 return sfloat_propagate_nan(state, a, b);
432 if ((exp_a | sig_a) == 0) {
433 SFLOAT_RAISE(state, SFLOAT_INVALID);
436 return SFLOAT_PACK(sign_z, 0xFF, 0);
440 return SFLOAT_PACK(sign_z, 0, 0);
441 SFLOAT_SUBNORMALIZE(sig_a, &exp_a, &sig_a);
445 return SFLOAT_PACK(sign_z, 0, 0);
446 SFLOAT_SUBNORMALIZE(sig_b, &exp_b, &sig_b);
448 exp_z = exp_a + exp_b - 0x7F;
449 sig_a = (sig_a | 0x00800000) << 7;
450 sig_b = (sig_b | 0x00800000) << 8;
451 SFLOAT_SHIFT(64, ((uint64_t)sig_a) * sig_b, 32, &sig_z64);
453 if (0 <= (int32_t)(sig_z << 1)) {
457 return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
460 static sfloat_t sfloat_div(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
461 int16_t exp_a = SFLOAT_EXTRACT_EXP(a);
462 int16_t exp_b = SFLOAT_EXTRACT_EXP(b);
464 uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a);
465 uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b);
467 bool sign_a = SFLOAT_EXTRACT_SIGN(a);
468 bool sign_b = SFLOAT_EXTRACT_SIGN(b);
469 bool sign_z = sign_a ^ sign_b;
473 return sfloat_propagate_nan(state, a, b);
476 return sfloat_propagate_nan(state, a, b);
477 SFLOAT_RAISE(state, SFLOAT_INVALID);
480 return SFLOAT_PACK(sign_z, 0xFF, 0);
483 return (sig_b) ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z, 0, 0);
486 if ((exp_a | sig_a) == 0) {
487 SFLOAT_RAISE(state, SFLOAT_INVALID);
490 SFLOAT_RAISE(state, SFLOAT_DIVBYZERO);
491 return SFLOAT_PACK(sign_z, 0xFF, 0);
493 SFLOAT_SUBNORMALIZE(sig_b, &exp_b, &sig_b);
497 return SFLOAT_PACK(sign_z, 0, 0);
498 SFLOAT_SUBNORMALIZE(sig_a, &exp_a, &sig_a);
500 exp_z = exp_a - exp_b + 0x7D;
501 sig_a = (sig_a | 0x00800000) << 7;
502 sig_b = (sig_b | 0x00800000) << 8;
503 if (sig_b <= (sig_a + sig_a)) {
507 sig_z = (((uint64_t)sig_a) << 32) / sig_b;
508 if ((sig_z & 0x3F) == 0)
509 sig_z |= ((uint64_t)sig_b * sig_z != ((uint64_t)sig_a) << 32);
510 return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
513 static sfloat_t sfloat_neg(sfloat_state_t *state, sfloat_t a) {
516 return sfloat_mul(state, a, neg.s);
519 static GMQCC_INLINE void sfloat_check(lex_ctx_t ctx, sfloat_state_t *state, const char *vec) {
520 /* Exception comes from vector component */
522 if (state->exceptionflags & SFLOAT_DIVBYZERO)
523 compile_error(ctx, "division by zero in `%s' component", vec);
524 if (state->exceptionflags & SFLOAT_INVALID)
525 compile_error(ctx, "undefined (inf) in `%s' component", vec);
526 if (state->exceptionflags & SFLOAT_OVERFLOW)
527 compile_error(ctx, "arithmetic overflow in `%s' component", vec);
528 if (state->exceptionflags & SFLOAT_UNDERFLOW)
529 compile_error(ctx, "arithmetic underflow in `%s' component", vec);
532 if (state->exceptionflags & SFLOAT_DIVBYZERO)
533 compile_error(ctx, "division by zero");
534 if (state->exceptionflags & SFLOAT_INVALID)
535 compile_error(ctx, "undefined (inf)");
536 if (state->exceptionflags & SFLOAT_OVERFLOW)
537 compile_error(ctx, "arithmetic overflow");
538 if (state->exceptionflags & SFLOAT_UNDERFLOW)
539 compile_error(ctx, "arithmetic underflow");
542 static GMQCC_INLINE void sfloat_init(sfloat_state_t *state) {
543 state->exceptionflags = SFLOAT_NOEXCEPT;
544 state->roundingmode = FOLD_ROUNDING;
545 state->tiny = FOLD_TINYNESS;
549 * There is two stages to constant folding in GMQCC: there is the parse
550 * stage constant folding, where, with the help of the AST, operator
551 * usages can be constant folded. Then there is the constant folding
552 * in the IR for things like eliding if statements, can occur.
554 * This file is thus, split into two parts.
557 #define isfloat(X) (((ast_expression*)(X))->vtype == TYPE_FLOAT)
558 #define isvector(X) (((ast_expression*)(X))->vtype == TYPE_VECTOR)
559 #define isstring(X) (((ast_expression*)(X))->vtype == TYPE_STRING)
560 #define isarray(X) (((ast_expression*)(X))->vtype == TYPE_ARRAY)
561 #define isfloats(X,Y) (isfloat (X) && isfloat (Y))
564 * Implementation of basic vector math for vec3_t, for trivial constant
567 * TODO: gcc/clang hinting for autovectorization
583 sfloat_state_t state[3];
586 static GMQCC_INLINE vec3_soft_t vec3_soft_convert(vec3_t vec) {
594 static GMQCC_INLINE bool vec3_soft_exception(vec3_soft_state_t *vstate, size_t index) {
595 sfloat_exceptionflags_t flags = vstate->state[index].exceptionflags;
596 if (flags & SFLOAT_DIVBYZERO) return true;
597 if (flags & SFLOAT_INVALID) return true;
598 if (flags & SFLOAT_OVERFLOW) return true;
599 if (flags & SFLOAT_UNDERFLOW) return true;
603 static GMQCC_INLINE void vec3_soft_eval(vec3_soft_state_t *state,
604 sfloat_t (*callback)(sfloat_state_t *, sfloat_t, sfloat_t),
608 vec3_soft_t sa = vec3_soft_convert(a);
609 vec3_soft_t sb = vec3_soft_convert(b);
610 callback(&state->state[0], sa.x.s, sb.x.s);
611 if (vec3_soft_exception(state, 0)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_X);
612 callback(&state->state[1], sa.y.s, sb.y.s);
613 if (vec3_soft_exception(state, 1)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_Y);
614 callback(&state->state[2], sa.z.s, sb.z.s);
615 if (vec3_soft_exception(state, 2)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_Z);
618 static GMQCC_INLINE void vec3_check_except(vec3_t a,
621 sfloat_t (*callback)(sfloat_state_t *, sfloat_t, sfloat_t))
623 vec3_soft_state_t state;
625 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
628 sfloat_init(&state.state[0]);
629 sfloat_init(&state.state[1]);
630 sfloat_init(&state.state[2]);
632 vec3_soft_eval(&state, callback, a, b);
633 if (state.faults & VEC_COMP_X) sfloat_check(ctx, &state.state[0], "x");
634 if (state.faults & VEC_COMP_Y) sfloat_check(ctx, &state.state[1], "y");
635 if (state.faults & VEC_COMP_Z) sfloat_check(ctx, &state.state[2], "z");
638 static GMQCC_INLINE vec3_t vec3_add(lex_ctx_t ctx, vec3_t a, vec3_t b) {
640 vec3_check_except(a, b, ctx, &sfloat_add);
647 static GMQCC_INLINE vec3_t vec3_sub(lex_ctx_t ctx, vec3_t a, vec3_t b) {
649 vec3_check_except(a, b, ctx, &sfloat_sub);
656 static GMQCC_INLINE vec3_t vec3_neg(lex_ctx_t ctx, vec3_t a) {
661 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
672 sfloat_neg(&s[0], v[0].s);
673 sfloat_neg(&s[1], v[1].s);
674 sfloat_neg(&s[2], v[2].s);
676 sfloat_check(ctx, &s[0], NULL);
677 sfloat_check(ctx, &s[1], NULL);
678 sfloat_check(ctx, &s[2], NULL);
687 static GMQCC_INLINE vec3_t vec3_or(vec3_t a, vec3_t b) {
689 out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b.x));
690 out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b.y));
691 out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b.z));
695 static GMQCC_INLINE vec3_t vec3_orvf(vec3_t a, qcfloat_t b) {
697 out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b));
698 out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b));
699 out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b));
703 static GMQCC_INLINE vec3_t vec3_and(vec3_t a, vec3_t b) {
705 out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b.x));
706 out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b.y));
707 out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b.z));
711 static GMQCC_INLINE vec3_t vec3_andvf(vec3_t a, qcfloat_t b) {
713 out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b));
714 out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b));
715 out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b));
719 static GMQCC_INLINE vec3_t vec3_xor(vec3_t a, vec3_t b) {
721 out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b.x));
722 out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b.y));
723 out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b.z));
727 static GMQCC_INLINE vec3_t vec3_xorvf(vec3_t a, qcfloat_t b) {
729 out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b));
730 out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b));
731 out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b));
735 static GMQCC_INLINE vec3_t vec3_not(vec3_t a) {
743 static GMQCC_INLINE qcfloat_t vec3_mulvv(lex_ctx_t ctx, vec3_t a, vec3_t b) {
749 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
752 sa = vec3_soft_convert(a);
753 sb = vec3_soft_convert(b);
761 r[0] = sfloat_mul(&s[0], sa.x.s, sb.x.s);
762 r[1] = sfloat_mul(&s[1], sa.y.s, sb.y.s);
763 r[2] = sfloat_mul(&s[2], sa.z.s, sb.z.s);
764 r[3] = sfloat_add(&s[3], r[0], r[1]);
765 r[4] = sfloat_add(&s[4], r[3], r[2]);
767 sfloat_check(ctx, &s[0], NULL);
768 sfloat_check(ctx, &s[1], NULL);
769 sfloat_check(ctx, &s[2], NULL);
770 sfloat_check(ctx, &s[3], NULL);
771 sfloat_check(ctx, &s[4], NULL);
774 return (a.x * b.x + a.y * b.y + a.z * b.z);
777 static GMQCC_INLINE vec3_t vec3_mulvf(lex_ctx_t ctx, vec3_t a, qcfloat_t b) {
783 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
786 sa = vec3_soft_convert(a);
792 sfloat_mul(&s[0], sa.x.s, sb.s);
793 sfloat_mul(&s[1], sa.y.s, sb.s);
794 sfloat_mul(&s[2], sa.z.s, sb.s);
796 sfloat_check(ctx, &s[0], "x");
797 sfloat_check(ctx, &s[1], "y");
798 sfloat_check(ctx, &s[2], "z");
807 static GMQCC_INLINE bool vec3_cmp(vec3_t a, vec3_t b) {
813 static GMQCC_INLINE vec3_t vec3_create(float x, float y, float z) {
821 static GMQCC_INLINE qcfloat_t vec3_notf(vec3_t a) {
822 return (!a.x && !a.y && !a.z);
825 static GMQCC_INLINE bool vec3_pbool(vec3_t a) {
826 return (a.x || a.y || a.z);
829 static GMQCC_INLINE vec3_t vec3_cross(lex_ctx_t ctx, vec3_t a, vec3_t b) {
836 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
839 sa = vec3_soft_convert(a);
840 sb = vec3_soft_convert(b);
852 r[0] = sfloat_mul(&s[0], sa.y.s, sb.z.s);
853 r[1] = sfloat_mul(&s[1], sa.z.s, sb.y.s);
854 r[2] = sfloat_mul(&s[2], sa.z.s, sb.x.s);
855 r[3] = sfloat_mul(&s[3], sa.x.s, sb.z.s);
856 r[4] = sfloat_mul(&s[4], sa.x.s, sb.y.s);
857 r[5] = sfloat_mul(&s[5], sa.y.s, sb.x.s);
858 r[6] = sfloat_sub(&s[6], r[0], r[1]);
859 r[7] = sfloat_sub(&s[7], r[2], r[3]);
860 r[8] = sfloat_sub(&s[8], r[4], r[5]);
862 sfloat_check(ctx, &s[0], NULL);
863 sfloat_check(ctx, &s[1], NULL);
864 sfloat_check(ctx, &s[2], NULL);
865 sfloat_check(ctx, &s[3], NULL);
866 sfloat_check(ctx, &s[4], NULL);
867 sfloat_check(ctx, &s[5], NULL);
868 sfloat_check(ctx, &s[6], "x");
869 sfloat_check(ctx, &s[7], "y");
870 sfloat_check(ctx, &s[8], "z");
873 out.x = a.y * b.z - a.z * b.y;
874 out.y = a.z * b.x - a.x * b.z;
875 out.z = a.x * b.y - a.y * b.x;
879 static lex_ctx_t fold_ctx(fold_t *fold) {
881 if (fold->parser->lex)
882 return parser_ctx(fold->parser);
884 memset(&ctx, 0, sizeof(ctx));
888 static GMQCC_INLINE bool fold_immediate_true(fold_t *fold, ast_value *v) {
889 switch (v->expression.vtype) {
891 return !!v->constval.vfloat;
893 return !!v->constval.vint;
895 if (OPTS_FLAG(CORRECT_LOGIC))
896 return vec3_pbool(v->constval.vvec);
897 return !!(v->constval.vvec.x);
899 if (!v->constval.vstring)
901 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
903 return !!v->constval.vstring[0];
905 compile_error(fold_ctx(fold), "internal error: fold_immediate_true on invalid type");
908 return !!v->constval.vfunc;
911 /* Handy macros to determine if an ast_value can be constant folded. */
912 #define fold_can_1(X) \
913 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
914 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
916 #define fold_can_2(X, Y) (fold_can_1(X) && fold_can_1(Y))
918 #define fold_immvalue_float(E) ((E)->constval.vfloat)
919 #define fold_immvalue_vector(E) ((E)->constval.vvec)
920 #define fold_immvalue_string(E) ((E)->constval.vstring)
922 fold_t *fold_init(parser_t *parser) {
923 fold_t *fold = (fold_t*)mem_a(sizeof(fold_t));
924 fold->parser = parser;
925 fold->imm_float = NULL;
926 fold->imm_vector = NULL;
927 fold->imm_string = NULL;
928 fold->imm_string_untranslate = util_htnew(FOLD_STRING_UNTRANSLATE_HTSIZE);
929 fold->imm_string_dotranslate = util_htnew(FOLD_STRING_DOTRANSLATE_HTSIZE);
932 * prime the tables with common constant values at constant
935 (void)fold_constgen_float (fold, 0.0f, false);
936 (void)fold_constgen_float (fold, 1.0f, false);
937 (void)fold_constgen_float (fold, -1.0f, false);
938 (void)fold_constgen_float (fold, 2.0f, false);
940 (void)fold_constgen_vector(fold, vec3_create(0.0f, 0.0f, 0.0f));
941 (void)fold_constgen_vector(fold, vec3_create(-1.0f, -1.0f, -1.0f));
946 bool fold_generate(fold_t *fold, ir_builder *ir) {
947 /* generate globals for immediate folded values */
951 for (i = 0; i < vec_size(fold->imm_float); ++i)
952 if (!ast_global_codegen ((cur = fold->imm_float[i]), ir, false)) goto err;
953 for (i = 0; i < vec_size(fold->imm_vector); ++i)
954 if (!ast_global_codegen((cur = fold->imm_vector[i]), ir, false)) goto err;
955 for (i = 0; i < vec_size(fold->imm_string); ++i)
956 if (!ast_global_codegen((cur = fold->imm_string[i]), ir, false)) goto err;
961 con_out("failed to generate global %s\n", cur->name);
962 ir_builder_delete(ir);
966 void fold_cleanup(fold_t *fold) {
969 for (i = 0; i < vec_size(fold->imm_float); ++i) ast_delete(fold->imm_float[i]);
970 for (i = 0; i < vec_size(fold->imm_vector); ++i) ast_delete(fold->imm_vector[i]);
971 for (i = 0; i < vec_size(fold->imm_string); ++i) ast_delete(fold->imm_string[i]);
973 vec_free(fold->imm_float);
974 vec_free(fold->imm_vector);
975 vec_free(fold->imm_string);
977 util_htdel(fold->imm_string_untranslate);
978 util_htdel(fold->imm_string_dotranslate);
983 ast_expression *fold_constgen_float(fold_t *fold, qcfloat_t value, bool inexact) {
984 ast_value *out = NULL;
987 for (i = 0; i < vec_size(fold->imm_float); i++) {
988 if (!memcmp(&fold->imm_float[i]->constval.vfloat, &value, sizeof(qcfloat_t)))
989 return (ast_expression*)fold->imm_float[i];
992 out = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_FLOAT);
994 out->hasvalue = true;
995 out->inexact = inexact;
996 out->constval.vfloat = value;
998 vec_push(fold->imm_float, out);
1000 return (ast_expression*)out;
1003 ast_expression *fold_constgen_vector(fold_t *fold, vec3_t value) {
1007 for (i = 0; i < vec_size(fold->imm_vector); i++) {
1008 if (vec3_cmp(fold->imm_vector[i]->constval.vvec, value))
1009 return (ast_expression*)fold->imm_vector[i];
1012 out = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_VECTOR);
1013 out->cvq = CV_CONST;
1014 out->hasvalue = true;
1015 out->constval.vvec = value;
1017 vec_push(fold->imm_vector, out);
1019 return (ast_expression*)out;
1022 ast_expression *fold_constgen_string(fold_t *fold, const char *str, bool translate) {
1023 hash_table_t *table = (translate) ? fold->imm_string_untranslate : fold->imm_string_dotranslate;
1024 ast_value *out = NULL;
1025 size_t hash = util_hthash(table, str);
1027 if ((out = (ast_value*)util_htgeth(table, str, hash)))
1028 return (ast_expression*)out;
1032 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(fold->parser->translated++));
1033 out = ast_value_new(parser_ctx(fold->parser), name, TYPE_STRING);
1034 out->expression.flags |= AST_FLAG_INCLUDE_DEF; /* def needs to be included for translatables */
1036 out = ast_value_new(fold_ctx(fold), "#IMMEDIATE", TYPE_STRING);
1038 out->cvq = CV_CONST;
1039 out->hasvalue = true;
1041 out->constval.vstring = parser_strdup(str);
1043 vec_push(fold->imm_string, out);
1044 util_htseth(table, str, hash, out);
1046 return (ast_expression*)out;
1050 void (*callback)(void);
1051 sfloat_t (*binary)(sfloat_state_t *, sfloat_t, sfloat_t);
1052 sfloat_t (*unary)(sfloat_state_t *, sfloat_t);
1053 } float_check_callback_t;
1055 static bool fold_check_except_float_impl(void (*callback)(void),
1060 float_check_callback_t call;
1064 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS) && !OPTS_WARN(WARN_INEXACT_COMPARES))
1067 call.callback = callback;
1069 ca.f = fold_immvalue_float(a);
1072 cb.f = fold_immvalue_float(b);
1073 call.binary(&s, ca.s, cb.s);
1075 call.unary(&s, ca.s);
1078 if (s.exceptionflags == 0)
1081 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
1082 goto inexact_possible;
1084 sfloat_check(fold_ctx(fold), &s, NULL);
1087 return s.exceptionflags & SFLOAT_INEXACT;
1090 #define fold_check_except_float(CALLBACK, FOLD, A, B) \
1091 fold_check_except_float_impl(((void (*)(void))(CALLBACK)), (FOLD), (A), (B))
1093 static bool fold_check_inexact_float(fold_t *fold, ast_value *a, ast_value *b) {
1094 lex_ctx_t ctx = fold_ctx(fold);
1095 if (!OPTS_WARN(WARN_INEXACT_COMPARES))
1097 if (!a->inexact && !b->inexact)
1099 return compile_warning(ctx, WARN_INEXACT_COMPARES, "inexact value in comparison");
1102 static GMQCC_INLINE ast_expression *fold_op_mul_vec(fold_t *fold, vec3_t vec, ast_value *sel, const char *set) {
1103 qcfloat_t x = (&vec.x)[set[0]-'x'];
1104 qcfloat_t y = (&vec.x)[set[1]-'x'];
1105 qcfloat_t z = (&vec.x)[set[2]-'x'];
1107 ast_expression *out;
1108 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
1109 out = (ast_expression*)ast_member_new(fold_ctx(fold), (ast_expression*)sel, set[0]-'x', NULL);
1110 out->node.keep = false;
1111 ((ast_member*)out)->rvalue = true;
1113 return (ast_expression*)ast_binary_new(fold_ctx(fold), INSTR_MUL_F, fold_constgen_float(fold, x, false), out);
1119 static GMQCC_INLINE ast_expression *fold_op_neg(fold_t *fold, ast_value *a) {
1121 if (fold_can_1(a)) {
1122 /* Negation can produce inexact as well */
1123 bool inexact = fold_check_except_float(&sfloat_neg, fold, a, NULL);
1124 return fold_constgen_float(fold, -fold_immvalue_float(a), inexact);
1126 } else if (isvector(a)) {
1128 return fold_constgen_vector(fold, vec3_neg(fold_ctx(fold), fold_immvalue_vector(a)));
1133 static GMQCC_INLINE ast_expression *fold_op_not(fold_t *fold, ast_value *a) {
1136 return fold_constgen_float(fold, !fold_immvalue_float(a), false);
1137 } else if (isvector(a)) {
1139 return fold_constgen_float(fold, vec3_notf(fold_immvalue_vector(a)), false);
1140 } else if (isstring(a)) {
1141 if (fold_can_1(a)) {
1142 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
1143 return fold_constgen_float(fold, !fold_immvalue_string(a), false);
1145 return fold_constgen_float(fold, !fold_immvalue_string(a) || !*fold_immvalue_string(a), false);
1151 static GMQCC_INLINE ast_expression *fold_op_add(fold_t *fold, ast_value *a, ast_value *b) {
1153 if (fold_can_2(a, b)) {
1154 bool inexact = fold_check_except_float(&sfloat_add, fold, a, b);
1155 return fold_constgen_float(fold, fold_immvalue_float(a) + fold_immvalue_float(b), inexact);
1157 } else if (isvector(a)) {
1158 if (fold_can_2(a, b))
1159 return fold_constgen_vector(fold, vec3_add(fold_ctx(fold),
1160 fold_immvalue_vector(a),
1161 fold_immvalue_vector(b)));
1166 static GMQCC_INLINE ast_expression *fold_op_sub(fold_t *fold, ast_value *a, ast_value *b) {
1168 if (fold_can_2(a, b)) {
1169 bool inexact = fold_check_except_float(&sfloat_sub, fold, a, b);
1170 return fold_constgen_float(fold, fold_immvalue_float(a) - fold_immvalue_float(b), inexact);
1172 } else if (isvector(a)) {
1173 if (fold_can_2(a, b))
1174 return fold_constgen_vector(fold, vec3_sub(fold_ctx(fold),
1175 fold_immvalue_vector(a),
1176 fold_immvalue_vector(b)));
1181 static GMQCC_INLINE ast_expression *fold_op_mul(fold_t *fold, ast_value *a, ast_value *b) {
1184 if (fold_can_2(a, b))
1185 return fold_constgen_vector(fold, vec3_mulvf(fold_ctx(fold), fold_immvalue_vector(b), fold_immvalue_float(a)));
1187 if (fold_can_2(a, b)) {
1188 bool inexact = fold_check_except_float(&sfloat_mul, fold, a, b);
1189 return fold_constgen_float(fold, fold_immvalue_float(a) * fold_immvalue_float(b), inexact);
1192 } else if (isvector(a)) {
1194 if (fold_can_2(a, b))
1195 return fold_constgen_vector(fold, vec3_mulvf(fold_ctx(fold), fold_immvalue_vector(a), fold_immvalue_float(b)));
1197 if (fold_can_2(a, b)) {
1198 return fold_constgen_float(fold, vec3_mulvv(fold_ctx(fold), fold_immvalue_vector(a), fold_immvalue_vector(b)), false);
1199 } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(a)) {
1200 ast_expression *out;
1201 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "xyz"))) return out;
1202 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "yxz"))) return out;
1203 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(a), b, "zxy"))) return out;
1204 } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(b)) {
1205 ast_expression *out;
1206 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "xyz"))) return out;
1207 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "yxz"))) return out;
1208 if ((out = fold_op_mul_vec(fold, fold_immvalue_vector(b), a, "zxy"))) return out;
1215 static GMQCC_INLINE ast_expression *fold_op_div(fold_t *fold, ast_value *a, ast_value *b) {
1217 if (fold_can_2(a, b)) {
1218 bool inexact = fold_check_except_float(&sfloat_div, fold, a, b);
1219 return fold_constgen_float(fold, fold_immvalue_float(a) / fold_immvalue_float(b), inexact);
1220 } else if (fold_can_1(b)) {
1221 return (ast_expression*)ast_binary_new(
1225 fold_constgen_float(fold, 1.0f / fold_immvalue_float(b), false)
1228 } else if (isvector(a)) {
1229 if (fold_can_2(a, b)) {
1230 return fold_constgen_vector(fold, vec3_mulvf(fold_ctx(fold), fold_immvalue_vector(a), 1.0f / fold_immvalue_float(b)));
1232 return (ast_expression*)ast_binary_new(
1237 ? (ast_expression*)fold_constgen_float(fold, 1.0f / fold_immvalue_float(b), false)
1238 : (ast_expression*)ast_binary_new(
1241 (ast_expression*)fold->imm_float[1],
1250 static GMQCC_INLINE ast_expression *fold_op_mod(fold_t *fold, ast_value *a, ast_value *b) {
1251 return (fold_can_2(a, b))
1252 ? fold_constgen_float(fold, fmod(fold_immvalue_float(a), fold_immvalue_float(b)), false)
1256 static GMQCC_INLINE ast_expression *fold_op_bor(fold_t *fold, ast_value *a, ast_value *b) {
1258 if (fold_can_2(a, b))
1259 return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) | ((qcint_t)fold_immvalue_float(b))), false);
1262 if (fold_can_2(a, b))
1263 return fold_constgen_vector(fold, vec3_or(fold_immvalue_vector(a), fold_immvalue_vector(b)));
1265 if (fold_can_2(a, b))
1266 return fold_constgen_vector(fold, vec3_orvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
1272 static GMQCC_INLINE ast_expression *fold_op_band(fold_t *fold, ast_value *a, ast_value *b) {
1274 if (fold_can_2(a, b))
1275 return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) & ((qcint_t)fold_immvalue_float(b))), false);
1278 if (fold_can_2(a, b))
1279 return fold_constgen_vector(fold, vec3_and(fold_immvalue_vector(a), fold_immvalue_vector(b)));
1281 if (fold_can_2(a, b))
1282 return fold_constgen_vector(fold, vec3_andvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
1288 static GMQCC_INLINE ast_expression *fold_op_xor(fold_t *fold, ast_value *a, ast_value *b) {
1290 if (fold_can_2(a, b))
1291 return fold_constgen_float(fold, (qcfloat_t)(((qcint_t)fold_immvalue_float(a)) ^ ((qcint_t)fold_immvalue_float(b))), false);
1293 if (fold_can_2(a, b)) {
1295 return fold_constgen_vector(fold, vec3_xor(fold_immvalue_vector(a), fold_immvalue_vector(b)));
1297 return fold_constgen_vector(fold, vec3_xorvf(fold_immvalue_vector(a), fold_immvalue_float(b)));
1303 static GMQCC_INLINE ast_expression *fold_op_lshift(fold_t *fold, ast_value *a, ast_value *b) {
1304 if (fold_can_2(a, b) && isfloats(a, b))
1305 return fold_constgen_float(fold, (qcfloat_t)floorf(fold_immvalue_float(a) * powf(2.0f, fold_immvalue_float(b))), false);
1309 static GMQCC_INLINE ast_expression *fold_op_rshift(fold_t *fold, ast_value *a, ast_value *b) {
1310 if (fold_can_2(a, b) && isfloats(a, b))
1311 return fold_constgen_float(fold, (qcfloat_t)floorf(fold_immvalue_float(a) / powf(2.0f, fold_immvalue_float(b))), false);
1315 static GMQCC_INLINE ast_expression *fold_op_andor(fold_t *fold, ast_value *a, ast_value *b, float expr) {
1316 if (fold_can_2(a, b)) {
1317 if (OPTS_FLAG(PERL_LOGIC)) {
1319 return (fold_immediate_true(fold, a)) ? (ast_expression*)a : (ast_expression*)b;
1321 return (fold_immediate_true(fold, a)) ? (ast_expression*)b : (ast_expression*)a;
1323 return fold_constgen_float (
1325 ((expr) ? (fold_immediate_true(fold, a) || fold_immediate_true(fold, b))
1326 : (fold_immediate_true(fold, a) && fold_immediate_true(fold, b)))
1336 static GMQCC_INLINE ast_expression *fold_op_tern(fold_t *fold, ast_value *a, ast_value *b, ast_value *c) {
1337 if (fold_can_1(a)) {
1338 return fold_immediate_true(fold, a)
1339 ? (ast_expression*)b
1340 : (ast_expression*)c;
1345 static GMQCC_INLINE ast_expression *fold_op_exp(fold_t *fold, ast_value *a, ast_value *b) {
1346 if (fold_can_2(a, b))
1347 return fold_constgen_float(fold, (qcfloat_t)powf(fold_immvalue_float(a), fold_immvalue_float(b)), false);
1351 static GMQCC_INLINE ast_expression *fold_op_lteqgt(fold_t *fold, ast_value *a, ast_value *b) {
1352 if (fold_can_2(a,b)) {
1353 fold_check_inexact_float(fold, a, b);
1354 if (fold_immvalue_float(a) < fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[2];
1355 if (fold_immvalue_float(a) == fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[0];
1356 if (fold_immvalue_float(a) > fold_immvalue_float(b)) return (ast_expression*)fold->imm_float[1];
1361 static GMQCC_INLINE ast_expression *fold_op_ltgt(fold_t *fold, ast_value *a, ast_value *b, bool lt) {
1362 if (fold_can_2(a, b)) {
1363 fold_check_inexact_float(fold, a, b);
1364 return (lt) ? (ast_expression*)fold->imm_float[!!(fold_immvalue_float(a) < fold_immvalue_float(b))]
1365 : (ast_expression*)fold->imm_float[!!(fold_immvalue_float(a) > fold_immvalue_float(b))];
1370 static GMQCC_INLINE ast_expression *fold_op_cmp(fold_t *fold, ast_value *a, ast_value *b, bool ne) {
1371 if (fold_can_2(a, b)) {
1372 if (isfloat(a) && isfloat(b)) {
1373 float la = fold_immvalue_float(a);
1374 float lb = fold_immvalue_float(b);
1375 fold_check_inexact_float(fold, a, b);
1376 return (ast_expression*)fold->imm_float[!(ne ? la == lb : la != lb)];
1377 } if (isvector(a) && isvector(b)) {
1378 vec3_t la = fold_immvalue_vector(a);
1379 vec3_t lb = fold_immvalue_vector(b);
1380 return (ast_expression*)fold->imm_float[!(ne ? vec3_cmp(la, lb) : !vec3_cmp(la, lb))];
1386 static GMQCC_INLINE ast_expression *fold_op_bnot(fold_t *fold, ast_value *a) {
1389 return fold_constgen_float(fold, -1-fold_immvalue_float(a), false);
1393 return fold_constgen_vector(fold, vec3_not(fold_immvalue_vector(a)));
1399 static GMQCC_INLINE ast_expression *fold_op_cross(fold_t *fold, ast_value *a, ast_value *b) {
1400 if (fold_can_2(a, b))
1401 return fold_constgen_vector(fold, vec3_cross(fold_ctx(fold),
1402 fold_immvalue_vector(a),
1403 fold_immvalue_vector(b)));
1407 static GMQCC_INLINE ast_expression *fold_op_length(fold_t *fold, ast_value *a) {
1408 if (fold_can_1(a) && isstring(a))
1409 return fold_constgen_float(fold, strlen(fold_immvalue_string(a)), false);
1411 return fold_constgen_float(fold, vec_size(a->initlist), false);
1415 ast_expression *fold_op(fold_t *fold, const oper_info *info, ast_expression **opexprs) {
1416 ast_value *a = (ast_value*)opexprs[0];
1417 ast_value *b = (ast_value*)opexprs[1];
1418 ast_value *c = (ast_value*)opexprs[2];
1419 ast_expression *e = NULL;
1421 /* can a fold operation be applied to this operator usage? */
1425 switch(info->operands) {
1426 case 3: if(!c) return NULL;
1427 case 2: if(!b) return NULL;
1430 compile_error(fold_ctx(fold), "internal error: fold_op no operands to fold\n");
1436 * we could use a boolean and default case but ironically gcc produces
1437 * invalid broken assembly from that operation. clang/tcc get it right,
1438 * but interestingly ignore compiling this to a jump-table when I do that,
1439 * this happens to be the most efficent method, since you have per-level
1440 * granularity on the pointer check happening only for the case you check
1441 * it in. Opposed to the default method which would involve a boolean and
1442 * pointer check after wards.
1444 #define fold_op_case(ARGS, ARGS_OPID, OP, ARGS_FOLD) \
1445 case opid##ARGS ARGS_OPID: \
1446 if ((e = fold_op_##OP ARGS_FOLD)) { \
1447 ++opts_optimizationcount[OPTIM_CONST_FOLD]; \
1452 fold_op_case(2, ('-', 'P'), neg, (fold, a));
1453 fold_op_case(2, ('!', 'P'), not, (fold, a));
1454 fold_op_case(1, ('+'), add, (fold, a, b));
1455 fold_op_case(1, ('-'), sub, (fold, a, b));
1456 fold_op_case(1, ('*'), mul, (fold, a, b));
1457 fold_op_case(1, ('/'), div, (fold, a, b));
1458 fold_op_case(1, ('%'), mod, (fold, a, b));
1459 fold_op_case(1, ('|'), bor, (fold, a, b));
1460 fold_op_case(1, ('&'), band, (fold, a, b));
1461 fold_op_case(1, ('^'), xor, (fold, a, b));
1462 fold_op_case(1, ('<'), ltgt, (fold, a, b, true));
1463 fold_op_case(1, ('>'), ltgt, (fold, a, b, false));
1464 fold_op_case(2, ('<', '<'), lshift, (fold, a, b));
1465 fold_op_case(2, ('>', '>'), rshift, (fold, a, b));
1466 fold_op_case(2, ('|', '|'), andor, (fold, a, b, true));
1467 fold_op_case(2, ('&', '&'), andor, (fold, a, b, false));
1468 fold_op_case(2, ('?', ':'), tern, (fold, a, b, c));
1469 fold_op_case(2, ('*', '*'), exp, (fold, a, b));
1470 fold_op_case(3, ('<','=','>'), lteqgt, (fold, a, b));
1471 fold_op_case(2, ('!', '='), cmp, (fold, a, b, true));
1472 fold_op_case(2, ('=', '='), cmp, (fold, a, b, false));
1473 fold_op_case(2, ('~', 'P'), bnot, (fold, a));
1474 fold_op_case(2, ('>', '<'), cross, (fold, a, b));
1475 fold_op_case(3, ('l', 'e', 'n'), length, (fold, a));
1478 compile_error(fold_ctx(fold), "internal error: attempted to constant-fold for unsupported operator");
1483 * Constant folding for compiler intrinsics, similar approach to operator
1484 * folding, primarily: individual functions for each intrinsics to fold,
1485 * and a generic selection function.
1487 static GMQCC_INLINE ast_expression *fold_intrin_isfinite(fold_t *fold, ast_value *a) {
1488 return fold_constgen_float(fold, isfinite(fold_immvalue_float(a)), false);
1490 static GMQCC_INLINE ast_expression *fold_intrin_isinf(fold_t *fold, ast_value *a) {
1491 return fold_constgen_float(fold, isinf(fold_immvalue_float(a)), false);
1493 static GMQCC_INLINE ast_expression *fold_intrin_isnan(fold_t *fold, ast_value *a) {
1494 return fold_constgen_float(fold, isnan(fold_immvalue_float(a)), false);
1496 static GMQCC_INLINE ast_expression *fold_intrin_isnormal(fold_t *fold, ast_value *a) {
1497 return fold_constgen_float(fold, isnormal(fold_immvalue_float(a)), false);
1499 static GMQCC_INLINE ast_expression *fold_intrin_signbit(fold_t *fold, ast_value *a) {
1500 return fold_constgen_float(fold, signbit(fold_immvalue_float(a)), false);
1502 static GMQCC_INLINE ast_expression *fold_intirn_acosh(fold_t *fold, ast_value *a) {
1503 return fold_constgen_float(fold, acoshf(fold_immvalue_float(a)), false);
1505 static GMQCC_INLINE ast_expression *fold_intrin_asinh(fold_t *fold, ast_value *a) {
1506 return fold_constgen_float(fold, asinhf(fold_immvalue_float(a)), false);
1508 static GMQCC_INLINE ast_expression *fold_intrin_atanh(fold_t *fold, ast_value *a) {
1509 return fold_constgen_float(fold, (float)atanh(fold_immvalue_float(a)), false);
1511 static GMQCC_INLINE ast_expression *fold_intrin_exp(fold_t *fold, ast_value *a) {
1512 return fold_constgen_float(fold, expf(fold_immvalue_float(a)), false);
1514 static GMQCC_INLINE ast_expression *fold_intrin_exp2(fold_t *fold, ast_value *a) {
1515 return fold_constgen_float(fold, exp2f(fold_immvalue_float(a)), false);
1517 static GMQCC_INLINE ast_expression *fold_intrin_expm1(fold_t *fold, ast_value *a) {
1518 return fold_constgen_float(fold, expm1f(fold_immvalue_float(a)), false);
1520 static GMQCC_INLINE ast_expression *fold_intrin_mod(fold_t *fold, ast_value *lhs, ast_value *rhs) {
1521 return fold_constgen_float(fold, fmodf(fold_immvalue_float(lhs), fold_immvalue_float(rhs)), false);
1523 static GMQCC_INLINE ast_expression *fold_intrin_pow(fold_t *fold, ast_value *lhs, ast_value *rhs) {
1524 return fold_constgen_float(fold, powf(fold_immvalue_float(lhs), fold_immvalue_float(rhs)), false);
1526 static GMQCC_INLINE ast_expression *fold_intrin_fabs(fold_t *fold, ast_value *a) {
1527 return fold_constgen_float(fold, fabsf(fold_immvalue_float(a)), false);
1531 ast_expression *fold_intrin(fold_t *fold, const char *intrin, ast_expression **arg) {
1532 ast_expression *ret = NULL;
1533 ast_value *a = (ast_value*)arg[0];
1534 ast_value *b = (ast_value*)arg[1];
1536 if (!strcmp(intrin, "isfinite")) ret = fold_intrin_isfinite(fold, a);
1537 if (!strcmp(intrin, "isinf")) ret = fold_intrin_isinf(fold, a);
1538 if (!strcmp(intrin, "isnan")) ret = fold_intrin_isnan(fold, a);
1539 if (!strcmp(intrin, "isnormal")) ret = fold_intrin_isnormal(fold, a);
1540 if (!strcmp(intrin, "signbit")) ret = fold_intrin_signbit(fold, a);
1541 if (!strcmp(intrin, "acosh")) ret = fold_intirn_acosh(fold, a);
1542 if (!strcmp(intrin, "asinh")) ret = fold_intrin_asinh(fold, a);
1543 if (!strcmp(intrin, "atanh")) ret = fold_intrin_atanh(fold, a);
1544 if (!strcmp(intrin, "exp")) ret = fold_intrin_exp(fold, a);
1545 if (!strcmp(intrin, "exp2")) ret = fold_intrin_exp2(fold, a);
1546 if (!strcmp(intrin, "expm1")) ret = fold_intrin_expm1(fold, a);
1547 if (!strcmp(intrin, "mod")) ret = fold_intrin_mod(fold, a, b);
1548 if (!strcmp(intrin, "pow")) ret = fold_intrin_pow(fold, a, b);
1549 if (!strcmp(intrin, "fabs")) ret = fold_intrin_fabs(fold, a);
1552 ++opts_optimizationcount[OPTIM_CONST_FOLD];
1558 * These are all the actual constant folding methods that happen in between
1559 * the AST/IR stage of the compiler , i.e eliminating branches for const
1560 * expressions, which is the only supported thing so far. We undefine the
1561 * testing macros here because an ir_value is differant than an ast_value.
1567 #undef fold_immvalue_float
1568 #undef fold_immvalue_string
1569 #undef fold_immvalue_vector
1573 #define isfloat(X) ((X)->vtype == TYPE_FLOAT)
1574 /*#define isstring(X) ((X)->vtype == TYPE_STRING)*/
1575 /*#define isvector(X) ((X)->vtype == TYPE_VECTOR)*/
1576 #define fold_immvalue_float(X) ((X)->constval.vfloat)
1577 #define fold_immvalue_vector(X) ((X)->constval.vvec)
1578 /*#define fold_immvalue_string(X) ((X)->constval.vstring)*/
1579 #define fold_can_1(X) ((X)->hasvalue && (X)->cvq == CV_CONST)
1580 /*#define fold_can_2(X,Y) (fold_can_1(X) && fold_can_1(Y))*/
1582 static ast_expression *fold_superfluous(ast_expression *left, ast_expression *right, int op) {
1583 ast_expression *swapped = NULL; /* using this as bool */
1586 if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right))) {
1592 if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right)))
1600 if (fold_immvalue_float(load) == 1.0f) {
1601 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1612 if (fold_immvalue_float(load) == 0.0f) {
1613 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1620 if (vec3_cmp(fold_immvalue_vector(load), vec3_create(1, 1, 1))) {
1621 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1631 if (vec3_cmp(fold_immvalue_vector(load), vec3_create(0, 0, 0))) {
1632 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1642 ast_expression *fold_binary(lex_ctx_t ctx, int op, ast_expression *left, ast_expression *right) {
1643 ast_expression *ret = fold_superfluous(left, right, op);
1646 return (ast_expression*)ast_binary_new(ctx, op, left, right);
1649 static GMQCC_INLINE int fold_cond(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1650 if (isfloat(condval) && fold_can_1(condval) && OPTS_OPTIMIZATION(OPTIM_CONST_FOLD_DCE)) {
1651 ast_expression_codegen *cgen;
1654 bool istrue = (fold_immvalue_float(condval) != 0.0f && branch->on_true);
1655 bool isfalse = (fold_immvalue_float(condval) == 0.0f && branch->on_false);
1656 ast_expression *path = (istrue) ? branch->on_true :
1657 (isfalse) ? branch->on_false : NULL;
1660 * no path to take implies that the evaluation is if(0) and there
1661 * is no else block. so eliminate all the code.
1663 ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1667 if (!(elide = ir_function_create_block(ast_ctx(branch), func->ir_func, ast_function_label(func, ((istrue) ? "ontrue" : "onfalse")))))
1669 if (!(*(cgen = path->codegen))((ast_expression*)path, func, false, &dummy))
1671 if (!ir_block_create_jump(func->curblock, ast_ctx(branch), elide))
1674 * now the branch has been eliminated and the correct block for the constant evaluation
1675 * is expanded into the current block for the function.
1677 func->curblock = elide;
1678 ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1681 return -1; /* nothing done */
1684 int fold_cond_ternary(ir_value *condval, ast_function *func, ast_ternary *branch) {
1685 return fold_cond(condval, func, (ast_ifthen*)branch);
1688 int fold_cond_ifthen(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1689 return fold_cond(condval, func, branch);