File: GlobalSorting.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (348 lines) | stat: -rw-r--r-- 10,827 bytes parent folder | download | duplicates (7)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/*
 * Copyright (c) 2023 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "GlobalSorting.h"

#include "ASTIdentifierExpression.h"
#include "ASTScopedVisitorInlines.h"
#include "ASTVariableStatement.h"
#include "ContextProviderInlines.h"
#include "WGSLShaderModule.h"
#include <wtf/DataLog.h>
#include <wtf/Deque.h>
#include <wtf/HashMap.h>
#include <wtf/ListHashSet.h>
#include <wtf/SetForScope.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/StringBuilder.h>

namespace WGSL {

constexpr bool shouldLogGlobalSorting = false;

inline String nameForDeclaration(AST::Declaration& declaration)
{
    return is<AST::ConstAssert>(declaration) ? "const_assert"_s : declaration.name().id();
}

class Graph {
public:
    class Edge;
    class Node;
    struct EdgeHash;
    struct EdgeHashTraits;
    using EdgeSet = ListHashSet<Edge, EdgeHash>;

    class Edge {
        friend EdgeHash;
        friend EdgeHashTraits;
    public:
        Edge()
            : m_source(nullptr)
            , m_target(nullptr)
        {
        }

        Edge(Node& source, Node& target)
            : m_source(&source)
            , m_target(&target)
        {
        }

        Node& source() const { return *m_source; }
        Node& target() const { return *m_target; }

        bool operator==(const Edge& other) const
        {
            return m_source == other.m_source && m_target == other.m_target;
        }

    private:
        Node* m_source;
        Node* m_target;
    };

    struct EdgeHashTraits : HashTraits<Edge> {
        static constexpr bool emptyValueIsZero = true;
        static void constructDeletedValue(Edge& slot) { slot.m_source = std::bit_cast<Node*>(static_cast<intptr_t>(-1)); }
        static bool isDeletedValue(const Edge& edge) { return edge.m_source == std::bit_cast<Node*>(static_cast<intptr_t>(-1)); }
    };

    struct EdgeHash {
        static unsigned hash(const Edge& edge)
        {
            return WTF::TupleHash<Node*, Node*>::hash(std::tuple(edge.m_source, edge.m_target));
        }
        static bool equal(const Edge& a, const Edge& b)
        {
            return a == b;
        }
        static constexpr bool safeToCompareToEmptyOrDeleted = true;
    };

    class Node {
    public:
        Node()
            : m_astNode(nullptr)
        {
        }

        Node(unsigned index, AST::Declaration& astNode)
            : m_index(index)
            , m_astNode(&astNode)
        {
        }

        unsigned index() const { return m_index; }
        AST::Declaration& astNode() const { return *m_astNode; }
        EdgeSet& incomingEdges() { return m_incomingEdges; }
        EdgeSet& outgoingEdges() { return m_outgoingEdges; }

    private:
        unsigned m_index;
        AST::Declaration* m_astNode;
        EdgeSet m_incomingEdges;
        EdgeSet m_outgoingEdges;
    };


    Graph(size_t capacity)
        : m_nodes(capacity)
    {
    }

    FixedVector<Node>& nodes() { return m_nodes; }
    Node* addNode(unsigned index, AST::Declaration& astNode)
    {
        bool isConstAssert = is<AST::ConstAssert>(astNode);
        if (!isConstAssert && m_nodeMap.find(astNode.name()) != m_nodeMap.end())
            return nullptr;

        m_nodes[index] = Node(index, astNode);
        auto* node = &m_nodes[index];
        if (!isConstAssert)
            m_nodeMap.add(astNode.name(), node);
        return node;
    }
    Node* getNode(const AST::Identifier& identifier)
    {
        auto it = m_nodeMap.find(identifier);
        if (it == m_nodeMap.end())
            return nullptr;
        return it->value;
    }

    EdgeSet& edges() { return m_edges; }
    void addEdge(Node& source, Node& target)
    {
        if constexpr (shouldLogGlobalSorting)
            dataLogLn("addEdge: source: ", nameForDeclaration(source.astNode()), ", target: ", target.astNode().name());
        auto result = m_edges.add(Edge(source, target));
        Edge& edge = *result.iterator;
        source.outgoingEdges().add(edge);
        target.incomingEdges().add(edge);
    }

    void topologicalSort();

private:
    FixedVector<Node> m_nodes;
    HashMap<String, Node*> m_nodeMap;
    EdgeSet m_edges;
};

struct Empty { };

class GraphBuilder : public AST::ScopedVisitor<Empty> {
    static constexpr unsigned s_maxExpressionDepth = 512;

    using Base = AST::ScopedVisitor<Empty>;
    using Base::visit;

public:
    static Result<void> visit(Graph&, Graph::Node&);

    void visit(AST::Parameter&) override;
    void visit(AST::VariableStatement&) override;
    void visit(AST::Expression&) override;
    void visit(AST::IdentifierExpression&) override;

private:
    GraphBuilder(Graph&, Graph::Node&);

    void introduceVariable(AST::Identifier&);
    void readVariable(AST::Identifier&) const;

    Graph& m_graph;
    Graph::Node& m_currentNode;
    unsigned m_expressionDepth { 0 };
};

Result<void> GraphBuilder::visit(Graph& graph, Graph::Node& node)
{
    GraphBuilder graphBuilder(graph, node);
    graphBuilder.visit(node.astNode());
    return graphBuilder.result();
}

GraphBuilder::GraphBuilder(Graph& graph, Graph::Node& node)
    : m_graph(graph)
    , m_currentNode(node)
{
}

void GraphBuilder::visit(AST::Parameter& parameter)
{
    introduceVariable(parameter.name());
    Base::visit(parameter);
}

void GraphBuilder::visit(AST::VariableStatement& variable)
{
    introduceVariable(variable.variable().name());
    Base::visit(variable);
}

void GraphBuilder::visit(AST::Expression& expression)
{
    SetForScope expressionDepthScope(m_expressionDepth, m_expressionDepth + 1);
    if (UNLIKELY(m_expressionDepth > s_maxExpressionDepth)) {
        setError({ makeString("reached maximum expression depth of "_s, String::number(s_maxExpressionDepth)), expression.span() });
        return;
    }

    Base::visit(expression);
}

void GraphBuilder::visit(AST::IdentifierExpression& identifier)
{
    readVariable(identifier.identifier());
}

void GraphBuilder::introduceVariable(AST::Identifier& name)
{
    ContextProvider::introduceVariable(name, { });
}

void GraphBuilder::readVariable(AST::Identifier& name) const
{
    if (ContextProvider::readVariable(name))
        return;
    if (auto* node = m_graph.getNode(name))
        m_graph.addEdge(m_currentNode, *node);
}


static std::optional<FailedCheck> reorder(AST::Declaration::List& list)
{
    Graph graph(list.size());
    Vector<Graph::Node*> graphNodeList;
    graphNodeList.reserveCapacity(list.size());
    unsigned index = 0;
    for (auto& node : list) {
        auto* graphNode = graph.addNode(index++, node);
        if (!graphNode) {
            // This is unfortunately duplicated between this pass and the type checker
            // since here we only cover redeclarations of the same type (e.g. two
            // variables with the same name), while the type checker will also identify
            // redeclarations of different types (e.g. a variable and a struct with the
            // same name)
            return FailedCheck { Vector<Error> { Error(makeString("redeclaration of '"_s, node.name(), '\''), node.span()) }, { } };
        }
        graphNodeList.append(graphNode);
    }

    for (auto* graphNode : graphNodeList) {
        auto result = GraphBuilder::visit(graph, *graphNode);
        if (!result)
            return FailedCheck { Vector<Error> { result.error() }, { } };
    }

    list.clear();
    Deque<Graph::Node> queue;

    std::function<void(Graph::Node&, unsigned)> processNode;
    processNode = [&](Graph::Node& node, unsigned currentIndex) {
        if constexpr (shouldLogGlobalSorting)
            dataLogLn("Process: ", nameForDeclaration(node.astNode()));
        list.append(node.astNode());
        for (auto edge : node.incomingEdges()) {
            auto& source = edge.source();
            source.outgoingEdges().remove(edge);
            graph.edges().remove(edge);
            if (source.outgoingEdges().isEmpty() && source.index() < currentIndex)
                processNode(source, currentIndex);
        }
    };

    for (auto& node : graph.nodes()) {
        if (node.outgoingEdges().isEmpty())
            processNode(node, node.index());
    }

    if (graph.edges().isEmpty())
        return std::nullopt;

    dataLogLnIf(shouldLogGlobalSorting, "=== CYCLE ===");
    Graph::Node* cycleNode = nullptr;
    for (auto& node : graph.nodes()) {
        if (!node.outgoingEdges().isEmpty()) {
            cycleNode = &node;
            break;
        }
    }
    ASSERT(cycleNode);
    StringBuilder error;
    auto* node = cycleNode;
    HashSet<Graph::Node*> visited;
    while (true) {
        if constexpr (shouldLogGlobalSorting)
            dataLogLn("cycle node: ", nameForDeclaration(node->astNode()));
        ASSERT(!node->outgoingEdges().isEmpty());
        visited.add(node);
        node = &node->outgoingEdges().first().target();
        if (visited.contains(node)) {
            cycleNode = node;
            break;
        }
    }
    error.append("encountered a dependency cycle: "_s, cycleNode->astNode().name());
    do {
        ASSERT(!node->outgoingEdges().isEmpty());
        node = &node->outgoingEdges().first().target();
        error.append(" -> "_s, node->astNode().name());
    } while (node != cycleNode);
    return FailedCheck { Vector<Error> { Error(error.toString(), cycleNode->astNode().span()) }, { } };
}

std::optional<FailedCheck> reorderGlobals(ShaderModule& module)
{
    if (auto maybeError = reorder(module.declarations()))
        return *maybeError;
    return std::nullopt;
}

} // namespace WGSL