]> git.tdb.fi Git - libs/gl.git/commitdiff
Eliminate constant ternary expressions
authorMikko Rasa <tdb@tdb.fi>
Mon, 15 Mar 2021 09:05:26 +0000 (11:05 +0200)
committerMikko Rasa <tdb@tdb.fi>
Mon, 15 Mar 2021 09:15:21 +0000 (11:15 +0200)
source/glsl/optimize.cpp
source/glsl/optimize.h
tests/glsl/constant_ternary_removal.glsl [new file with mode: 0644]

index 9cfad86a69d70069fcf6abf2e5877bb99f167000..7473fe2ca598ad996ee6c3263385f938986e80e2 100644 (file)
@@ -792,6 +792,24 @@ void ConstantConditionEliminator::visit(Block &block)
        }
 }
 
+void ConstantConditionEliminator::visit(RefPtr<Expression> &expr)
+{
+       r_ternary_result = 0;
+       expr->visit(*this);
+       if(r_ternary_result)
+               expr = r_ternary_result;
+       r_ternary_result = 0;
+}
+
+void ConstantConditionEliminator::visit(TernaryExpression &ternary)
+{
+       ConstantStatus result = check_constant_condition(*ternary.condition);
+       if(result!=NOT_CONSTANT)
+               r_ternary_result = (result==CONSTANT_TRUE ? ternary.true_expr : ternary.false_expr);
+       else
+               r_ternary_result = 0;
+}
+
 void ConstantConditionEliminator::visit(Conditional &cond)
 {
        ConstantStatus result = check_constant_condition(*cond.condition);
index 1262823f53ead86c058734fc0d62841b70f7dea3..160388065b8fab22d492e3193f8eed9702f76acb 100644 (file)
@@ -191,6 +191,7 @@ private:
 
        NodeList<Statement>::iterator insert_point;
        std::set<Node *> nodes_to_remove;
+       RefPtr<Expression> r_ternary_result;
 
 public:
        void apply(Stage &);
@@ -199,6 +200,8 @@ private:
        ConstantStatus check_constant_condition(const Expression &);
 
        virtual void visit(Block &);
+       virtual void visit(RefPtr<Expression> &);
+       virtual void visit(TernaryExpression &);
        virtual void visit(Conditional &);
        virtual void visit(Iteration &);
 };
diff --git a/tests/glsl/constant_ternary_removal.glsl b/tests/glsl/constant_ternary_removal.glsl
new file mode 100644 (file)
index 0000000..0270710
--- /dev/null
@@ -0,0 +1,33 @@
+const bool use_color = false;
+
+#pragma MSP stage(vertex)
+layout(location=0) in vec4 position;
+layout(location=1) in vec4 color;
+void main()
+{
+       gl_Position = position;
+       passthrough;
+}
+
+#pragma MSP stage(fragment)
+layout(location=0) out vec4 frag_color;
+void main()
+{
+       frag_color = (use_color ? color : vec4(1.0));
+}
+
+/* Expected output: vertex
+layout(location=0) in vec4 position;
+void main()
+{
+       gl_Position = position;
+}
+*/
+
+/* Expected output: fragment
+layout(location=0) out vec4 frag_color;
+void main()
+{
+       frag_color = vec4(1.0);
+}
+*/