summaryrefslogtreecommitdiffstats
path: root/gfx/skia/skia/src/sksl/transform/SkSLEliminateEmptyStatements.cpp
blob: e36867bd5e52aad98281aba6d3f8996ee9f2cca9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
 * Copyright 2022 Google LLC
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "include/core/SkSpan.h"
#include "include/private/SkSLDefines.h"
#include "include/private/SkSLProgramElement.h"
#include "include/private/SkSLStatement.h"
#include "src/sksl/SkSLCompiler.h"
#include "src/sksl/ir/SkSLBlock.h"
#include "src/sksl/ir/SkSLFunctionDefinition.h"
#include "src/sksl/transform/SkSLProgramWriter.h"
#include "src/sksl/transform/SkSLTransform.h"

#include <algorithm>
#include <iterator>
#include <memory>
#include <vector>

namespace SkSL {

class Expression;

static void eliminate_empty_statements(SkSpan<std::unique_ptr<ProgramElement>> elements) {
    class EmptyStatementEliminator : public ProgramWriter {
    public:
        bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
            // We don't need to look inside expressions at all.
            return false;
        }

        bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
            // Work from the innermost blocks to the outermost.
            INHERITED::visitStatementPtr(stmt);

            if (stmt->is<Block>()) {
                StatementArray& children = stmt->as<Block>().children();
                auto iter = std::remove_if(children.begin(), children.end(),
                                           [](std::unique_ptr<Statement>& stmt) {
                                               return stmt->isEmpty();
                                           });
                children.resize(std::distance(children.begin(), iter));
            }

            // We always check the entire program.
            return false;
        }

        using INHERITED = ProgramWriter;
    };

    for (std::unique_ptr<ProgramElement>& pe : elements) {
        if (pe->is<FunctionDefinition>()) {
            EmptyStatementEliminator visitor;
            visitor.visitStatementPtr(pe->as<FunctionDefinition>().body());
        }
    }
}

void Transform::EliminateEmptyStatements(Module& module) {
    return eliminate_empty_statements(SkSpan(module.fElements));
}

}  // namespace SkSL