]> git.xonotic.org Git - xonotic/gmqcc.git/blobdiff - fold.c
Implement constant folding on ternary operations via fold_cond.
[xonotic/gmqcc.git] / fold.c
diff --git a/fold.c b/fold.c
index 98e637ae0e62177fe580fbcb180495898d3e3540..d51b7652dcc9b48efdd2bf42c0befe73d6c13503 100644 (file)
--- a/fold.c
+++ b/fold.c
@@ -386,7 +386,7 @@ static GMQCC_INLINE ast_expression *fold_op_mul_vec(fold_t *fold, vec3_t vec, as
         out                        = (ast_expression*)ast_member_new(fold_ctx(fold), (ast_expression*)sel, set[0]-'x', NULL);
         out->node.keep             = false;
         ((ast_member*)out)->rvalue = true;
-        if (x != -1)
+        if (x != -1.0f)
             return (ast_expression*)ast_binary_new(fold_ctx(fold), INSTR_MUL_F, fold_constgen_float(fold, x), out);
     }
     return NULL;
@@ -483,15 +483,20 @@ static GMQCC_INLINE ast_expression *fold_op_div(fold_t *fold, ast_value *a, ast_
                 return fold_constgen_float(fold, fold_immvalue_float(a) / fold_immvalue_float(b));
             else
                 return (ast_expression*)fold->imm_float[3]; /* inf */
+        } else if (fold_can_1(b)) {
+            return (ast_expression*)ast_binary_new(
+                fold_ctx(fold),
+                INSTR_MUL_F,
+                (ast_expression*)a,
+                fold_constgen_float(fold, 1.0f / fold_immvalue_float(b))
+            );
         }
     } else if (isvector(a)) {
         if (fold_can_2(a, b)) {
             if (fold_can_div(b)) {
-                printf("hit wrong logic\n");
                 return fold_constgen_vector(fold, vec3_mulvf(fold_immvalue_vector(a), 1.0f / fold_immvalue_float(b)));
             }
             else {
-                printf("hit logic\n");
                 return (ast_expression*)fold->imm_vector[2]; /* inf */
             }
         } else {
@@ -792,7 +797,7 @@ ast_expression *fold_intrin(fold_t *fold, const char *intrin, ast_expression **a
 /*#define fold_can_2(X,Y)         (fold_can_1(X) && fold_can_1(Y))*/
 
 
-int fold_cond(ir_value *condval, ast_function *func, ast_ifthen *branch) {
+static GMQCC_INLINE int fold_cond(ir_value *condval, ast_function *func, ast_ifthen *branch) {
     if (isfloat(condval) && fold_can_1(condval) && OPTS_OPTIMIZATION(OPTIM_CONST_FOLD_DCE)) {
         ast_expression_codegen *cgen;
         ir_block               *elide;
@@ -826,3 +831,11 @@ int fold_cond(ir_value *condval, ast_function *func, ast_ifthen *branch) {
     }
     return -1; /* nothing done */
 }
+
+int fold_cond_ternary(ir_value *condval, ast_function *func, ast_ternary *branch) {
+    return fold_cond(condval, func, (ast_ifthen*)branch);
+}
+
+int fold_cond_ifthen(ir_value *condval, ast_function *func, ast_ifthen *branch) {
+    return fold_cond(condval, func, branch);
+}