summaryrefslogtreecommitdiffstats
path: root/source/slang/slang-ir-spirv-snippet.cpp
blob: 6ed902ba44d82f032ae39a911adfa9594ed6ad91 (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
// slang-ir-spirv-snippet.cpp

#include "slang-ir-spirv-snippet.h"

#include "../compiler-core/slang-spirv-core-grammar.h"
#include "../core/slang-token-reader.h"
#include "slang-lookup-spirv.h"

namespace Slang
{
static SpvStorageClass translateStorageClass(String name)
{
    if (name == "Uniform")
    {
        return SpvStorageClassUniform;
    }
    else if (name == "StorageBuffer")
    {
        return SpvStorageClassStorageBuffer;
    }
    return (SpvStorageClass)-1;
}

SpvSnippet::ASMType parseASMType(Slang::Misc::TokenReader& tokenReader)
{
    auto word = tokenReader.ReadWord();
    if (word == "float")
        return SpvSnippet::ASMType::Float;
    else if (word == "double")
        return SpvSnippet::ASMType::Double;
    else if (word == "uint2")
        return SpvSnippet::ASMType::UInt2;
    else if (word == "uint16_t")
        return SpvSnippet::ASMType::UInt16;
    else if (word == "float2")
        return SpvSnippet::ASMType::Float2;
    else if (word == "int")
        return SpvSnippet::ASMType::Int;
    else if (word == "uint")
        return SpvSnippet::ASMType::UInt;
    else if (word == "_p")
        return SpvSnippet::ASMType::FloatOrDouble;
    else if (word == "half")
        return SpvSnippet::ASMType::Half;
    return SpvSnippet::ASMType::None;
}

// Read an unsigned integer (a SPIR-V word) or a SPIR-V enum (currently those
// which are coded into this function).
//
// This also 'or's together a list of these words/enums separated by '|'
SpvWord readWordOrWordLiteral(Misc::TokenReader& reader)
{
    SpvWord ret = 0;
    do
    {
        switch (reader.NextToken().Type)
        {
        case Slang::Misc::TokenType::IntLiteral:
            ret = reader.ReadUInt();
            break;
        case Slang::Misc::TokenType::Identifier:
            {
                const auto i = reader.ReadWord();
#define GO(x)    \
    if (i == #x) \
    ret |= Spv##x
                GO(ScopeWorkgroup);
                else GO(ScopeDevice);
                else GO(MemorySemanticsMaskNone);
                else GO(MemorySemanticsAcquireReleaseMask);
                else GO(MemorySemanticsUniformMemoryMask);
                else GO(MemorySemanticsImageMemoryMask);
                else GO(MemorySemanticsAtomicCounterMemoryMask);
                else GO(MemorySemanticsWorkgroupMemoryMask);
#undef GO
                else
                {
                    reader.Back(1);
                    throw Misc::TextFormatException(
                        "Text parsing error: Unrecognized SPIR-V enum: " + i);
                }
            }
            break;
        default:
            throw Misc::TextFormatException("Text parsing error: Expected int or SPIR-V enum");
        }
    } while (reader.AdvanceIf(Misc::TokenType::OpBitOr));
    return ret;
}

RefPtr<SpvSnippet> SpvSnippet::parse(
    const SPIRVCoreGrammarInfo& spirvGrammar,
    UnownedStringSlice definition)
{
    RefPtr<SpvSnippet> snippet = new SpvSnippet();
    try
    {
        Dictionary<String, SpvWord> mapInstNameToIndex;
        Slang::Misc::TokenReader tokenReader(definition);
        // A leading "*" at the beginning of the snip modifies $resultType with
        // a storage class.
        if (tokenReader.AdvanceIf("*"))
        {
            auto storageToken = tokenReader.ReadWord();
            snippet->resultStorageClass = translateStorageClass(storageToken);
        }
        while (!tokenReader.IsEnd())
        {
            SpvSnippet::ASMInst inst;
            if (tokenReader.AdvanceIf("%"))
            {
                String instName = tokenReader.ReadToken().Content;
                mapInstNameToIndex.set(instName, (int)snippet->instructions.getCount());
                tokenReader.Read(Slang::Misc::TokenType::OpAssign);
            }
            SpvOp opCode;
            switch (tokenReader.NextToken().Type)
            {
            case Slang::Misc::TokenType::IntLiteral:
                opCode = (SpvOp)tokenReader.ReadInt();
                break;
            case Slang::Misc::TokenType::Identifier:
                {
                    auto opName = tokenReader.ReadWord();
                    const auto opCodeMaybe = spirvGrammar.opcodes.lookup(opName.getUnownedSlice());
                    if (!opCodeMaybe)
                    {
                        throw Misc::TextFormatException(
                            "Text parsing error: Unrecognized SPIR-V opcode: " + opName);
                    }
                    opCode = *opCodeMaybe;
                    break;
                }
            default:
                throw Misc::TextFormatException("Text parsing error: SPIR-V intrinsics must "
                                                "begin with an integer or opcode name");
            }
            inst.opCode = opCode;
            bool insideOperandList = true;
            const bool isExtInst = inst.opCode == SpvOpExtInst;
            bool isGLSLstd450OpcodeAllowed = false;
            auto readExtInstOpcode = [&]()
            {
                switch (tokenReader.NextToken().Type)
                {
                case Slang::Misc::TokenType::IntLiteral:
                    return (SpvWord)tokenReader.ReadInt();
                    break;
                case Slang::Misc::TokenType::Identifier:
                    {
                        if (isGLSLstd450OpcodeAllowed)
                        {
                            auto opName = tokenReader.ReadWord();
                            GLSLstd450 glslOpcode;
                            if (!lookupGLSLstd450(opName.getUnownedSlice(), glslOpcode))
                            {
                                throw Misc::TextFormatException(
                                    "Text parsing error: Unrecognized SPIR-V GLSLstd450 opcode: " +
                                    opName);
                            }
                            return (SpvWord)glslOpcode;
                        }
                    }
                // fallthrough
                default:
                    throw Misc::TextFormatException(
                        "Text parsing error: Failed to read SPIR-V ExtInst Opcode");
                }
            };
            while (insideOperandList)
            {
                ASMOperand operand = {ASMOperandType::SpvWord, 0, 0, 0};
                switch (tokenReader.NextToken().Type)
                {
                case Slang::Misc::TokenType::Semicolon:
                    insideOperandList = false;
                    tokenReader.ReadToken();
                    break;
                case Slang::Misc::TokenType::IntLiteral:
                    operand.type = SpvSnippet::ASMOperandType::SpvWord;
                    operand.content = tokenReader.ReadInt();
                    inst.operands.add(operand);
                    break;
                case Slang::Misc::TokenType::OpMod:
                    {
                        tokenReader.ReadToken();
                        operand.type = SpvSnippet::ASMOperandType::InstReference;
                        auto refName = tokenReader.ReadToken().Content;
                        if (!mapInstNameToIndex.tryGetValue(refName, operand.content))
                        {
                            SLANG_ASSERT(!"Invalid SPV ASM: referenced inst is not defined.");
                        }
                        inst.operands.add(operand);
                    }
                    break;
                case Slang::Misc::TokenType::Identifier:
                    {
                        auto identifier = tokenReader.ReadToken().Content;
                        if (identifier == "resultType")
                        {
                            operand.type = SpvSnippet::ASMOperandType::ResultTypeId;
                            operand.content = (SpvWord)0xFFFFFFFF;
                            if (tokenReader.AdvanceIf("*"))
                            {
                                // A "*" at operand qualifies the use of `resultType` as
                                // `ptr(resultType, storage class), but does
                                // not modify `resultType` itself.
                                auto storageClass = tokenReader.ReadWord();
                                auto spvStorageClass = translateStorageClass(storageClass);
                                operand.content = spvStorageClass;
                                snippet->usedPtrResultTypeStorageClasses.add(spvStorageClass);
                            }
                            inst.operands.add(operand);
                        }
                        else if (identifier == "resultId")
                        {
                            operand.type = SpvSnippet::ASMOperandType::ResultId;
                            inst.operands.add(operand);
                        }
                        else if (identifier == "glsl450")
                        {
                            operand.type = SpvSnippet::ASMOperandType::GLSL450ExtInstSet;
                            inst.operands.add(operand);
                            // Allow the next token to be parsed as a glslsstd450 opcode
                            isGLSLstd450OpcodeAllowed = isExtInst;
                        }
                        else if (identifier == "fi")
                        {
                            operand.type = SpvSnippet::ASMOperandType::FloatIntegerSelection;
                            tokenReader.Read("(");
                            operand.content = readExtInstOpcode();
                            tokenReader.Read(",");
                            operand.content2 = readExtInstOpcode();
                            tokenReader.Read(")");
                            inst.operands.add(operand);
                        }
                        else if (identifier == "fus")
                        {
                            operand.type = SpvSnippet::ASMOperandType::FloatUnsignedSignedSelection;
                            tokenReader.Read("(");
                            operand.content = readExtInstOpcode();
                            tokenReader.Read(",");
                            operand.content2 = readExtInstOpcode();
                            tokenReader.Read(",");
                            operand.content3 = readExtInstOpcode();
                            tokenReader.Read(")");
                            inst.operands.add(operand);
                        }
                        else if (identifier == "_type")
                        {
                            operand.type = SpvSnippet::ASMOperandType::TypeReference;
                            tokenReader.Read("(");
                            operand.content = (SpvWord)parseASMType(tokenReader);
                            tokenReader.Read(")");
                            inst.operands.add(operand);
                        }
                        else if (identifier.startsWith("_"))
                        {
                            operand.type = SpvSnippet::ASMOperandType::ObjectReference;
                            operand.content = (SpvWord)stringToInt(
                                identifier.subString(1, identifier.getLength() - 1));
                            inst.operands.add(operand);
                        }
                        else if (identifier == "const")
                        {
                            operand.type = SpvSnippet::ASMOperandType::ConstantReference;
                            ASMConstant constant;
                            memset(&constant, 0, sizeof(ASMConstant));
                            tokenReader.Read("(");
                            constant.type = parseASMType(tokenReader);
                            int i = 0;
                            while (tokenReader.AdvanceIf(","))
                            {
                                switch (constant.type)
                                {
                                case ASMType::Float:
                                case ASMType::Float2:
                                case ASMType::FloatOrDouble:
                                    constant.floatValues[i] = tokenReader.ReadFloat();
                                    ++i;
                                    break;

                                default:
                                    constant.intValues[i] = readWordOrWordLiteral(tokenReader);
                                    ++i;
                                    break;
                                }
                            }
                            tokenReader.Read(")");
                            snippet->constants.add(constant);
                            operand.content = (SpvWord)(snippet->constants.getCount() - 1);
                            inst.operands.add(operand);
                        }
                        else if (isGLSLstd450OpcodeAllowed)
                        {
                            GLSLstd450 glslstd450Opcode;
                            lookupGLSLstd450(identifier.getUnownedSlice(), glslstd450Opcode);
                            operand.type = SpvSnippet::ASMOperandType::SpvWord;
                            operand.content = (SpvWord)glslstd450Opcode;
                            inst.operands.add(operand);
                        }
                        else
                        {
                            SLANG_UNEXPECTED(
                                ("Invalid SPV ASM operand: \"" + identifier + "\"").getBuffer());
                        }
                    }
                    break;
                default:
                    insideOperandList = false;
                    break;
                }
            }
            snippet->instructions.add(inst);
        }
    }
    catch (const Slang::Misc::TextFormatException&)
    {
        return nullptr;
    }
    return snippet;
}


} // namespace Slang