summaryrefslogtreecommitdiffstats
path: root/gfx/angle/checkout/src/compiler/translator/tree_ops/RewriteArrayOfArrayOfOpaqueUniforms.cpp
blob: bd12cd10062b14dfef31e01d794856864ceba21f (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
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 2019 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// RewriteAtomicCounters: Emulate atomic counter buffers with storage buffers.
//

#include "compiler/translator/tree_ops/RewriteArrayOfArrayOfOpaqueUniforms.h"

#include "compiler/translator/Compiler.h"
#include "compiler/translator/ImmutableStringBuilder.h"
#include "compiler/translator/SymbolTable.h"
#include "compiler/translator/tree_util/IntermNode_util.h"
#include "compiler/translator/tree_util/IntermTraverse.h"
#include "compiler/translator/tree_util/ReplaceVariable.h"

namespace sh
{
namespace
{
struct UniformData
{
    // Corresponding to an array of array of opaque uniform variable, this is the flattened variable
    // that is replacing it.
    const TVariable *flattened;
    // Assume a general case of array declaration with N dimensions:
    //
    //     uniform type u[Dn]..[D2][D1];
    //
    // Let's define
    //
    //     Pn = D(n-1)*...*D2*D1
    //
    // In that case, we have:
    //
    //     u[In]         = ac + In*Pn
    //     u[In][I(n-1)] = ac + In*Pn + I(n-1)*P(n-1)
    //     u[In]...[Ii]  = ac + In*Pn + ... + Ii*Pi
    //
    // This array contains Pi.  Note that the like TType::mArraySizes, the last element is the
    // outermost dimension.  Element 0 is necessarily 1.
    TVector<unsigned int> mSubArraySizes;
};

using UniformMap = angle::HashMap<const TVariable *, UniformData>;

TIntermTyped *RewriteArrayOfArraySubscriptExpression(TCompiler *compiler,
                                                     TIntermBinary *node,
                                                     const UniformMap &uniformMap);

// Given an expression, this traverser calculates a new expression where array of array of opaque
// uniforms are replaced with their flattened ones.  In particular, this is run on the right node of
// EOpIndexIndirect binary nodes, so that the expression in the index gets a chance to go through
// this transformation.
class RewriteExpressionTraverser final : public TIntermTraverser
{
  public:
    explicit RewriteExpressionTraverser(TCompiler *compiler, const UniformMap &uniformMap)
        : TIntermTraverser(true, false, false), mCompiler(compiler), mUniformMap(uniformMap)
    {}

    bool visitBinary(Visit visit, TIntermBinary *node) override
    {
        TIntermTyped *rewritten =
            RewriteArrayOfArraySubscriptExpression(mCompiler, node, mUniformMap);
        if (rewritten == nullptr)
        {
            return true;
        }

        queueReplacement(rewritten, OriginalNode::IS_DROPPED);

        // Don't iterate as the expression is rewritten.
        return false;
    }

    void visitSymbol(TIntermSymbol *node) override
    {
        // We cannot reach here for an opaque uniform that is being replaced.  visitBinary should
        // have taken care of it.
        ASSERT(!IsOpaqueType(node->getType().getBasicType()) ||
               mUniformMap.find(&node->variable()) == mUniformMap.end());
    }

  private:
    TCompiler *mCompiler;

    const UniformMap &mUniformMap;
};

// Rewrite the index of an EOpIndexIndirect expression.  The root can never need replacing, because
// it cannot be an opaque uniform itself.
void RewriteIndexExpression(TCompiler *compiler,
                            TIntermTyped *expression,
                            const UniformMap &uniformMap)
{
    RewriteExpressionTraverser traverser(compiler, uniformMap);
    expression->traverse(&traverser);
    bool valid = traverser.updateTree(compiler, expression);
    ASSERT(valid);
}

// Given an expression such as the following:
//
//                                              EOpIndex(In)Direct (opaque uniform)
//                                                    /           \
//                                            EOpIndex(In)Direct   I1
//                                                  /           \
//                                                ...            I2
//                                            /
//                                    EOpIndex(In)Direct
//                                          /           \
//                                      uniform          In
//
// produces:
//
//          EOpIndex(In)Direct
//            /        \
//        uniform    In*Pn + ... + I2*P2 + I1*P1
//
TIntermTyped *RewriteArrayOfArraySubscriptExpression(TCompiler *compiler,
                                                     TIntermBinary *node,
                                                     const UniformMap &uniformMap)
{
    // Only interested in opaque uniforms.
    if (!IsOpaqueType(node->getType().getBasicType()))
    {
        return nullptr;
    }

    TIntermSymbol *opaqueUniform = nullptr;

    // Iterate once and find the opaque uniform that's being indexed.
    TIntermBinary *iter = node;
    while (opaqueUniform == nullptr)
    {
        ASSERT(iter->getOp() == EOpIndexDirect || iter->getOp() == EOpIndexIndirect);

        opaqueUniform = iter->getLeft()->getAsSymbolNode();
        iter          = iter->getLeft()->getAsBinaryNode();
    }

    // If not being replaced, there's nothing to do.
    auto flattenedIter = uniformMap.find(&opaqueUniform->variable());
    if (flattenedIter == uniformMap.end())
    {
        return nullptr;
    }

    const UniformData &data = flattenedIter->second;

    // Iterate again and build the index expression.  The index expression constitutes the sum of
    // the variable indices plus a constant offset calculated from the constant indices.  For
    // example, smplr[1][x][2][y] will have an index of x*P3 + y*P1 + c, where c = (1*P4 + 2*P2).
    unsigned int constantOffset = 0;
    TIntermTyped *variableIndex = nullptr;

    // Since the opaque uniforms are fully subscripted, we know exactly how many EOpIndex* nodes
    // there should be.
    for (size_t dimIndex = 0; dimIndex < data.mSubArraySizes.size(); ++dimIndex)
    {
        ASSERT(node);

        unsigned int subArraySize = data.mSubArraySizes[dimIndex];

        switch (node->getOp())
        {
            case EOpIndexDirect:
                // Accumulate the constant index.
                constantOffset +=
                    node->getRight()->getAsConstantUnion()->getIConst(0) * subArraySize;
                break;
            case EOpIndexIndirect:
            {
                // Run RewriteExpressionTraverser on the right node.  It may itself be an expression
                // with an array of array of opaque uniform inside that needs to be rewritten.
                TIntermTyped *indexExpression = node->getRight();
                RewriteIndexExpression(compiler, indexExpression, uniformMap);

                // Scale and accumulate.
                if (subArraySize != 1)
                {
                    indexExpression =
                        new TIntermBinary(EOpMul, indexExpression, CreateIndexNode(subArraySize));
                }

                if (variableIndex == nullptr)
                {
                    variableIndex = indexExpression;
                }
                else
                {
                    variableIndex = new TIntermBinary(EOpAdd, variableIndex, indexExpression);
                }
                break;
            }
            default:
                UNREACHABLE();
                break;
        }

        node = node->getLeft()->getAsBinaryNode();
    }

    // Add the two accumulated indices together.
    TIntermTyped *index = nullptr;
    if (constantOffset == 0 && variableIndex != nullptr)
    {
        // No constant offset, but there's variable offset.  Take that as offset.
        index = variableIndex;
    }
    else
    {
        // Either the constant offset is non zero, or there's no variable offset (so constant 0
        // should be used).
        index = CreateIndexNode(constantOffset);

        if (variableIndex)
        {
            index = new TIntermBinary(EOpAdd, index, variableIndex);
        }
    }

    // Create an index into the flattened uniform.
    TOperator op = variableIndex ? EOpIndexIndirect : EOpIndexDirect;
    return new TIntermBinary(op, new TIntermSymbol(data.flattened), index);
}

// Traverser that takes:
//
//     uniform sampler/image/atomic_uint u[N][M]..
//
// and transforms it to:
//
//     uniform sampler/image/atomic_uint u[N * M * ..]
//
// MonomorphizeUnsupportedFunctions makes it impossible for this array to be partially
// subscripted, or passed as argument to a function unsubscripted.  This means that every encounter
// of this uniform can be expected to be fully subscripted.
//
class RewriteArrayOfArrayOfOpaqueUniformsTraverser : public TIntermTraverser
{
  public:
    RewriteArrayOfArrayOfOpaqueUniformsTraverser(TCompiler *compiler, TSymbolTable *symbolTable)
        : TIntermTraverser(true, false, false, symbolTable), mCompiler(compiler)
    {}

    bool visitDeclaration(Visit visit, TIntermDeclaration *node) override
    {
        if (!mInGlobalScope)
        {
            return true;
        }

        const TIntermSequence &sequence = *(node->getSequence());

        TIntermTyped *variable = sequence.front()->getAsTyped();
        const TType &type      = variable->getType();
        bool isOpaqueUniform =
            type.getQualifier() == EvqUniform && IsOpaqueType(type.getBasicType());

        // Only interested in array of array of opaque uniforms.
        if (!isOpaqueUniform || !type.isArrayOfArrays())
        {
            return false;
        }

        // Opaque uniforms cannot have initializers, so the declaration must necessarily be a
        // symbol.
        TIntermSymbol *symbol = variable->getAsSymbolNode();
        ASSERT(symbol != nullptr);

        const TVariable *uniformVariable = &symbol->variable();

        // Create an entry in the map.
        ASSERT(mUniformMap.find(uniformVariable) == mUniformMap.end());
        UniformData &data = mUniformMap[uniformVariable];

        // Calculate the accumulated dimension products.  See UniformData::mSubArraySizes.
        const TSpan<const unsigned int> &arraySizes = type.getArraySizes();
        mUniformMap[uniformVariable].mSubArraySizes.resize(arraySizes.size());
        unsigned int runningProduct = 1;
        for (size_t dimension = 0; dimension < arraySizes.size(); ++dimension)
        {
            data.mSubArraySizes[dimension] = runningProduct;
            runningProduct *= arraySizes[dimension];
        }

        // Create a replacement variable with the array flattened.
        TType *newType = new TType(type);
        newType->toArrayBaseType();
        newType->makeArray(runningProduct);

        data.flattened = new TVariable(mSymbolTable, uniformVariable->name(), newType,
                                       uniformVariable->symbolType());

        TIntermDeclaration *decl = new TIntermDeclaration;
        decl->appendDeclarator(new TIntermSymbol(data.flattened));

        queueReplacement(decl, OriginalNode::IS_DROPPED);
        return false;
    }

    bool visitFunctionDefinition(Visit visit, TIntermFunctionDefinition *node) override
    {
        // As an optimization, don't bother inspecting functions if there aren't any opaque uniforms
        // to replace.
        return !mUniformMap.empty();
    }

    // Same implementation as in RewriteExpressionTraverser.  That traverser cannot replace root.
    bool visitBinary(Visit visit, TIntermBinary *node) override
    {
        TIntermTyped *rewritten =
            RewriteArrayOfArraySubscriptExpression(mCompiler, node, mUniformMap);
        if (rewritten == nullptr)
        {
            return true;
        }

        queueReplacement(rewritten, OriginalNode::IS_DROPPED);

        // Don't iterate as the expression is rewritten.
        return false;
    }

    void visitSymbol(TIntermSymbol *node) override
    {
        ASSERT(!IsOpaqueType(node->getType().getBasicType()) ||
               mUniformMap.find(&node->variable()) == mUniformMap.end());
    }

  private:
    TCompiler *mCompiler;
    UniformMap mUniformMap;
};
}  // anonymous namespace

bool RewriteArrayOfArrayOfOpaqueUniforms(TCompiler *compiler,
                                         TIntermBlock *root,
                                         TSymbolTable *symbolTable)
{
    RewriteArrayOfArrayOfOpaqueUniformsTraverser traverser(compiler, symbolTable);
    root->traverse(&traverser);
    return traverser.updateTree(compiler, root);
}
}  // namespace sh