10 #define FOLD_STRING_UNTRANSLATE_HTSIZE 1024
11 #define FOLD_STRING_DOTRANSLATE_HTSIZE 1024
13 /* The options to use for inexact and arithmetic exceptions */
14 #define FOLD_ROUNDING SFLOAT_ROUND_NEAREST_EVEN
15 #define FOLD_TINYNESS SFLOAT_TBEFORE
18 * Comparing float values is an unsafe operation when the operands to the
19 * comparison are floating point values that are inexact. For instance 1/3 is an
20 * inexact value. The FPU is meant to raise exceptions when these sorts of things
21 * happen, including division by zero, underflows and overflows. The C standard
22 * library provides us with the <fenv.h> header to gain access to the floating-
23 * point environment and lets us set the rounding mode and check for these exceptions.
24 * The problem is the standard C library allows an implementation to leave these
25 * stubbed out and does not require they be implemented. Furthermore, depending
26 * on implementations there is no control over the FPU. This is an IEE 754
27 * conforming implementation in software to compensate.
29 typedef uint32_t sfloat_t;
37 enum sfloat_exceptionflags_t {
42 SFLOAT_UNDERFLOW = 16,
47 enum sfloat_roundingmode_t {
48 SFLOAT_ROUND_NEAREST_EVEN,
54 /* Underflow tininess-detection mode */
55 enum sfloat_tdetect_t {
60 struct sfloat_state_t {
61 sfloat_roundingmode_t roundingmode;
62 sfloat_exceptionflags_t exceptionflags;
63 sfloat_tdetect_t tiny;
66 /* Counts the number of leading zero bits before the most-significand one bit. */
68 /* MSVC has an intrinsic for this */
69 static GMQCC_INLINE uint32_t sfloat_clz(uint32_t x) {
71 _BitScanForward(&r, x);
74 # define SFLOAT_CLZ(X, SUB) \
75 (sfloat_clz((X)) - (SUB))
76 #elif defined(__GNUC__) || defined(__CLANG__)
77 /* Clang and GCC have a builtin for this */
78 # define SFLOAT_CLZ(X, SUB) \
79 (__builtin_clz((X)) - (SUB))
82 static GMQCC_INLINE uint32_t sfloat_popcnt(uint32_t x) {
83 x -= ((x >> 1) & 0x55555555);
84 x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
85 x = (((x >> 4) + x) & 0x0F0F0F0F);
88 return x & 0x0000003F;
90 static GMQCC_INLINE uint32_t sfloat_clz(uint32_t x) {
96 return 32 - sfloat_popcnt(x);
98 # define SFLOAT_CLZ(X, SUB) \
99 (sfloat_clz((X) - (SUB)))
102 /* The value of a NaN */
103 #define SFLOAT_NAN 0xFFFFFFFF
105 #define SFLOAT_ISNAN(A) \
106 (0xFF000000 < (uint32_t)((A) << 1))
107 /* Test if signaling NaN */
108 #define SFLOAT_ISSNAN(A) \
109 (((((A) >> 22) & 0x1FF) == 0x1FE) && ((A) & 0x003FFFFF))
110 /* Raise exception */
111 #define SFLOAT_RAISE(STATE, FLAGS) \
112 ((STATE)->exceptionflags = (sfloat_exceptionflags_t)((STATE)->exceptionflags | (FLAGS)))
114 * Shifts `A' right by the number of bits given in `COUNT'. If any non-zero bits
115 * are shifted off they are forced into the least significand bit of the result
116 * by setting it to one. As a result of this, the value of `COUNT' can be
117 * arbitrarily large; if `COUNT' is greater than 32, the result will be either
118 * zero or one, depending on whether `A' is a zero or non-zero. The result is
119 * stored into the value pointed by `Z'.
121 #define SFLOAT_SHIFT(SIZE, A, COUNT, Z) \
122 *(Z) = ((COUNT) == 0) \
124 : (((COUNT) < (SIZE)) \
125 ? ((A) >> (COUNT)) | (((A) << ((-(COUNT)) & ((SIZE) - 1))) != 0) \
128 /* Extract fractional component */
129 #define SFLOAT_EXTRACT_FRAC(X) \
130 ((uint32_t)((X) & 0x007FFFFF))
131 /* Extract exponent component */
132 #define SFLOAT_EXTRACT_EXP(X) \
133 ((int16_t)((X) >> 23) & 0xFF)
134 /* Extract sign bit */
135 #define SFLOAT_EXTRACT_SIGN(X) \
138 * Normalizes the subnormal value represented by the denormalized significand
139 * `SA'. The normalized exponent and significand are stored at the locations
140 * pointed by `Z' and `SZ' respectively.
142 #define SFLOAT_SUBNORMALIZE(SA, Z, SZ) \
143 (void)(*(SZ) = (SA) << SFLOAT_CLZ((SA), 8), *(Z) = 1 - SFLOAT_CLZ((SA), 8))
145 * Packs the sign `SIGN', exponent `EXP' and significand `SIG' into the value
148 * After the shifting into their proper positions, the fields are added together
149 * to form the result. This means any integer portion of `SIG' will be added
150 * to the exponent. Similarly, because a properly normalized significand will
151 * always have an integer portion equal to one, the exponent input `EXP' should
152 * be one less than the desired result exponent whenever the significant input
153 * `SIG' is a complete, normalized significand.
155 #define SFLOAT_PACK(SIGN, EXP, SIG) \
156 (sfloat_t)((((uint32_t)(SIGN)) << 31) + (((uint32_t)(EXP)) << 23) + (SIG))
159 * Takes two values `a' and `b', one of which is a NaN, and returns the appropriate
160 * NaN result. If either `a' or `b' is a signaling NaN than an invalid exception is
163 static sfloat_t sfloat_propagate_nan(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
164 bool isnan_a = SFLOAT_ISNAN(a);
165 bool issnan_a = SFLOAT_ISSNAN(a);
166 bool isnan_b = SFLOAT_ISNAN(b);
167 bool issnan_b = SFLOAT_ISSNAN(b);
172 if (issnan_a | issnan_b)
173 SFLOAT_RAISE(state, SFLOAT_INVALID);
175 return (issnan_a & isnan_b) ? b : a;
180 * Takes an abstract value having sign `sign_z', exponent `exp_z', and significand
181 * `sig_z' and returns the appropriate value corresponding to the abstract input.
183 * The abstract value is simply rounded and packed into the format. If the abstract
184 * input cannot be represented exactly an inexact exception is raised. If the
185 * abstract input is too large, the overflow and inexact exceptions are both raised
186 * and an infinity or maximal finite value is returned. If the abstract value is
187 * too small, the value is rounded to a subnormal and the underflow and inexact
188 * exceptions are only raised if the value cannot be represented exactly with
191 * The input significand `sig_z' has it's binary point between bits 30 and 29,
192 * this is seven bits to the left of its usual location. The shifted significand
193 * must be normalized or smaller than this. If it's not normalized then the exponent
194 * `exp_z' must be zero; in that case, the result returned is a subnormal number
195 * which must not require rounding. In the more usual case where the significand
196 * is normalized, the exponent must be one less than the *true* exponent.
198 * The handling of underflow and overflow is otherwise in alignment with IEC/IEEE.
200 static sfloat_t SFLOAT_PACK_round(sfloat_state_t *state, bool sign_z, int16_t exp_z, uint32_t sig_z) {
201 sfloat_roundingmode_t mode = state->roundingmode;
202 bool even = !!(mode == SFLOAT_ROUND_NEAREST_EVEN);
203 unsigned char increment = 0x40;
204 unsigned char bits = sig_z & 0x7F;
207 if (mode == SFLOAT_ROUND_TO_ZERO)
212 if (mode == SFLOAT_ROUND_UP)
215 if (mode == SFLOAT_ROUND_DOWN)
221 if (0xFD <= (uint16_t)exp_z) {
222 if ((0xFD < exp_z) || ((exp_z == 0xFD) && ((int32_t)(sig_z + increment) < 0))) {
223 SFLOAT_RAISE(state, SFLOAT_OVERFLOW | SFLOAT_INEXACT);
224 return SFLOAT_PACK(sign_z, 0xFF, 0) - (increment == 0);
227 /* Check for underflow */
228 bool tiny = (state->tiny == SFLOAT_TBEFORE) || (exp_z < -1) || (sig_z + increment < 0x80000000);
229 SFLOAT_SHIFT(32, sig_z, -exp_z, &sig_z);
233 SFLOAT_RAISE(state, SFLOAT_UNDERFLOW);
237 SFLOAT_RAISE(state, SFLOAT_INEXACT);
238 sig_z = (sig_z + increment) >> 7;
239 sig_z &= ~(((bits ^ 0x40) == 0) & even);
242 return SFLOAT_PACK(sign_z, exp_z, sig_z);
246 * Takes an abstract value having sign `sign_z', exponent `exp_z' and significand
247 * `sig_z' and returns the appropriate value corresponding to the abstract input.
248 * This function is exactly like `PACK_round' except the significand does not have
251 * Bit 31 of the significand must be zero and the exponent must be one less than
252 * the *true* exponent.
254 static sfloat_t SFLOAT_PACK_normal(sfloat_state_t *state, bool sign_z, int16_t exp_z, uint32_t sig_z) {
255 unsigned char c = SFLOAT_CLZ(sig_z, 1);
256 return SFLOAT_PACK_round(state, sign_z, exp_z - c, sig_z << c);
260 * Returns the result of adding the absolute values of `a' and `b'. The sign
261 * `sign_z' is ignored if the result is a NaN.
263 static sfloat_t sfloat_add_impl(sfloat_state_t *state, sfloat_t a, sfloat_t b, bool sign_z) {
264 int16_t exp_a = SFLOAT_EXTRACT_EXP(a);
265 int16_t exp_b = SFLOAT_EXTRACT_EXP(b);
267 int16_t exp_d = exp_a - exp_b;
268 uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a) << 6;
269 uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b) << 6;
274 return sig_a ? sfloat_propagate_nan(state, a, b) : a;
279 SFLOAT_SHIFT(32, sig_b, exp_d, &sig_b);
281 } else if (exp_d < 0) {
283 return sig_b ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z, 0xFF, 0);
288 SFLOAT_SHIFT(32, sig_a, -exp_d, &sig_a);
292 return (sig_a | sig_b) ? sfloat_propagate_nan(state, a, b) : a;
294 return SFLOAT_PACK(sign_z, 0, (sig_a + sig_b) >> 6);
295 sig_z = 0x40000000 + sig_a + sig_b;
300 sig_z = (sig_a + sig_b) << 1;
302 if ((int32_t)sig_z < 0) {
303 sig_z = sig_a + sig_b;
307 return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
311 * Returns the result of subtracting the absolute values of `a' and `b'. If the
312 * sign `sign_z' is one, the difference is negated before being returned. The
313 * sign is ignored if the result is a NaN.
315 static sfloat_t sfloat_sub_impl(sfloat_state_t *state, sfloat_t a, sfloat_t b, bool sign_z) {
316 int16_t exp_a = SFLOAT_EXTRACT_EXP(a);
317 int16_t exp_b = SFLOAT_EXTRACT_EXP(b);
319 int16_t exp_d = exp_a - exp_b;
320 uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a) << 7;
321 uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b) << 7;
324 if (0 < exp_d) goto exp_greater_a;
325 if (exp_d < 0) goto exp_greater_b;
329 return sfloat_propagate_nan(state, a, b);
330 SFLOAT_RAISE(state, SFLOAT_INVALID);
337 if (sig_b < sig_a) goto greater_a;
338 if (sig_a < sig_b) goto greater_b;
340 return SFLOAT_PACK(state->roundingmode == SFLOAT_ROUND_DOWN, 0, 0);
344 return (sig_b) ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z ^ 1, 0xFF, 0);
349 SFLOAT_SHIFT(32, sig_a, -exp_d, &sig_a);
352 sig_z = sig_b - sig_a;
359 return (sig_a) ? sfloat_propagate_nan(state, a, b) : a;
364 SFLOAT_SHIFT(32, sig_b, exp_d, &sig_b);
367 sig_z = sig_a - sig_b;
372 return SFLOAT_PACK_normal(state, sign_z, exp_z, sig_z);
375 static GMQCC_INLINE sfloat_t sfloat_add(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
376 bool sign_a = SFLOAT_EXTRACT_SIGN(a);
377 bool sign_b = SFLOAT_EXTRACT_SIGN(b);
378 return (sign_a == sign_b) ? sfloat_add_impl(state, a, b, sign_a)
379 : sfloat_sub_impl(state, a, b, sign_a);
382 static GMQCC_INLINE sfloat_t sfloat_sub(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
383 bool sign_a = SFLOAT_EXTRACT_SIGN(a);
384 bool sign_b = SFLOAT_EXTRACT_SIGN(b);
385 return (sign_a == sign_b) ? sfloat_sub_impl(state, a, b, sign_a)
386 : sfloat_add_impl(state, a, b, sign_a);
389 static sfloat_t sfloat_mul(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
390 int16_t exp_a = SFLOAT_EXTRACT_EXP(a);
391 int16_t exp_b = SFLOAT_EXTRACT_EXP(b);
393 uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a);
394 uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b);
396 uint64_t sig_z64 = 0;
397 bool sign_a = SFLOAT_EXTRACT_SIGN(a);
398 bool sign_b = SFLOAT_EXTRACT_SIGN(b);
399 bool sign_z = sign_a ^ sign_b;
402 if (sig_a || ((exp_b == 0xFF) && sig_b))
403 return sfloat_propagate_nan(state, a, b);
404 if ((exp_b | sig_b) == 0) {
405 SFLOAT_RAISE(state, SFLOAT_INVALID);
408 return SFLOAT_PACK(sign_z, 0xFF, 0);
412 return sfloat_propagate_nan(state, a, b);
413 if ((exp_a | sig_a) == 0) {
414 SFLOAT_RAISE(state, SFLOAT_INVALID);
417 return SFLOAT_PACK(sign_z, 0xFF, 0);
421 return SFLOAT_PACK(sign_z, 0, 0);
422 SFLOAT_SUBNORMALIZE(sig_a, &exp_a, &sig_a);
426 return SFLOAT_PACK(sign_z, 0, 0);
427 SFLOAT_SUBNORMALIZE(sig_b, &exp_b, &sig_b);
429 exp_z = exp_a + exp_b - 0x7F;
430 sig_a = (sig_a | 0x00800000) << 7;
431 sig_b = (sig_b | 0x00800000) << 8;
432 SFLOAT_SHIFT(64, ((uint64_t)sig_a) * sig_b, 32, &sig_z64);
434 if (0 <= (int32_t)(sig_z << 1)) {
438 return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
441 static sfloat_t sfloat_div(sfloat_state_t *state, sfloat_t a, sfloat_t b) {
442 int16_t exp_a = SFLOAT_EXTRACT_EXP(a);
443 int16_t exp_b = SFLOAT_EXTRACT_EXP(b);
445 uint32_t sig_a = SFLOAT_EXTRACT_FRAC(a);
446 uint32_t sig_b = SFLOAT_EXTRACT_FRAC(b);
448 bool sign_a = SFLOAT_EXTRACT_SIGN(a);
449 bool sign_b = SFLOAT_EXTRACT_SIGN(b);
450 bool sign_z = sign_a ^ sign_b;
454 return sfloat_propagate_nan(state, a, b);
457 return sfloat_propagate_nan(state, a, b);
458 SFLOAT_RAISE(state, SFLOAT_INVALID);
461 return SFLOAT_PACK(sign_z, 0xFF, 0);
464 return (sig_b) ? sfloat_propagate_nan(state, a, b) : SFLOAT_PACK(sign_z, 0, 0);
467 if ((exp_a | sig_a) == 0) {
468 SFLOAT_RAISE(state, SFLOAT_INVALID);
471 SFLOAT_RAISE(state, SFLOAT_DIVBYZERO);
472 return SFLOAT_PACK(sign_z, 0xFF, 0);
474 SFLOAT_SUBNORMALIZE(sig_b, &exp_b, &sig_b);
478 return SFLOAT_PACK(sign_z, 0, 0);
479 SFLOAT_SUBNORMALIZE(sig_a, &exp_a, &sig_a);
481 exp_z = exp_a - exp_b + 0x7D;
482 sig_a = (sig_a | 0x00800000) << 7;
483 sig_b = (sig_b | 0x00800000) << 8;
484 if (sig_b <= (sig_a + sig_a)) {
488 sig_z = (((uint64_t)sig_a) << 32) / sig_b;
489 if ((sig_z & 0x3F) == 0)
490 sig_z |= ((uint64_t)sig_b * sig_z != ((uint64_t)sig_a) << 32);
491 return SFLOAT_PACK_round(state, sign_z, exp_z, sig_z);
494 static sfloat_t sfloat_neg(sfloat_state_t *state, sfloat_t a) {
497 return sfloat_mul(state, a, neg.s);
500 static GMQCC_INLINE void sfloat_check(lex_ctx_t ctx, sfloat_state_t *state, const char *vec) {
501 /* Exception comes from vector component */
503 if (state->exceptionflags & SFLOAT_DIVBYZERO)
504 compile_error(ctx, "division by zero in `%s' component", vec);
505 if (state->exceptionflags & SFLOAT_INVALID)
506 compile_error(ctx, "undefined (inf) in `%s' component", vec);
507 if (state->exceptionflags & SFLOAT_OVERFLOW)
508 compile_error(ctx, "arithmetic overflow in `%s' component", vec);
509 if (state->exceptionflags & SFLOAT_UNDERFLOW)
510 compile_error(ctx, "arithmetic underflow in `%s' component", vec);
513 if (state->exceptionflags & SFLOAT_DIVBYZERO)
514 compile_error(ctx, "division by zero");
515 if (state->exceptionflags & SFLOAT_INVALID)
516 compile_error(ctx, "undefined (inf)");
517 if (state->exceptionflags & SFLOAT_OVERFLOW)
518 compile_error(ctx, "arithmetic overflow");
519 if (state->exceptionflags & SFLOAT_UNDERFLOW)
520 compile_error(ctx, "arithmetic underflow");
523 static GMQCC_INLINE void sfloat_init(sfloat_state_t *state) {
524 state->exceptionflags = SFLOAT_NOEXCEPT;
525 state->roundingmode = FOLD_ROUNDING;
526 state->tiny = FOLD_TINYNESS;
530 * There is two stages to constant folding in GMQCC: there is the parse
531 * stage constant folding, where, with the help of the AST, operator
532 * usages can be constant folded. Then there is the constant folding
533 * in the IR for things like eliding if statements, can occur.
535 * This file is thus, split into two parts.
538 #define isfloat(X) (((ast_expression*)(X))->m_vtype == TYPE_FLOAT)
539 #define isvector(X) (((ast_expression*)(X))->m_vtype == TYPE_VECTOR)
540 #define isstring(X) (((ast_expression*)(X))->m_vtype == TYPE_STRING)
541 #define isarray(X) (((ast_expression*)(X))->m_vtype == TYPE_ARRAY)
542 #define isfloats(X,Y) (isfloat (X) && isfloat (Y))
545 * Implementation of basic vector math for vec3_t, for trivial constant
548 * TODO: gcc/clang hinting for autovectorization
562 struct vec3_soft_state_t {
564 sfloat_state_t state[3];
567 static GMQCC_INLINE vec3_soft_t vec3_soft_convert(vec3_t vec) {
575 static GMQCC_INLINE bool vec3_soft_exception(vec3_soft_state_t *vstate, size_t index) {
576 sfloat_exceptionflags_t flags = vstate->state[index].exceptionflags;
577 if (flags & SFLOAT_DIVBYZERO) return true;
578 if (flags & SFLOAT_INVALID) return true;
579 if (flags & SFLOAT_OVERFLOW) return true;
580 if (flags & SFLOAT_UNDERFLOW) return true;
584 static GMQCC_INLINE void vec3_soft_eval(vec3_soft_state_t *state,
585 sfloat_t (*callback)(sfloat_state_t *, sfloat_t, sfloat_t),
589 vec3_soft_t sa = vec3_soft_convert(a);
590 vec3_soft_t sb = vec3_soft_convert(b);
591 callback(&state->state[0], sa.x.s, sb.x.s);
592 if (vec3_soft_exception(state, 0)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_X);
593 callback(&state->state[1], sa.y.s, sb.y.s);
594 if (vec3_soft_exception(state, 1)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_Y);
595 callback(&state->state[2], sa.z.s, sb.z.s);
596 if (vec3_soft_exception(state, 2)) state->faults = (vec3_comp_t)(state->faults | VEC_COMP_Z);
599 static GMQCC_INLINE void vec3_check_except(vec3_t a,
602 sfloat_t (*callback)(sfloat_state_t *, sfloat_t, sfloat_t))
604 vec3_soft_state_t state;
606 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
609 sfloat_init(&state.state[0]);
610 sfloat_init(&state.state[1]);
611 sfloat_init(&state.state[2]);
613 vec3_soft_eval(&state, callback, a, b);
614 if (state.faults & VEC_COMP_X) sfloat_check(ctx, &state.state[0], "x");
615 if (state.faults & VEC_COMP_Y) sfloat_check(ctx, &state.state[1], "y");
616 if (state.faults & VEC_COMP_Z) sfloat_check(ctx, &state.state[2], "z");
619 static GMQCC_INLINE vec3_t vec3_add(lex_ctx_t ctx, vec3_t a, vec3_t b) {
621 vec3_check_except(a, b, ctx, &sfloat_add);
628 static GMQCC_INLINE vec3_t vec3_sub(lex_ctx_t ctx, vec3_t a, vec3_t b) {
630 vec3_check_except(a, b, ctx, &sfloat_sub);
637 static GMQCC_INLINE vec3_t vec3_neg(lex_ctx_t ctx, vec3_t a) {
642 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
653 sfloat_neg(&s[0], v[0].s);
654 sfloat_neg(&s[1], v[1].s);
655 sfloat_neg(&s[2], v[2].s);
657 sfloat_check(ctx, &s[0], nullptr);
658 sfloat_check(ctx, &s[1], nullptr);
659 sfloat_check(ctx, &s[2], nullptr);
668 static GMQCC_INLINE vec3_t vec3_or(vec3_t a, vec3_t b) {
670 out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b.x));
671 out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b.y));
672 out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b.z));
676 static GMQCC_INLINE vec3_t vec3_orvf(vec3_t a, qcfloat_t b) {
678 out.x = (qcfloat_t)(((qcint_t)a.x) | ((qcint_t)b));
679 out.y = (qcfloat_t)(((qcint_t)a.y) | ((qcint_t)b));
680 out.z = (qcfloat_t)(((qcint_t)a.z) | ((qcint_t)b));
684 static GMQCC_INLINE vec3_t vec3_and(vec3_t a, vec3_t b) {
686 out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b.x));
687 out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b.y));
688 out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b.z));
692 static GMQCC_INLINE vec3_t vec3_andvf(vec3_t a, qcfloat_t b) {
694 out.x = (qcfloat_t)(((qcint_t)a.x) & ((qcint_t)b));
695 out.y = (qcfloat_t)(((qcint_t)a.y) & ((qcint_t)b));
696 out.z = (qcfloat_t)(((qcint_t)a.z) & ((qcint_t)b));
700 static GMQCC_INLINE vec3_t vec3_xor(vec3_t a, vec3_t b) {
702 out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b.x));
703 out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b.y));
704 out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b.z));
708 static GMQCC_INLINE vec3_t vec3_xorvf(vec3_t a, qcfloat_t b) {
710 out.x = (qcfloat_t)(((qcint_t)a.x) ^ ((qcint_t)b));
711 out.y = (qcfloat_t)(((qcint_t)a.y) ^ ((qcint_t)b));
712 out.z = (qcfloat_t)(((qcint_t)a.z) ^ ((qcint_t)b));
716 static GMQCC_INLINE vec3_t vec3_not(vec3_t a) {
724 static GMQCC_INLINE qcfloat_t vec3_mulvv(lex_ctx_t ctx, vec3_t a, vec3_t b) {
730 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
733 sa = vec3_soft_convert(a);
734 sb = vec3_soft_convert(b);
742 r[0] = sfloat_mul(&s[0], sa.x.s, sb.x.s);
743 r[1] = sfloat_mul(&s[1], sa.y.s, sb.y.s);
744 r[2] = sfloat_mul(&s[2], sa.z.s, sb.z.s);
745 r[3] = sfloat_add(&s[3], r[0], r[1]);
746 r[4] = sfloat_add(&s[4], r[3], r[2]);
748 sfloat_check(ctx, &s[0], nullptr);
749 sfloat_check(ctx, &s[1], nullptr);
750 sfloat_check(ctx, &s[2], nullptr);
751 sfloat_check(ctx, &s[3], nullptr);
752 sfloat_check(ctx, &s[4], nullptr);
755 return (a.x * b.x + a.y * b.y + a.z * b.z);
758 static GMQCC_INLINE vec3_t vec3_mulvf(lex_ctx_t ctx, vec3_t a, qcfloat_t b) {
764 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
767 sa = vec3_soft_convert(a);
773 sfloat_mul(&s[0], sa.x.s, sb.s);
774 sfloat_mul(&s[1], sa.y.s, sb.s);
775 sfloat_mul(&s[2], sa.z.s, sb.s);
777 sfloat_check(ctx, &s[0], "x");
778 sfloat_check(ctx, &s[1], "y");
779 sfloat_check(ctx, &s[2], "z");
788 static GMQCC_INLINE bool vec3_cmp(vec3_t a, vec3_t b) {
794 static GMQCC_INLINE vec3_t vec3_create(float x, float y, float z) {
802 static GMQCC_INLINE qcfloat_t vec3_notf(vec3_t a) {
803 return (!a.x && !a.y && !a.z);
806 static GMQCC_INLINE bool vec3_pbool(vec3_t a) {
807 return (a.x || a.y || a.z);
810 static GMQCC_INLINE vec3_t vec3_cross(lex_ctx_t ctx, vec3_t a, vec3_t b) {
817 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
820 sa = vec3_soft_convert(a);
821 sb = vec3_soft_convert(b);
833 r[0] = sfloat_mul(&s[0], sa.y.s, sb.z.s);
834 r[1] = sfloat_mul(&s[1], sa.z.s, sb.y.s);
835 r[2] = sfloat_mul(&s[2], sa.z.s, sb.x.s);
836 r[3] = sfloat_mul(&s[3], sa.x.s, sb.z.s);
837 r[4] = sfloat_mul(&s[4], sa.x.s, sb.y.s);
838 r[5] = sfloat_mul(&s[5], sa.y.s, sb.x.s);
839 r[6] = sfloat_sub(&s[6], r[0], r[1]);
840 r[7] = sfloat_sub(&s[7], r[2], r[3]);
841 r[8] = sfloat_sub(&s[8], r[4], r[5]);
843 sfloat_check(ctx, &s[0], nullptr);
844 sfloat_check(ctx, &s[1], nullptr);
845 sfloat_check(ctx, &s[2], nullptr);
846 sfloat_check(ctx, &s[3], nullptr);
847 sfloat_check(ctx, &s[4], nullptr);
848 sfloat_check(ctx, &s[5], nullptr);
849 sfloat_check(ctx, &s[6], "x");
850 sfloat_check(ctx, &s[7], "y");
851 sfloat_check(ctx, &s[8], "z");
854 out.x = a.y * b.z - a.z * b.y;
855 out.y = a.z * b.x - a.x * b.z;
856 out.z = a.x * b.y - a.y * b.x;
860 qcfloat_t fold::immvalue_float(ast_value *value) {
861 return value->m_constval.vfloat;
864 vec3_t fold::immvalue_vector(ast_value *value) {
865 return value->m_constval.vvec;
868 const char *fold::immvalue_string(ast_value *value) {
869 return value->m_constval.vstring;
872 lex_ctx_t fold::ctx() {
875 return parser_ctx(m_parser);
876 memset(&ctx, 0, sizeof(ctx));
880 bool fold::immediate_true(ast_value *v) {
881 switch (v->m_vtype) {
883 return !!v->m_constval.vfloat;
885 return !!v->m_constval.vint;
887 if (OPTS_FLAG(CORRECT_LOGIC))
888 return vec3_pbool(v->m_constval.vvec);
889 return !!(v->m_constval.vvec.x);
891 if (!v->m_constval.vstring)
893 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
895 return !!v->m_constval.vstring[0];
897 compile_error(ctx(), "internal error: fold_immediate_true on invalid type");
900 return !!v->m_constval.vfunc;
903 /* Handy macros to determine if an ast_value can be constant folded. */
904 #define fold_can_1(X) \
905 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->m_hasvalue && ((X)->m_cvq == CV_CONST) && \
906 ((ast_expression*)(X))->m_vtype != TYPE_FUNCTION)
908 #define fold_can_2(X, Y) (fold_can_1(X) && fold_can_1(Y))
915 fold::fold(parser_t *parser)
918 m_imm_string_untranslate = util_htnew(FOLD_STRING_UNTRANSLATE_HTSIZE);
919 m_imm_string_dotranslate = util_htnew(FOLD_STRING_DOTRANSLATE_HTSIZE);
921 constgen_float(0.0f, false);
922 constgen_float(1.0f, false);
923 constgen_float(-1.0f, false);
924 constgen_float(2.0f, false);
926 constgen_vector(vec3_create(0.0f, 0.0f, 0.0f));
927 constgen_vector(vec3_create(-1.0f, -1.0f, -1.0f));
930 bool fold::generate(ir_builder *ir) {
931 // generate globals for immediate folded values
933 for (auto &it : m_imm_float)
934 if (!ast_global_codegen((cur = it), ir, false)) goto err;
935 for (auto &it : m_imm_vector)
936 if (!ast_global_codegen((cur = it), ir, false)) goto err;
937 for (auto &it : m_imm_string)
938 if (!ast_global_codegen((cur = it), ir, false)) goto err;
941 con_out("failed to generate global %s\n", cur->m_name);
947 // TODO: parser lifetime so this is called when it should be
949 for (auto &it : m_imm_float) ast_delete(it);
950 for (auto &it : m_imm_vector) ast_delete(it);
951 for (auto &it : m_imm_string) ast_delete(it);
953 util_htdel(m_imm_string_untranslate);
954 util_htdel(m_imm_string_dotranslate);
958 ast_expression *fold::constgen_float(qcfloat_t value, bool inexact) {
959 for (auto &it : m_imm_float)
960 if (!memcmp(&it->m_constval.vfloat, &value, sizeof(qcfloat_t)))
961 return (ast_expression*)it;
963 ast_value *out = ast_value_new(ctx(), "#IMMEDIATE", TYPE_FLOAT);
964 out->m_cvq = CV_CONST;
965 out->m_hasvalue = true;
966 out->m_inexact = inexact;
967 out->m_constval.vfloat = value;
969 m_imm_float.push_back(out);
971 return (ast_expression*)out;
974 ast_expression *fold::constgen_vector(vec3_t value) {
975 for (auto &it : m_imm_vector)
976 if (vec3_cmp(it->m_constval.vvec, value))
977 return (ast_expression*)it;
979 ast_value *out = ast_value_new(ctx(), "#IMMEDIATE", TYPE_VECTOR);
980 out->m_cvq = CV_CONST;
981 out->m_hasvalue = true;
982 out->m_constval.vvec = value;
984 m_imm_vector.push_back(out);
986 return (ast_expression*)out;
989 ast_expression *fold::constgen_string(const char *str, bool translate) {
990 hash_table_t *table = translate ? m_imm_string_untranslate : m_imm_string_dotranslate;
991 ast_value *out = nullptr;
992 size_t hash = util_hthash(table, str);
994 if ((out = (ast_value*)util_htgeth(table, str, hash)))
995 return (ast_expression*)out;
999 util_snprintf(name, sizeof(name), "dotranslate_%zu", m_parser->translated++);
1000 out = ast_value_new(ctx(), name, TYPE_STRING);
1001 out->m_flags |= AST_FLAG_INCLUDE_DEF; /* def needs to be included for translatables */
1003 out = ast_value_new(ctx(), "#IMMEDIATE", TYPE_STRING);
1006 out->m_cvq = CV_CONST;
1007 out->m_hasvalue = true;
1008 out->m_isimm = true;
1009 out->m_constval.vstring = parser_strdup(str);
1011 m_imm_string.push_back(out);
1012 util_htseth(table, str, hash, out);
1014 return (ast_expression*)out;
1018 void (*callback)(void);
1019 sfloat_t (*binary)(sfloat_state_t *, sfloat_t, sfloat_t);
1020 sfloat_t (*unary)(sfloat_state_t *, sfloat_t);
1021 } float_check_callback_t;
1023 bool fold::check_except_float_impl(void (*callback)(void), ast_value *a, ast_value *b) {
1024 float_check_callback_t call;
1028 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS) && !OPTS_WARN(WARN_INEXACT_COMPARES))
1031 call.callback = callback;
1033 ca.f = immvalue_float(a);
1036 cb.f = immvalue_float(b);
1037 call.binary(&s, ca.s, cb.s);
1039 call.unary(&s, ca.s);
1042 if (s.exceptionflags == 0)
1045 if (!OPTS_FLAG(ARITHMETIC_EXCEPTIONS))
1046 goto inexact_possible;
1048 sfloat_check(ctx(), &s, nullptr);
1051 return s.exceptionflags & SFLOAT_INEXACT;
1054 #define check_except_float(CALLBACK, A, B) \
1055 check_except_float_impl(((void (*)(void))(CALLBACK)), (A), (B))
1057 bool fold::check_inexact_float(ast_value *a, ast_value *b) {
1058 if (!OPTS_WARN(WARN_INEXACT_COMPARES))
1060 if (!a->m_inexact && !b->m_inexact)
1062 return compile_warning(ctx(), WARN_INEXACT_COMPARES, "inexact value in comparison");
1065 ast_expression *fold::op_mul_vec(vec3_t vec, ast_value *sel, const char *set) {
1066 qcfloat_t x = (&vec.x)[set[0]-'x'];
1067 qcfloat_t y = (&vec.x)[set[1]-'x'];
1068 qcfloat_t z = (&vec.x)[set[2]-'x'];
1070 ast_expression *out;
1071 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
1072 out = (ast_expression*)ast_member_new(ctx(), (ast_expression*)sel, set[0]-'x', nullptr);
1073 out->m_keep_node = false;
1074 ((ast_member*)out)->m_rvalue = true;
1076 return (ast_expression*)ast_binary_new(ctx(), INSTR_MUL_F, constgen_float(x, false), out);
1082 ast_expression *fold::op_neg(ast_value *a) {
1084 if (fold_can_1(a)) {
1085 /* Negation can produce inexact as well */
1086 bool inexact = check_except_float(&sfloat_neg, a, nullptr);
1087 return constgen_float(-immvalue_float(a), inexact);
1089 } else if (isvector(a)) {
1091 return constgen_vector(vec3_neg(ctx(), immvalue_vector(a)));
1096 ast_expression *fold::op_not(ast_value *a) {
1099 return constgen_float(!immvalue_float(a), false);
1100 } else if (isvector(a)) {
1102 return constgen_float(vec3_notf(immvalue_vector(a)), false);
1103 } else if (isstring(a)) {
1104 if (fold_can_1(a)) {
1105 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
1106 return constgen_float(!immvalue_string(a), false);
1108 return constgen_float(!immvalue_string(a) || !*immvalue_string(a), false);
1114 ast_expression *fold::op_add(ast_value *a, ast_value *b) {
1116 if (fold_can_2(a, b)) {
1117 bool inexact = check_except_float(&sfloat_add, a, b);
1118 return constgen_float(immvalue_float(a) + immvalue_float(b), inexact);
1120 } else if (isvector(a)) {
1121 if (fold_can_2(a, b))
1122 return constgen_vector(vec3_add(ctx(),
1124 immvalue_vector(b)));
1129 ast_expression *fold::op_sub(ast_value *a, ast_value *b) {
1131 if (fold_can_2(a, b)) {
1132 bool inexact = check_except_float(&sfloat_sub, a, b);
1133 return constgen_float(immvalue_float(a) - immvalue_float(b), inexact);
1135 } else if (isvector(a)) {
1136 if (fold_can_2(a, b))
1137 return constgen_vector(vec3_sub(ctx(),
1139 immvalue_vector(b)));
1144 ast_expression *fold::op_mul(ast_value *a, ast_value *b) {
1147 if (fold_can_2(a, b))
1148 return constgen_vector(vec3_mulvf(ctx(), immvalue_vector(b), immvalue_float(a)));
1150 if (fold_can_2(a, b)) {
1151 bool inexact = check_except_float(&sfloat_mul, a, b);
1152 return constgen_float(immvalue_float(a) * immvalue_float(b), inexact);
1155 } else if (isvector(a)) {
1157 if (fold_can_2(a, b))
1158 return constgen_vector(vec3_mulvf(ctx(), immvalue_vector(a), immvalue_float(b)));
1160 if (fold_can_2(a, b)) {
1161 return constgen_float(vec3_mulvv(ctx(), immvalue_vector(a), immvalue_vector(b)), false);
1162 } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(a)) {
1163 ast_expression *out;
1164 if ((out = op_mul_vec(immvalue_vector(a), b, "xyz"))) return out;
1165 if ((out = op_mul_vec(immvalue_vector(a), b, "yxz"))) return out;
1166 if ((out = op_mul_vec(immvalue_vector(a), b, "zxy"))) return out;
1167 } else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && fold_can_1(b)) {
1168 ast_expression *out;
1169 if ((out = op_mul_vec(immvalue_vector(b), a, "xyz"))) return out;
1170 if ((out = op_mul_vec(immvalue_vector(b), a, "yxz"))) return out;
1171 if ((out = op_mul_vec(immvalue_vector(b), a, "zxy"))) return out;
1178 ast_expression *fold::op_div(ast_value *a, ast_value *b) {
1180 if (fold_can_2(a, b)) {
1181 bool inexact = check_except_float(&sfloat_div, a, b);
1182 return constgen_float(immvalue_float(a) / immvalue_float(b), inexact);
1183 } else if (fold_can_1(b)) {
1184 return (ast_expression*)ast_binary_new(
1188 constgen_float(1.0f / immvalue_float(b), false)
1191 } else if (isvector(a)) {
1192 if (fold_can_2(a, b)) {
1193 return constgen_vector(vec3_mulvf(ctx(), immvalue_vector(a), 1.0f / immvalue_float(b)));
1195 return (ast_expression*)ast_binary_new(
1200 ? (ast_expression*)constgen_float(1.0f / immvalue_float(b), false)
1201 : (ast_expression*)ast_binary_new(
1204 (ast_expression*)m_imm_float[1],
1213 ast_expression *fold::op_mod(ast_value *a, ast_value *b) {
1214 return (fold_can_2(a, b))
1215 ? constgen_float(fmod(immvalue_float(a), immvalue_float(b)), false)
1219 ast_expression *fold::op_bor(ast_value *a, ast_value *b) {
1221 if (fold_can_2(a, b))
1222 return constgen_float((qcfloat_t)(((qcint_t)immvalue_float(a)) | ((qcint_t)immvalue_float(b))), false);
1225 if (fold_can_2(a, b))
1226 return constgen_vector(vec3_or(immvalue_vector(a), immvalue_vector(b)));
1228 if (fold_can_2(a, b))
1229 return constgen_vector(vec3_orvf(immvalue_vector(a), immvalue_float(b)));
1235 ast_expression *fold::op_band(ast_value *a, ast_value *b) {
1237 if (fold_can_2(a, b))
1238 return constgen_float((qcfloat_t)(((qcint_t)immvalue_float(a)) & ((qcint_t)immvalue_float(b))), false);
1241 if (fold_can_2(a, b))
1242 return constgen_vector(vec3_and(immvalue_vector(a), immvalue_vector(b)));
1244 if (fold_can_2(a, b))
1245 return constgen_vector(vec3_andvf(immvalue_vector(a), immvalue_float(b)));
1251 ast_expression *fold::op_xor(ast_value *a, ast_value *b) {
1253 if (fold_can_2(a, b))
1254 return constgen_float((qcfloat_t)(((qcint_t)immvalue_float(a)) ^ ((qcint_t)immvalue_float(b))), false);
1256 if (fold_can_2(a, b)) {
1258 return constgen_vector(vec3_xor(immvalue_vector(a), immvalue_vector(b)));
1260 return constgen_vector(vec3_xorvf(immvalue_vector(a), immvalue_float(b)));
1266 ast_expression *fold::op_lshift(ast_value *a, ast_value *b) {
1267 if (fold_can_2(a, b) && isfloats(a, b))
1268 return constgen_float((qcfloat_t)floorf(immvalue_float(a) * powf(2.0f, immvalue_float(b))), false);
1272 ast_expression *fold::op_rshift(ast_value *a, ast_value *b) {
1273 if (fold_can_2(a, b) && isfloats(a, b))
1274 return constgen_float((qcfloat_t)floorf(immvalue_float(a) / powf(2.0f, immvalue_float(b))), false);
1278 ast_expression *fold::op_andor(ast_value *a, ast_value *b, float expr) {
1279 if (fold_can_2(a, b)) {
1280 if (OPTS_FLAG(PERL_LOGIC)) {
1282 return immediate_true(a) ? (ast_expression*)a : (ast_expression*)b;
1284 return immediate_true(a) ? (ast_expression*)b : (ast_expression*)a;
1286 return constgen_float(
1287 ((expr) ? (immediate_true(a) || immediate_true(b))
1288 : (immediate_true(a) && immediate_true(b)))
1298 ast_expression *fold::op_tern(ast_value *a, ast_value *b, ast_value *c) {
1299 if (fold_can_1(a)) {
1300 return immediate_true(a)
1301 ? (ast_expression*)b
1302 : (ast_expression*)c;
1307 ast_expression *fold::op_exp(ast_value *a, ast_value *b) {
1308 if (fold_can_2(a, b))
1309 return constgen_float((qcfloat_t)powf(immvalue_float(a), immvalue_float(b)), false);
1313 ast_expression *fold::op_lteqgt(ast_value *a, ast_value *b) {
1314 if (fold_can_2(a,b)) {
1315 check_inexact_float(a, b);
1316 if (immvalue_float(a) < immvalue_float(b)) return (ast_expression*)m_imm_float[2];
1317 if (immvalue_float(a) == immvalue_float(b)) return (ast_expression*)m_imm_float[0];
1318 if (immvalue_float(a) > immvalue_float(b)) return (ast_expression*)m_imm_float[1];
1323 ast_expression *fold::op_ltgt(ast_value *a, ast_value *b, bool lt) {
1324 if (fold_can_2(a, b)) {
1325 check_inexact_float(a, b);
1326 return (lt) ? (ast_expression*)m_imm_float[!!(immvalue_float(a) < immvalue_float(b))]
1327 : (ast_expression*)m_imm_float[!!(immvalue_float(a) > immvalue_float(b))];
1332 ast_expression *fold::op_cmp(ast_value *a, ast_value *b, bool ne) {
1333 if (fold_can_2(a, b)) {
1334 if (isfloat(a) && isfloat(b)) {
1335 float la = immvalue_float(a);
1336 float lb = immvalue_float(b);
1337 check_inexact_float(a, b);
1338 return (ast_expression*)m_imm_float[!(ne ? la == lb : la != lb)];
1339 } if (isvector(a) && isvector(b)) {
1340 vec3_t la = immvalue_vector(a);
1341 vec3_t lb = immvalue_vector(b);
1342 return (ast_expression*)m_imm_float[!(ne ? vec3_cmp(la, lb) : !vec3_cmp(la, lb))];
1348 ast_expression *fold::op_bnot(ast_value *a) {
1351 return constgen_float(-1-immvalue_float(a), false);
1355 return constgen_vector(vec3_not(immvalue_vector(a)));
1361 ast_expression *fold::op_cross(ast_value *a, ast_value *b) {
1362 if (fold_can_2(a, b))
1363 return constgen_vector(vec3_cross(ctx(),
1365 immvalue_vector(b)));
1369 ast_expression *fold::op_length(ast_value *a) {
1370 if (fold_can_1(a) && isstring(a))
1371 return constgen_float(strlen(immvalue_string(a)), false);
1373 return constgen_float(a->m_initlist.size(), false);
1377 ast_expression *fold::op(const oper_info *info, ast_expression **opexprs) {
1378 ast_value *a = (ast_value*)opexprs[0];
1379 ast_value *b = (ast_value*)opexprs[1];
1380 ast_value *c = (ast_value*)opexprs[2];
1381 ast_expression *e = nullptr;
1383 /* can a fold operation be applied to this operator usage? */
1387 switch(info->operands) {
1388 case 3: if(!c) return nullptr;
1389 case 2: if(!b) return nullptr;
1392 compile_error(ctx(), "internal error: fold_op no operands to fold\n");
1397 #define fold_op_case(ARGS, ARGS_OPID, OP, ARGS_FOLD) \
1398 case opid##ARGS ARGS_OPID: \
1399 if ((e = op_##OP ARGS_FOLD)) { \
1400 ++opts_optimizationcount[OPTIM_CONST_FOLD]; \
1405 fold_op_case(2, ('-', 'P'), neg, (a));
1406 fold_op_case(2, ('!', 'P'), not, (a));
1407 fold_op_case(1, ('+'), add, (a, b));
1408 fold_op_case(1, ('-'), sub, (a, b));
1409 fold_op_case(1, ('*'), mul, (a, b));
1410 fold_op_case(1, ('/'), div, (a, b));
1411 fold_op_case(1, ('%'), mod, (a, b));
1412 fold_op_case(1, ('|'), bor, (a, b));
1413 fold_op_case(1, ('&'), band, (a, b));
1414 fold_op_case(1, ('^'), xor, (a, b));
1415 fold_op_case(1, ('<'), ltgt, (a, b, true));
1416 fold_op_case(1, ('>'), ltgt, (a, b, false));
1417 fold_op_case(2, ('<', '<'), lshift, (a, b));
1418 fold_op_case(2, ('>', '>'), rshift, (a, b));
1419 fold_op_case(2, ('|', '|'), andor, (a, b, true));
1420 fold_op_case(2, ('&', '&'), andor, (a, b, false));
1421 fold_op_case(2, ('?', ':'), tern, (a, b, c));
1422 fold_op_case(2, ('*', '*'), exp, (a, b));
1423 fold_op_case(3, ('<','=','>'), lteqgt, (a, b));
1424 fold_op_case(2, ('!', '='), cmp, (a, b, true));
1425 fold_op_case(2, ('=', '='), cmp, (a, b, false));
1426 fold_op_case(2, ('~', 'P'), bnot, (a));
1427 fold_op_case(2, ('>', '<'), cross, (a, b));
1428 fold_op_case(3, ('l', 'e', 'n'), length, (a));
1431 compile_error(ctx(), "internal error: attempted to constant-fold for unsupported operator");
1436 * Constant folding for compiler intrinsics, similar approach to operator
1437 * folding, primarily: individual functions for each intrinsics to fold,
1438 * and a generic selection function.
1440 ast_expression *fold::intrinsic_isfinite(ast_value *a) {
1441 return constgen_float(isfinite(immvalue_float(a)), false);
1443 ast_expression *fold::intrinsic_isinf(ast_value *a) {
1444 return constgen_float(isinf(immvalue_float(a)), false);
1446 ast_expression *fold::intrinsic_isnan(ast_value *a) {
1447 return constgen_float(isnan(immvalue_float(a)), false);
1449 ast_expression *fold::intrinsic_isnormal(ast_value *a) {
1450 return constgen_float(isnormal(immvalue_float(a)), false);
1452 ast_expression *fold::intrinsic_signbit(ast_value *a) {
1453 return constgen_float(signbit(immvalue_float(a)), false);
1455 ast_expression *fold::intrinsic_acosh(ast_value *a) {
1456 return constgen_float(acoshf(immvalue_float(a)), false);
1458 ast_expression *fold::intrinsic_asinh(ast_value *a) {
1459 return constgen_float(asinhf(immvalue_float(a)), false);
1461 ast_expression *fold::intrinsic_atanh(ast_value *a) {
1462 return constgen_float((float)atanh(immvalue_float(a)), false);
1464 ast_expression *fold::intrinsic_exp(ast_value *a) {
1465 return constgen_float(expf(immvalue_float(a)), false);
1467 ast_expression *fold::intrinsic_exp2(ast_value *a) {
1468 return constgen_float(exp2f(immvalue_float(a)), false);
1470 ast_expression *fold::intrinsic_expm1(ast_value *a) {
1471 return constgen_float(expm1f(immvalue_float(a)), false);
1473 ast_expression *fold::intrinsic_mod(ast_value *lhs, ast_value *rhs) {
1474 return constgen_float(fmodf(immvalue_float(lhs), immvalue_float(rhs)), false);
1476 ast_expression *fold::intrinsic_pow(ast_value *lhs, ast_value *rhs) {
1477 return constgen_float(powf(immvalue_float(lhs), immvalue_float(rhs)), false);
1479 ast_expression *fold::intrinsic_fabs(ast_value *a) {
1480 return constgen_float(fabsf(immvalue_float(a)), false);
1483 ast_expression *fold::intrinsic(const char *intrinsic, ast_expression **arg) {
1484 ast_expression *ret = nullptr;
1485 ast_value *a = (ast_value*)arg[0];
1486 ast_value *b = (ast_value*)arg[1];
1488 if (!strcmp(intrinsic, "isfinite")) ret = intrinsic_isfinite(a);
1489 if (!strcmp(intrinsic, "isinf")) ret = intrinsic_isinf(a);
1490 if (!strcmp(intrinsic, "isnan")) ret = intrinsic_isnan(a);
1491 if (!strcmp(intrinsic, "isnormal")) ret = intrinsic_isnormal(a);
1492 if (!strcmp(intrinsic, "signbit")) ret = intrinsic_signbit(a);
1493 if (!strcmp(intrinsic, "acosh")) ret = intrinsic_acosh(a);
1494 if (!strcmp(intrinsic, "asinh")) ret = intrinsic_asinh(a);
1495 if (!strcmp(intrinsic, "atanh")) ret = intrinsic_atanh(a);
1496 if (!strcmp(intrinsic, "exp")) ret = intrinsic_exp(a);
1497 if (!strcmp(intrinsic, "exp2")) ret = intrinsic_exp2(a);
1498 if (!strcmp(intrinsic, "expm1")) ret = intrinsic_expm1(a);
1499 if (!strcmp(intrinsic, "mod")) ret = intrinsic_mod(a, b);
1500 if (!strcmp(intrinsic, "pow")) ret = intrinsic_pow(a, b);
1501 if (!strcmp(intrinsic, "fabs")) ret = intrinsic_fabs(a);
1504 ++opts_optimizationcount[OPTIM_CONST_FOLD];
1510 * These are all the actual constant folding methods that happen in between
1511 * the AST/IR stage of the compiler , i.e eliminating branches for const
1512 * expressions, which is the only supported thing so far. We undefine the
1513 * testing macros here because an ir_value is differant than an ast_value.
1519 #undef fold__immvalue_float
1520 #undef fold__immvalue_string
1521 #undef fold__immvalue_vector
1525 #define isfloat(X) ((X)->m_vtype == TYPE_FLOAT)
1526 /*#define isstring(X) ((X)->m_vtype == TYPE_STRING)*/
1527 /*#define isvector(X) ((X)->m_vtype == TYPE_VECTOR)*/
1528 #define fold_can_1(X) ((X)->m_hasvalue && (X)->m_cvq == CV_CONST)
1529 /*#define fold_can_2(X,Y) (fold_can_1(X) && fold_can_1(Y))*/
1531 qcfloat_t fold::immvalue_float(ir_value *value) {
1532 return value->m_constval.vfloat;
1535 vec3_t fold::immvalue_vector(ir_value *value) {
1536 return value->m_constval.vvec;
1539 ast_expression *fold::superfluous(ast_expression *left, ast_expression *right, int op) {
1540 ast_expression *swapped = nullptr; /* using this as bool */
1543 if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right))) {
1549 if (!ast_istype(right, ast_value) || !fold_can_1((load = (ast_value*)right)))
1557 if (immvalue_float(load) == 1.0f) {
1558 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1569 if (immvalue_float(load) == 0.0f) {
1570 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1577 if (vec3_cmp(immvalue_vector(load), vec3_create(1, 1, 1))) {
1578 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1588 if (vec3_cmp(immvalue_vector(load), vec3_create(0, 0, 0))) {
1589 ++opts_optimizationcount[OPTIM_PEEPHOLE];
1599 ast_expression *fold::binary(lex_ctx_t ctx, int op, ast_expression *left, ast_expression *right) {
1600 ast_expression *ret = superfluous(left, right, op);
1603 return (ast_expression*)ast_binary_new(ctx, op, left, right);
1606 int fold::cond(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1607 if (isfloat(condval) && fold_can_1(condval) && OPTS_OPTIMIZATION(OPTIM_CONST_FOLD_DCE)) {
1608 ast_expression_codegen *cgen;
1611 bool istrue = (immvalue_float(condval) != 0.0f && branch->m_on_true);
1612 bool isfalse = (immvalue_float(condval) == 0.0f && branch->m_on_false);
1613 ast_expression *path = (istrue) ? branch->m_on_true :
1614 (isfalse) ? branch->m_on_false : nullptr;
1617 * no path to take implies that the evaluation is if(0) and there
1618 * is no else block. so eliminate all the code.
1620 ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1624 if (!(elide = ir_function_create_block(branch->m_context, func->m_ir_func, ast_function_label(func, ((istrue) ? "ontrue" : "onfalse")))))
1626 if (!(*(cgen = path->m_codegen))((ast_expression*)path, func, false, &dummy))
1628 if (!ir_block_create_jump(func->m_curblock, branch->m_context, elide))
1631 * now the branch has been eliminated and the correct block for the constant evaluation
1632 * is expanded into the current block for the function.
1634 func->m_curblock = elide;
1635 ++opts_optimizationcount[OPTIM_CONST_FOLD_DCE];
1638 return -1; /* nothing done */
1641 int fold::cond_ternary(ir_value *condval, ast_function *func, ast_ternary *branch) {
1642 return cond(condval, func, (ast_ifthen*)branch);
1645 int fold::cond_ifthen(ir_value *condval, ast_function *func, ast_ifthen *branch) {
1646 return cond(condval, func, branch);