yum-mirror/glslang

git clone https://git.yummers.dev/yum-mirror/glslang

Jeff BolzImplement GL_EXT_ocp_microscaling_types62f5430e

vulkan-sdk-1.4.357.0
57.2 KiB1235 linesraw
1//
2// Copyright (C) 2014-2015 LunarG, Inc.
3// Copyright (C) 2015-2020 Google, Inc.
4// Copyright (C) 2017 ARM Limited.
5// Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
6//
7// All rights reserved.
8//
9// Redistribution and use in source and binary forms, with or without
10// modification, are permitted provided that the following conditions
11// are met:
12//
13//    Redistributions of source code must retain the above copyright
14//    notice, this list of conditions and the following disclaimer.
15//
16//    Redistributions in binary form must reproduce the above
17//    copyright notice, this list of conditions and the following
18//    disclaimer in the documentation and/or other materials provided
19//    with the distribution.
20//
21//    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
22//    contributors may be used to endorse or promote products derived
23//    from this software without specific prior written permission.
24//
25// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36// POSSIBILITY OF SUCH DAMAGE.
37
38//
39// "Builder" is an interface to fully build SPIR-V IR.   Allocate one of
40// these to build (a thread safe) internal SPIR-V representation (IR),
41// and then dump it as a binary stream according to the SPIR-V specification.
42//
43// A Builder has a 1:1 relationship with a SPIR-V module.
44//
45
46#pragma once
47#ifndef SpvBuilder_H
48#define SpvBuilder_H
49
50#include "Logger.h"
51#define SPV_ENABLE_UTILITY_CODE
52#include "spirv.hpp11"
53#include "spvIR.h"
54#include "spvUtil.h"
55
56namespace spv {
57    #include "GLSL.ext.KHR.h"
58    #include "GLSL.ext.EXT.h"
59    #include "NonSemanticShaderDebugInfo.h"
60}
61
62#include <algorithm>
63#include <cstdint>
64#include <map>
65#include <memory>
66#include <set>
67#include <sstream>
68#include <stack>
69#include <unordered_map>
70#include <unordered_set>
71#include <map>
72
73namespace spv {
74
75typedef enum {
76    Spv_1_0 = (1 << 16),
77    Spv_1_1 = (1 << 16) | (1 << 8),
78    Spv_1_2 = (1 << 16) | (2 << 8),
79    Spv_1_3 = (1 << 16) | (3 << 8),
80    Spv_1_4 = (1 << 16) | (4 << 8),
81    Spv_1_5 = (1 << 16) | (5 << 8),
82    Spv_1_6 = (1 << 16) | (6 << 8),
83} SpvVersion;
84
85struct StructMemberDebugInfo {
86    std::string name {};
87    int line {0};
88    int column {0};
89    // Set if the caller knows a better debug type than what is associated with the functional SPIR-V type.
90    spv::Id debugTypeOverride {0};
91};
92
93class Builder {
94public:
95    Builder(unsigned int spvVersion, unsigned int userNumber, SpvBuildLogger* logger);
96    virtual ~Builder();
97
98    static const int maxMatrixSize = 4;
99
100    unsigned int getSpvVersion() const { return spvVersion; }
101
102    void setSource(spv::SourceLanguage lang, int version)
103    {
104        sourceLang = lang;
105        sourceVersion = version;
106    }
107    spv::Id getStringId(const std::string& str)
108    {
109        auto sItr = stringIds.find(str);
110        if (sItr != stringIds.end())
111            return sItr->second;
112        spv::Id strId = getUniqueId();
113        Instruction* fileString = new Instruction(strId, NoType, Op::OpString);
114        const char* file_c_str = str.c_str();
115        fileString->addStringOperand(file_c_str);
116        strings.push_back(std::unique_ptr<Instruction>(fileString));
117        module.mapInstruction(fileString);
118        stringIds[file_c_str] = strId;
119        return strId;
120    }
121
122    spv::Id getMainFileId() const { return mainFileId; }
123
124    // Initialize the main source file name
125    void setDebugMainSourceFile(const std::string& file)
126    {
127        if (trackDebugInfo) {
128            dirtyLineTracker = true;
129            mainFileId = getStringId(file);
130            currentFileId = mainFileId;
131        }
132    }
133
134    // Set the debug source location tracker in the builder.
135    // The upcoming instructions in basic blocks will be associated to this location.
136    void setDebugSourceLocation(int line, const char* filename)
137    {
138        if (trackDebugInfo) {
139            dirtyLineTracker = true;
140            if (line != 0) {
141                // TODO: This is special handling of some AST nodes having (untracked) line 0.
142                //       But they should have a valid line number.
143                currentLine = line;
144                if (filename) {
145                    currentFileId = getStringId(filename);
146                }
147            }
148        }
149    }
150
151    void setSourceText(const std::string& text) { sourceText = text; }
152    void addSourceExtension(const char* ext) { sourceExtensions.push_back(ext); }
153    void addModuleProcessed(const std::string& p) { moduleProcesses.push_back(p.c_str()); }
154    void setEmitSpirvDebugInfo()
155    {
156        trackDebugInfo = true;
157        emitSpirvDebugInfo = true;
158    }
159    void setEmitNonSemanticShaderDebugInfo(bool emitSourceText)
160    {
161        trackDebugInfo = true;
162        emitNonSemanticShaderDebugInfo = true;
163        importNonSemanticShaderDebugInfoInstructions();
164
165        if (emitSourceText) {
166            emitNonSemanticShaderDebugSource = emitSourceText;
167        }
168    }
169    void addExtension(const char* ext) { extensions.insert(ext); }
170    void removeExtension(const char* ext)
171    {
172        extensions.erase(ext);
173    }
174    void addIncorporatedExtension(const char* ext, SpvVersion incorporatedVersion)
175    {
176        if (getSpvVersion() < static_cast<unsigned>(incorporatedVersion))
177            addExtension(ext);
178    }
179    void promoteIncorporatedExtension(const char* baseExt, const char* promoExt, SpvVersion incorporatedVersion)
180    {
181        removeExtension(baseExt);
182        addIncorporatedExtension(promoExt, incorporatedVersion);
183    }
184    void addInclude(const std::string& name, const std::string& text)
185    {
186        spv::Id incId = getStringId(name);
187        includeFiles[incId] = &text;
188    }
189    Id import(const char*);
190    void setMemoryModel(spv::AddressingModel addr, spv::MemoryModel mem)
191    {
192        addressModel = addr;
193        memoryModel = mem;
194    }
195
196    void addCapability(spv::Capability cap) { capabilities.insert(cap); }
197
198    // To get a new <id> for anything needing a new one.
199    Id getUniqueId() { return ++uniqueId; }
200
201    // To get a set of new <id>s, e.g., for a set of function parameters
202    Id getUniqueIds(int numIds)
203    {
204        Id id = uniqueId + 1;
205        uniqueId += numIds;
206        return id;
207    }
208
209    // Maps the given OpType Id to a Non-Semantic DebugType Id.
210    Id getDebugType(Id type) {
211        if (auto it = debugTypeIdLookup.find(type); it != debugTypeIdLookup.end()) {
212            return it->second;
213        }
214        
215        return NoType;
216    }
217
218    // Maps the given OpFunction Id to a Non-Semantic DebugFunction Id.
219    Id getDebugFunction(Id func) {
220        if (auto it = debugFuncIdLookup.find(func); it != debugFuncIdLookup.end()) {
221            return it->second;
222        }
223        
224        return NoResult;
225    }
226
227    // For creating new types (will return old type if the requested one was already made).
228    Id makeVoidType();
229    Id makeBoolType();
230    Id makePointer(StorageClass, Id pointee);
231    Id makeForwardPointer(StorageClass);
232    Id makePointerFromForwardPointer(StorageClass, Id forwardPointerType, Id pointee);
233    Id makeUntypedPointer(StorageClass storageClass, bool setBufferPointer = false);
234    Id makeIntegerType(int width, bool hasSign);   // generic
235    Id makeIntType(int width) { return makeIntegerType(width, true); }
236    Id makeUintType(int width) { return makeIntegerType(width, false); }
237    Id makeFloatType(int width);
238    Id makeBFloat16Type();
239    Id makeFloatE5M2Type();
240    Id makeFloatE4M3Type();
241    Id makeFloatE2M1Type();
242    Id makeFloatE3M2Type();
243    Id makeFloatE2M3Type();
244    Id makeFloatUE8M0Type();
245    Id makeFloatMXINT8Type();
246    Id makeFloatOcpMicroscalingType(uint32_t width, FPEncoding encoding, Capability cap);
247    Id makeStructType(const std::vector<Id>& members, const std::vector<spv::StructMemberDebugInfo>& memberDebugInfo,
248                      const char* name, bool const compilerGenerated = true);
249    Id makeStructResultType(Id type0, Id type1);
250    Id makeVectorType(Id component, int size);
251    Id makeMatrixType(Id component, int cols, int rows);
252    Id makeArrayType(Id element, Id sizeId, int stride);  // 0 stride means no stride decoration
253    Id makeRuntimeArray(Id element);
254    Id makeFunctionType(Id returnType, const std::vector<Id>& paramTypes);
255    Id makeImageType(Id sampledType, Dim, bool depth, bool arrayed, bool ms, unsigned sampled, ImageFormat format, const char* debugNames);
256    Id makeSamplerType(const char* debugName);
257    Id makeSampledImageType(Id imageType, const char* debugName);
258    Id makeCooperativeMatrixTypeKHR(Id component, Id scope, Id rows, Id cols, Id use);
259    Id makeCooperativeMatrixTypeNV(Id component, Id scope, Id rows, Id cols);
260    Id makeCooperativeMatrixTypeWithSameShape(Id component, Id otherType);
261    Id makeCooperativeVectorTypeNV(Id componentType, Id components);
262    Id makeTensorTypeARM(Id elementType, Id rank);
263    Id makeGenericType(spv::Op opcode, std::vector<spv::IdImmediate>& operands);
264
265    // SPIR-V NonSemantic Shader DebugInfo Instructions
266    Id makeDebugInfoNone();
267    Id makeBoolDebugType(int const size);
268    Id makeIntegerDebugType(int const width, bool const hasSign);
269    Id makeFloatDebugType(int const width, Id const fpEncoding = NoType);
270    Id makeSequentialDebugType(Id const baseType, Id const componentCount, NonSemanticShaderDebugInfoInstructions const sequenceType);
271    Id makeArrayDebugType(Id const baseType, Id const componentCount);
272    Id makeVectorDebugType(Id const baseType, int const componentCount);
273    Id makeMatrixDebugType(Id const vectorType, int const vectorCount, bool columnMajor = true);
274    Id makeMemberDebugType(Id const memberType, StructMemberDebugInfo const& debugTypeLoc);
275    Id makeCompositeDebugType(std::vector<Id> const& memberTypes, std::vector<StructMemberDebugInfo> const& memberDebugInfo,
276                              char const* const name, NonSemanticShaderDebugInfoDebugCompositeType const tag);
277    Id makeOpaqueDebugType(char const* const name);
278    Id makeVectorIdDebugType(Id componentType, Id componentCount);
279    Id makeCooperativeMatrixDebugTypeKHR(Id componentType, Id scope, Id rows, Id cols, Id use);
280    Id makePointerDebugType(StorageClass storageClass, Id const baseType);
281    Id makeForwardPointerDebugType(StorageClass storageClass);
282    Id makeDebugSource(const Id fileName);
283    Id makeDebugCompilationUnit();
284    Id createDebugGlobalVariable(Id const type, char const*const name, Id const variable);
285    Id createDebugLocalVariable(Id type, char const*const name, size_t const argNumber = 0);
286    Id makeDebugExpression();
287    Id makeDebugDeclare(Id const debugLocalVariable, Id const pointer);
288    Id makeDebugValue(Id const debugLocalVariable, Id const value);
289    Id makeDebugFunctionType(Id returnType, const std::vector<Id>& paramTypes);
290    Id makeDebugFunction(Function* function, Id nameId, Id funcTypeId);
291    Id makeDebugLexicalBlock(uint32_t line, uint32_t column);
292    std::string unmangleFunctionName(std::string const& name) const;
293
294    // Initialize non-semantic debug information for a function, including those of:
295    // - The function definition
296    // - The function parameters
297    void setupFunctionDebugInfo(Function* function, const char* name, const std::vector<Id>& paramTypes,
298                                const std::vector<char const*>& paramNames);
299
300    // accelerationStructureNV type
301    Id makeAccelerationStructureType();
302    // rayQueryEXT type
303    Id makeRayQueryType();
304    // hitObjectNV type
305    Id makeHitObjectNVType();
306    // hitObjectEXT type
307    Id makeHitObjectEXTType();
308
309    // For querying about types.
310    Id getTypeId(Id resultId) const { return module.getTypeId(resultId); }
311    Id getDerefTypeId(Id resultId) const;
312    Op getOpCode(Id id) const { return module.getInstruction(id)->getOpCode(); }
313    Op getTypeClass(Id typeId) const { return getOpCode(typeId); }
314    Op getMostBasicTypeClass(Id typeId) const;
315    unsigned int getNumComponents(Id resultId) const { return getNumTypeComponents(getTypeId(resultId)); }
316    unsigned int getNumTypeConstituents(Id typeId) const;
317    unsigned int getNumTypeComponents(Id typeId) const { return getNumTypeConstituents(typeId); }
318    Id getScalarTypeId(Id typeId) const;
319    Id getContainedTypeId(Id typeId) const;
320    Id getContainedTypeId(Id typeId, int) const;
321    StorageClass getTypeStorageClass(Id typeId) const { return module.getStorageClass(typeId); }
322    ImageFormat getImageTypeFormat(Id typeId) const
323        { return (ImageFormat)module.getInstruction(typeId)->getImmediateOperand(6); }
324    Id getResultingAccessChainType() const;
325    Id getIdOperand(Id resultId, int idx) { return module.getInstruction(resultId)->getIdOperand(idx); }
326    Id getCooperativeVectorNumComponents(Id typeId) const { return module.getInstruction(typeId)->getIdOperand(1); }
327
328    bool isPointer(Id resultId)      const { return isPointerType(getTypeId(resultId)); }
329    bool isUntypedPointer(Id resultId) const
330    {
331        const Id tid = getTypeId(resultId);
332        // Expect that OpString have no type
333        if (tid == 0)
334            return false;
335        return isUntypedPointerType(tid);
336    }
337    bool isScalar(Id resultId)       const { return isScalarType(getTypeId(resultId)); }
338    bool isVector(Id resultId)       const { return isVectorType(getTypeId(resultId)); }
339    bool isMatrix(Id resultId)       const { return isMatrixType(getTypeId(resultId)); }
340    bool isCooperativeMatrix(Id resultId)const { return isCooperativeMatrixType(getTypeId(resultId)); }
341    bool isCooperativeVector(Id resultId)const { return isCooperativeVectorType(getTypeId(resultId)); }
342    bool isAggregate(Id resultId)    const { return isAggregateType(getTypeId(resultId)); }
343    bool isSampledImage(Id resultId) const { return isSampledImageType(getTypeId(resultId)); }
344    bool isTensorView(Id resultId)const { return isTensorViewType(getTypeId(resultId)); }
345
346    bool isBoolType(Id typeId)
347        { return groupedTypes[enumCast(Op::OpTypeBool)].size() > 0 && typeId == groupedTypes[enumCast(Op::OpTypeBool)].back()->getResultId(); }
348    bool isIntType(Id typeId)          const
349        { return getTypeClass(typeId) == Op::OpTypeInt && module.getInstruction(typeId)->getImmediateOperand(1) != 0; }
350    bool isUintType(Id typeId)         const
351        { return getTypeClass(typeId) == Op::OpTypeInt && module.getInstruction(typeId)->getImmediateOperand(1) == 0; }
352    bool isFloatType(Id typeId)        const { return getTypeClass(typeId) == Op::OpTypeFloat; }
353    bool isPointerType(Id typeId)      const { return getTypeClass(typeId) == Op::OpTypePointer; }
354    bool isUntypedPointerType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeUntypedPointerKHR; }
355    bool isScalarType(Id typeId)       const
356        { return getTypeClass(typeId) == Op::OpTypeFloat || getTypeClass(typeId) == Op::OpTypeInt ||
357          getTypeClass(typeId) == Op::OpTypeBool; }
358    bool isVectorType(Id typeId)       const { return getTypeClass(typeId) == Op::OpTypeVector; }
359    bool isMatrixType(Id typeId)       const { return getTypeClass(typeId) == Op::OpTypeMatrix; }
360    bool isStructType(Id typeId)       const { return getTypeClass(typeId) == Op::OpTypeStruct; }
361    bool isArrayType(Id typeId)        const { return getTypeClass(typeId) == Op::OpTypeArray; }
362    bool isCooperativeMatrixType(Id typeId)const
363    {
364        return getTypeClass(typeId) == Op::OpTypeCooperativeMatrixKHR || getTypeClass(typeId) == Op::OpTypeCooperativeMatrixNV;
365    }
366    bool isTensorViewType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeTensorViewNV; }
367    bool isCooperativeVectorType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeCooperativeVectorNV; }
368    bool isTensorTypeARM(Id typeId)    const { return getTypeClass(typeId) == Op::OpTypeTensorARM; }
369    bool isAggregateType(Id typeId)    const
370        { return isArrayType(typeId) || isStructType(typeId) || isCooperativeMatrixType(typeId); }
371    bool isImageType(Id typeId)        const { return getTypeClass(typeId) == Op::OpTypeImage; }
372    bool isSamplerType(Id typeId)      const { return getTypeClass(typeId) == Op::OpTypeSampler; }
373    bool isSampledImageType(Id typeId) const { return getTypeClass(typeId) == Op::OpTypeSampledImage; }
374    bool containsType(Id typeId, Op typeOp, unsigned int width) const;
375    bool containsPhysicalStorageBufferOrArray(Id typeId) const;
376
377    bool isConstantOpCode(Op opcode) const;
378    bool isSpecConstantOpCode(Op opcode) const;
379    bool isConstant(Id resultId) const { return isConstantOpCode(getOpCode(resultId)); }
380    bool isConstantScalar(Id resultId) const { return getOpCode(resultId) == Op::OpConstant; }
381    bool isSpecConstant(Id resultId) const { return isSpecConstantOpCode(getOpCode(resultId)); }
382    unsigned int getConstantScalar(Id resultId) const
383        { return module.getInstruction(resultId)->getImmediateOperand(0); }
384    StorageClass getStorageClass(Id resultId) const { return getTypeStorageClass(getTypeId(resultId)); }
385
386    bool isVariableOpCode(Op opcode) const { return opcode == Op::OpVariable; }
387    bool isVariable(Id resultId) const { return isVariableOpCode(getOpCode(resultId)); }
388    bool isGlobalStorage(Id resultId) const { return getStorageClass(resultId) != StorageClass::Function; }
389    bool isGlobalVariable(Id resultId) const { return isVariable(resultId) && isGlobalStorage(resultId); }
390    // See if a resultId is valid for use as an initializer.
391    bool isValidInitializer(Id resultId) const { return isConstant(resultId) || isGlobalVariable(resultId); }
392
393    int getScalarTypeWidth(Id typeId) const
394    {
395        Id scalarTypeId = getScalarTypeId(typeId);
396        assert(getTypeClass(scalarTypeId) == Op::OpTypeInt || getTypeClass(scalarTypeId) == Op::OpTypeFloat);
397        return module.getInstruction(scalarTypeId)->getImmediateOperand(0);
398    }
399
400    unsigned int getTypeNumColumns(Id typeId) const
401    {
402        assert(isMatrixType(typeId));
403        return getNumTypeConstituents(typeId);
404    }
405    unsigned int getNumColumns(Id resultId) const { return getTypeNumColumns(getTypeId(resultId)); }
406    unsigned int getTypeNumRows(Id typeId) const
407    {
408        assert(isMatrixType(typeId));
409        return getNumTypeComponents(getContainedTypeId(typeId));
410    }
411    unsigned int getNumRows(Id resultId) const { return getTypeNumRows(getTypeId(resultId)); }
412
413    Dim getTypeDimensionality(Id typeId) const
414    {
415        assert(isImageType(typeId));
416        return (Dim)module.getInstruction(typeId)->getImmediateOperand(1);
417    }
418    Id getImageType(Id resultId) const
419    {
420        Id typeId = getTypeId(resultId);
421        assert(isImageType(typeId) || isSampledImageType(typeId));
422        return isSampledImageType(typeId) ? module.getInstruction(typeId)->getIdOperand(0) : typeId;
423    }
424    bool isArrayedImageType(Id typeId) const
425    {
426        assert(isImageType(typeId));
427        return module.getInstruction(typeId)->getImmediateOperand(3) != 0;
428    }
429
430    // For making new constants (will return old constant if the requested one was already made).
431    Id makeNullConstant(Id typeId);
432    Id makeBoolConstant(bool b, bool specConstant = false);
433    Id makeIntConstant(Id typeId, unsigned value, bool specConstant);
434    Id makeInt64Constant(Id typeId, unsigned long long value, bool specConstant);
435    Id makeInt8Constant(int i, bool specConstant = false)
436        { return makeIntConstant(makeIntType(8),  (unsigned)i, specConstant); }
437    Id makeUint8Constant(unsigned u, bool specConstant = false)
438        { return makeIntConstant(makeUintType(8),           u, specConstant); }
439    Id makeInt16Constant(int i, bool specConstant = false)
440        { return makeIntConstant(makeIntType(16),  (unsigned)i, specConstant); }
441    Id makeUint16Constant(unsigned u, bool specConstant = false)
442        { return makeIntConstant(makeUintType(16),           u, specConstant); }
443    Id makeIntConstant(int i, bool specConstant = false)
444        { return makeIntConstant(makeIntType(32),  (unsigned)i, specConstant); }
445    Id makeUintConstant(unsigned u, bool specConstant = false)
446        { return makeIntConstant(makeUintType(32),           u, specConstant); }
447    Id makeUintConstant(Scope u, bool specConstant = false)
448        { return makeUintConstant((unsigned)u, specConstant); }
449    Id makeUintConstant(StorageClass u, bool specConstant = false)
450        { return makeUintConstant((unsigned)u, specConstant); }
451    Id makeUintConstant(MemorySemanticsMask u, bool specConstant = false)
452        { return makeUintConstant((unsigned)u, specConstant); }
453    Id makeUintConstant(SourceLanguage u, bool specConstant = false)
454        { return makeUintConstant((unsigned)u, specConstant); }
455    Id makeInt64Constant(long long i, bool specConstant = false)
456        { return makeInt64Constant(makeIntType(64),  (unsigned long long)i, specConstant); }
457    Id makeUint64Constant(unsigned long long u, bool specConstant = false)
458        { return makeInt64Constant(makeUintType(64),                     u, specConstant); }
459    Id makeFloatConstant(float f, bool specConstant = false);
460    Id makeDoubleConstant(double d, bool specConstant = false);
461    Id makeFloat16Constant(float f16, bool specConstant = false);
462    Id makeBFloat16Constant(float bf16, bool specConstant = false);
463    Id makeFloatE5M2Constant(float fe5m2, bool specConstant = false);
464    Id makeFloatE4M3Constant(float fe4m3, bool specConstant = false);
465    Id makeFloatE2M1Constant(float fe2m1, bool specConstant = false);
466    Id makeFloatE3M2Constant(float fe3m2, bool specConstant = false);
467    Id makeFloatE2M3Constant(float fe2m3, bool specConstant = false);
468    Id makeFloatUE8M0Constant(float fue8m0, bool specConstant = false);
469    Id makeFloatMXINT8Constant(float mxint8, bool specConstant = false);
470    Id makeFpConstant(Id type, double d, bool specConstant = false);
471
472    Id importNonSemanticShaderDebugInfoInstructions();
473    // Ensure the NonSemantic.Shader.DebugInfo import string names at least `version`.
474    // If the import instruction already exists, its name is patched in place.
475    // If it has not been created yet, importNonSemanticShaderDebugInfoInstructions()
476    // will use the updated version when it runs.
477    void requireNonSemanticShaderDebugInfoVersion(unsigned version);
478
479    // Turn the array of constants into a proper spv constant of the requested type.
480    Id makeCompositeConstant(Id type, const std::vector<Id>& comps, bool specConst = false);
481
482    // Methods for adding information outside the CFG.
483    Instruction* addEntryPoint(ExecutionModel, Function*, const char* name);
484    void addExecutionMode(Function*, ExecutionMode mode, int value1 = -1, int value2 = -1, int value3 = -1);
485    void addExecutionMode(Function*, ExecutionMode mode, const std::vector<unsigned>& literals);
486    void addExecutionModeId(Function*, ExecutionMode mode, const std::vector<Id>& operandIds);
487    void addName(Id, const char* name);
488    void addMemberName(Id, int member, const char* name);
489    void addDecoration(Id, Decoration, int num = -1);
490    void addDecoration(Id, Decoration, const char*);
491    void addDecoration(Id, Decoration, const std::vector<unsigned>& literals);
492    void addDecoration(Id, Decoration, const std::vector<const char*>& strings);
493    void addLinkageDecoration(Id id, const char* name, spv::LinkageType linkType);
494    void addDecorationId(Id id, Decoration, Id idDecoration);
495    void addDecorationId(Id id, Decoration, const std::vector<Id>& operandIds);
496    void addMemberDecoration(Id, unsigned int member, Decoration, int num = -1);
497    void addMemberDecoration(Id, unsigned int member, Decoration, const char*);
498    void addMemberDecoration(Id, unsigned int member, Decoration, const std::vector<unsigned>& literals);
499    void addMemberDecoration(Id, unsigned int member, Decoration, const std::vector<const char*>& strings);
500    void addMemberDecorationIdEXT(Id, unsigned int member, Decoration, const std::vector<unsigned>& operands);
501
502    // At the end of what block do the next create*() instructions go?
503    // Also reset current last DebugScope and current source line to unknown
504    void setBuildPoint(Block* bp) {
505        buildPoint = bp;
506        descHeapShiftedBaseCache.clear();
507        dirtyLineTracker = true;
508        dirtyScopeTracker = true;
509    }
510    Block* getBuildPoint() const { return buildPoint; }
511
512    // Append an instruction to the end of the current build point.
513    // Optionally, additional debug info instructions may also be prepended.
514    void addInstruction(std::unique_ptr<Instruction> inst);
515
516    // Append an instruction to the end of the current build point without prepending any debug instructions.
517    // This is useful for insertion of some debug info instructions themselves or some control flow instructions
518    // that are attached to its predecessor instruction.
519    void addInstructionNoDebugInfo(std::unique_ptr<Instruction> inst);
520
521    // Make the entry-point function. The returned pointer is only valid
522    // for the lifetime of this builder.
523    Function* makeEntryPoint(const char*);
524
525    // Make a shader-style function, and create its entry block if entry is non-zero.
526    // Return the function, pass back the entry.
527    // The returned pointer is only valid for the lifetime of this builder.
528    Function* makeFunctionEntry(Decoration precision, Id returnType, const char* name, LinkageType linkType,
529                                const std::vector<Id>& paramTypes,
530                                const std::vector<std::vector<Decoration>>& precisions, Block** entry = nullptr);
531
532    // Create a return. An 'implicit' return is one not appearing in the source
533    // code.  In the case of an implicit return, no post-return block is inserted.
534    void makeReturn(bool implicit, Id retVal = 0);
535
536    // Initialize state and generate instructions for new lexical scope
537    void enterLexicalBlock(uint32_t line, uint32_t column);
538
539    // Set state and generate instructions to exit current lexical scope
540    void leaveLexicalBlock();
541
542    // Prepare builder for generation of instructions for a function.
543    void enterFunction(Function const* function);
544
545    // Generate all the code needed to finish up a function.
546    void leaveFunction();
547
548    // Create block terminator instruction for certain statements like
549    // discard, terminate-invocation, terminateRayEXT, or ignoreIntersectionEXT
550    void makeStatementTerminator(spv::Op opcode, const char *name);
551
552    // Create block terminator instruction for statements that have input operands
553    // such as OpEmitMeshTasksEXT
554    void makeStatementTerminator(spv::Op opcode, const std::vector<Id>& operands, const char* name);
555
556    // Create a global/local constant. Because OpConstant is automatically emitted by getting the constant
557    // ids, this function only handles debug info.
558    void createConstVariable(Id type, const char* name, Id constant, bool isGlobal);
559
560    // Create a global or function local or IO variable.
561    Id createVariable(Decoration precision, StorageClass storageClass, Id type, const char* name = nullptr,
562        Id initializer = NoResult, bool const compilerGenerated = true);
563
564    // Create an untyped global or function local or IO variable.
565    Id createUntypedVariable(Decoration precision, StorageClass storageClass, const char* name = nullptr,
566                             Id dataType = NoResult, Id initializer = NoResult);
567
568    // Create an intermediate with an undefined value.
569    Id createUndefined(Id type);
570
571    // Create load/store instruction with a remapped descriptor heap base.
572    Instruction* createDescHeapLoadStoreBaseRemap(Id base, Op op);
573
574    // Store into an Id and return the l-value
575    void createStore(Id rValue, Id lValue, spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMask::MaskNone,
576        spv::Scope scope = spv::Scope::Max, unsigned int alignment = 0);
577
578    // Load from an Id and return it
579    Id createLoad(Id lValue, spv::Decoration precision,
580        spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMask::MaskNone,
581        spv::Scope scope = spv::Scope::Max, unsigned int alignment = 0);
582
583    // Create an OpAccessChain instruction
584    Id createAccessChain(StorageClass, Id base, const std::vector<Id>& offsets);
585
586    // Create an OpUntypedAccessChainKHR instruction
587    Id createUntypedAccessChain(Id resultType, Id base, const std::vector<Id>& offsets, Id resultId = NoResult);
588
589    // Create an OpArrayLength instruction
590    Id createArrayLength(Id base, unsigned int member, unsigned int bits);
591
592    // Create an OpCooperativeMatrixLengthKHR instruction
593    Id createCooperativeMatrixLengthKHR(Id type);
594    // Create an OpCooperativeMatrixLengthNV instruction
595    Id createCooperativeMatrixLengthNV(Id type);
596
597    // Create an OpCompositeExtract instruction
598    Id createCompositeExtract(Id composite, Id typeId, unsigned index);
599    Id createCompositeExtract(Id composite, Id typeId, const std::vector<unsigned>& indexes);
600    Id createCompositeInsert(Id object, Id composite, Id typeId, unsigned index);
601    Id createCompositeInsert(Id object, Id composite, Id typeId, const std::vector<unsigned>& indexes);
602
603    Id createVectorExtractDynamic(Id vector, Id typeId, Id componentIndex);
604    Id createVectorInsertDynamic(Id vector, Id typeId, Id component, Id componentIndex);
605
606    void createNoResultOp(Op);
607    void createNoResultOp(Op, Id operand);
608    void createNoResultOp(Op, const std::vector<Id>& operands);
609    void createNoResultOp(Op, const std::vector<IdImmediate>& operands);
610    void createControlBarrier(Scope execution, Scope memory, MemorySemanticsMask);
611    void createMemoryBarrier(Scope executionScope, MemorySemanticsMask memorySemantics);
612    Id createUnaryOp(Op, Id typeId, Id operand);
613    Id createBinOp(Op, Id typeId, Id operand1, Id operand2);
614    Id createTriOp(Op, Id typeId, Id operand1, Id operand2, Id operand3);
615    Id createOp(Op, Id typeId, const std::vector<Id>& operands);
616    Id createOp(Op, Id typeId, const std::vector<IdImmediate>& operands);
617    Id createConstData(Op opCode, Id typeId, const std::vector<const char*> operands);
618    Id createFunctionCall(spv::Function*, const std::vector<spv::Id>&);
619    Id createSpecConstantOp(Op, Id typeId, const std::vector<spv::Id>& operands, const std::vector<unsigned>& literals);
620    Id createSpecConstantAlignTo(Id value, Id alignment);
621    Id createSpecConstantSelectMax(Id lhs, Id rhs);
622
623    // Take an rvalue (source) and a set of channels to extract from it to
624    // make a new rvalue, which is returned.
625    Id createRvalueSwizzle(Decoration precision, Id typeId, Id source, const std::vector<unsigned>& channels);
626
627    // Take a copy of an lvalue (target) and a source of components, and set the
628    // source components into the lvalue where the 'channels' say to put them.
629    // An updated version of the target is returned.
630    // (No true lvalue or stores are used.)
631    Id createLvalueSwizzle(Id typeId, Id target, Id source, const std::vector<unsigned>& channels);
632
633    // If both the id and precision are valid, the id
634    // gets tagged with the requested precision.
635    // The passed in id is always the returned id, to simplify use patterns.
636    Id setPrecision(Id id, Decoration precision)
637    {
638        if (precision != NoPrecision && id != NoResult)
639            addDecoration(id, precision);
640
641        return id;
642    }
643
644    // Can smear a scalar to a vector for the following forms:
645    //   - promoteScalar(scalar, vector)  // smear scalar to width of vector
646    //   - promoteScalar(vector, scalar)  // smear scalar to width of vector
647    //   - promoteScalar(pointer, scalar) // smear scalar to width of what pointer points to
648    //   - promoteScalar(scalar, scalar)  // do nothing
649    // Other forms are not allowed.
650    //
651    // Generally, the type of 'scalar' does not need to be the same type as the components in 'vector'.
652    // The type of the created vector is a vector of components of the same type as the scalar.
653    //
654    // Note: One of the arguments will change, with the result coming back that way rather than
655    // through the return value.
656    void promoteScalar(Decoration precision, Id& left, Id& right);
657
658    // Make a value by smearing the scalar to fill the type.
659    // vectorType should be the correct type for making a vector of scalarVal.
660    // (No conversions are done.)
661    Id smearScalar(Decoration precision, Id scalarVal, Id vectorType);
662
663    // Create a call to a built-in function.
664    Id createBuiltinCall(Id resultType, Id builtins, int entryPoint, const std::vector<Id>& args);
665
666    // List of parameters used to create a texture operation
667    struct TextureParameters {
668        Id sampler;
669        Id coords;
670        Id bias;
671        Id lod;
672        Id Dref;
673        Id offset;
674        Id offsets;
675        Id gradX;
676        Id gradY;
677        Id sample;
678        Id component;
679        Id texelOut;
680        Id lodClamp;
681        Id granularity;
682        Id coarse;
683        bool nonprivate;
684        bool volatil;
685        bool nontemporal;
686    };
687
688    // Select the correct texture operation based on all inputs, and emit the correct instruction
689    Id createTextureCall(Decoration precision, Id resultType, bool sparse, bool fetch, bool proj, bool gather,
690        bool noImplicit, const TextureParameters&, ImageOperandsMask);
691
692    // Emit the OpTextureQuery* instruction that was passed in.
693    // Figure out the right return value and type, and return it.
694    Id createTextureQueryCall(Op, const TextureParameters&, bool isUnsignedResult);
695
696    Id createSamplePositionCall(Decoration precision, Id, Id);
697
698    Id createBitFieldExtractCall(Decoration precision, Id, Id, Id, bool isSigned);
699    Id createBitFieldInsertCall(Decoration precision, Id, Id, Id, Id);
700
701    // Reduction comparison for composites:  For equal and not-equal resulting in a scalar.
702    Id createCompositeCompare(Decoration precision, Id, Id, bool /* true if for equal, false if for not-equal */);
703
704    // OpCompositeConstruct
705    Id createCompositeConstruct(Id typeId, const std::vector<Id>& constituents);
706
707    // vector or scalar constructor
708    Id createConstructor(Decoration precision, const std::vector<Id>& sources, Id resultTypeId);
709
710    // matrix constructor
711    Id createMatrixConstructor(Decoration precision, const std::vector<Id>& sources, Id constructee);
712
713    // coopmat conversion
714    Id createCooperativeMatrixConversion(Id typeId, Id source);
715    Id createCooperativeMatrixReduce(Op opcode, Id typeId, Id source, unsigned int mask, Id func);
716    Id createCooperativeMatrixPerElementOp(Id typeId, const std::vector<Id>& operands);
717
718    // Helper to use for building nested control flow with if-then-else.
719    class If {
720    public:
721        If(Id condition, SelectionControlMask ctrl, Builder& builder);
722        ~If() {}
723
724        void makeBeginElse();
725        void makeEndIf();
726
727    private:
728        If(const If&);
729        If& operator=(If&);
730
731        Builder& builder;
732        Id condition;
733        SelectionControlMask control;
734        Function* function;
735        Block* headerBlock;
736        Block* thenBlock;
737        Block* elseBlock;
738        Block* mergeBlock;
739    };
740
741    // Make a switch statement.  A switch has 'numSegments' of pieces of code, not containing
742    // any case/default labels, all separated by one or more case/default labels.  Each possible
743    // case value v is a jump to the caseValues[v] segment.  The defaultSegment is also in this
744    // number space.  How to compute the value is given by 'condition', as in switch(condition).
745    //
746    // The SPIR-V Builder will maintain the stack of post-switch merge blocks for nested switches.
747    //
748    // Use a defaultSegment < 0 if there is no default segment (to branch to post switch).
749    //
750    // Returns the right set of basic blocks to start each code segment with, so that the caller's
751    // recursion stack can hold the memory for it.
752    //
753    void makeSwitch(Id condition, SelectionControlMask control, int numSegments, const std::vector<int>& caseValues,
754                    const std::vector<int>& valueToSegment, int defaultSegment, std::vector<Block*>& segmentBB);
755
756    // Add a branch to the innermost switch's merge block.
757    void addSwitchBreak(bool implicit);
758
759    // Move to the next code segment, passing in the return argument in makeSwitch()
760    void nextSwitchSegment(std::vector<Block*>& segmentBB, int segment);
761
762    // Finish off the innermost switch.
763    void endSwitch(std::vector<Block*>& segmentBB);
764
765    struct LoopBlocks {
766        LoopBlocks(Block& head, Block& body, Block& merge, Block& continue_target) :
767            head(head), body(body), merge(merge), continue_target(continue_target) { }
768        Block &head, &body, &merge, &continue_target;
769    private:
770        LoopBlocks();
771        LoopBlocks& operator=(const LoopBlocks&) = delete;
772    };
773
774    // Start a new loop and prepare the builder to generate code for it.  Until
775    // closeLoop() is called for this loop, createLoopContinue() and
776    // createLoopExit() will target its corresponding blocks.
777    LoopBlocks& makeNewLoop();
778
779    // Create a new block in the function containing the build point.  Memory is
780    // owned by the function object.
781    Block& makeNewBlock();
782
783    // Add a branch to the continue_target of the current (innermost) loop.
784    void createLoopContinue();
785
786    // Add an exit (e.g. "break") from the innermost loop that we're currently
787    // in.
788    void createLoopExit();
789
790    // Close the innermost loop that you're in
791    void closeLoop();
792
793    //
794    // Access chain design for an R-Value vs. L-Value:
795    //
796    // There is a single access chain the builder is building at
797    // any particular time.  Such a chain can be used to either to a load or
798    // a store, when desired.
799    //
800    // Expressions can be r-values, l-values, or both, or only r-values:
801    //    a[b.c].d = ....  // l-value
802    //    ... = a[b.c].d;  // r-value, that also looks like an l-value
803    //    ++a[b.c].d;      // r-value and l-value
804    //    (x + y)[2];      // r-value only, can't possibly be l-value
805    //
806    // Computing an r-value means generating code.  Hence,
807    // r-values should only be computed when they are needed, not speculatively.
808    //
809    // Computing an l-value means saving away information for later use in the compiler,
810    // no code is generated until the l-value is later dereferenced.  It is okay
811    // to speculatively generate an l-value, just not okay to speculatively dereference it.
812    //
813    // The base of the access chain (the left-most variable or expression
814    // from which everything is based) can be set either as an l-value
815    // or as an r-value.  Most efficient would be to set an l-value if one
816    // is available.  If an expression was evaluated, the resulting r-value
817    // can be set as the chain base.
818    //
819    // The users of this single access chain can save and restore if they
820    // want to nest or manage multiple chains.
821    //
822
823    struct AccessChain {
824        Id base;                       // for l-values, pointer to the base object, for r-values, the base object
825        std::vector<Id> indexChain;
826        Id instr;                      // cache the instruction that generates this access chain
827        std::vector<unsigned> swizzle; // each std::vector element selects the next GLSL component number
828        Id component;                  // a dynamic component index, can coexist with a swizzle,
829                                       // done after the swizzle, NoResult if not present
830        Id preSwizzleBaseType;         // dereferenced type, before swizzle or component is applied;
831                                       // NoType unless a swizzle or component is present
832        bool isRValue;                 // true if 'base' is an r-value, otherwise, base is an l-value
833        unsigned int alignment;        // bitwise OR of alignment values passed in. Accumulates worst alignment.
834                                       // Only tracks base and (optional) component selection alignment.
835
836        struct DescHeapInfo {
837            Id descHeapBaseTy;                  // for descriptor heap, record its base data type.
838            Id descHeapBaseOffset;              // byte offset applied to the heap base before descriptor lookup.
839            std::vector<Id> descHeapIndexChain;
840            Id descTy;                          // for target resource type
841            StorageClass descStorageClass;      // for descriptor heap, record its basic storage class.
842            bool descReadonly;                  // for decorating OpBufferPointerEXT results.
843            bool descWriteonly;                 // for decorating OpBufferPointerEXT results.
844            std::vector<Instruction*> descHeapInstId;
845                                                // for descriptor heap, record its data type for loading/store results.
846        };
847        DescHeapInfo descHeapInfo;
848
849        // Accumulate whether anything in the chain of structures has coherent decorations.
850        struct CoherentFlags {
851            CoherentFlags() { clear(); }
852            bool isVolatile() const { return volatil; }
853            bool isNonUniform() const { return nonUniform; }
854            bool anyCoherent() const {
855                return coherent || devicecoherent || queuefamilycoherent || workgroupcoherent ||
856                    subgroupcoherent || shadercallcoherent;
857            }
858
859            unsigned coherent : 1;
860            unsigned devicecoherent : 1;
861            unsigned queuefamilycoherent : 1;
862            unsigned workgroupcoherent : 1;
863            unsigned subgroupcoherent : 1;
864            unsigned shadercallcoherent : 1;
865            unsigned nonprivate : 1;
866            unsigned volatil : 1;
867            unsigned nontemporal : 1;
868            unsigned isImage : 1;
869            unsigned nonUniform : 1;
870
871            void clear() {
872                coherent = 0;
873                devicecoherent = 0;
874                queuefamilycoherent = 0;
875                workgroupcoherent = 0;
876                subgroupcoherent = 0;
877                shadercallcoherent = 0;
878                nonprivate = 0;
879                volatil = 0;
880                nontemporal = 0;
881                isImage = 0;
882                nonUniform = 0;
883            }
884
885            CoherentFlags operator |=(const CoherentFlags &other) {
886                coherent |= other.coherent;
887                devicecoherent |= other.devicecoherent;
888                queuefamilycoherent |= other.queuefamilycoherent;
889                workgroupcoherent |= other.workgroupcoherent;
890                subgroupcoherent |= other.subgroupcoherent;
891                shadercallcoherent |= other.shadercallcoherent;
892                nonprivate |= other.nonprivate;
893                volatil |= other.volatil;
894                nontemporal = other.nontemporal;
895                isImage |= other.isImage;
896                nonUniform |= other.nonUniform;
897                return *this;
898            }
899        };
900        CoherentFlags coherentFlags;
901    };
902
903    //
904    // the SPIR-V builder maintains a single active chain that
905    // the following methods operate on
906    //
907
908    // for external save and restore
909    AccessChain getAccessChain() { return accessChain; }
910    void setAccessChain(AccessChain newChain) { accessChain = newChain; }
911
912    // for EXT_descriptor_heap and EXT_structured_descriptor_heap
913    Id getAccessChainDescHeapBaseType() const { return accessChain.descHeapInfo.descHeapBaseTy; }
914    void setAccessChainDescHeapBaseType(Id baseType) { accessChain.descHeapInfo.descHeapBaseTy = baseType; }
915    void setAccessChainDescHeapBaseOffset(Id baseOffset) { accessChain.descHeapInfo.descHeapBaseOffset = baseOffset; }
916    const std::vector<Id>& getAccessChainDescHeapIndexChain() const { return accessChain.descHeapInfo.descHeapIndexChain; }
917    void accessChainPushDescHeapIndex(Id index) { accessChain.descHeapInfo.descHeapIndexChain.push_back(index); }
918    bool hasAccessChainIndex() const { return !accessChain.indexChain.empty(); }
919    void moveAccessChainIndexToDescHeapIndexChain()
920    {
921        assert(accessChain.indexChain.size() == 1);
922        accessChainPushDescHeapIndex(accessChain.indexChain.back());
923        accessChain.indexChain.pop_back();
924    }
925    void setAccessChainDescHeapDescriptorType(Id descTy, StorageClass storageClass, bool readonly, bool writeonly)
926    {
927        accessChain.descHeapInfo.descTy = descTy;
928        accessChain.descHeapInfo.descStorageClass = storageClass;
929        accessChain.descHeapInfo.descReadonly = readonly;
930        accessChain.descHeapInfo.descWriteonly = writeonly;
931    }
932
933    // clear accessChain
934    void clearAccessChain();
935
936    Id createDescHeapAccessChain();
937    Id createConstantSizeOfEXT(Id typeId);
938
939    // set new base as an l-value base
940    void setAccessChainLValue(Id lValue)
941    {
942        assert(isPointer(lValue) || isUntypedPointer(lValue));
943        accessChain.base = lValue;
944    }
945
946    // set new base value as an r-value
947    void setAccessChainRValue(Id rValue)
948    {
949        accessChain.isRValue = true;
950        accessChain.base = rValue;
951    }
952
953    // push offset onto the end of the chain
954    void accessChainPush(Id offset, AccessChain::CoherentFlags coherentFlags, unsigned int alignment)
955    {
956        accessChain.indexChain.push_back(offset);
957        accessChain.coherentFlags |= coherentFlags;
958        accessChain.alignment |= alignment;
959    }
960
961    // push new swizzle onto the end of any existing swizzle, merging into a single swizzle
962    void accessChainPushSwizzle(std::vector<unsigned>& swizzle, Id preSwizzleBaseType,
963        AccessChain::CoherentFlags coherentFlags, unsigned int alignment);
964
965    // push a dynamic component selection onto the access chain, only applicable with a
966    // non-trivial swizzle or no swizzle
967    void accessChainPushComponent(Id component, Id preSwizzleBaseType, AccessChain::CoherentFlags coherentFlags,
968        unsigned int alignment)
969    {
970        if (accessChain.swizzle.size() != 1) {
971            accessChain.component = component;
972            if (accessChain.preSwizzleBaseType == NoType)
973                accessChain.preSwizzleBaseType = preSwizzleBaseType;
974        }
975        accessChain.coherentFlags |= coherentFlags;
976        accessChain.alignment |= alignment;
977    }
978
979    // use accessChain and swizzle to store value
980    void accessChainStore(Id rvalue, Decoration nonUniform,
981        spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMask::MaskNone,
982        spv::Scope scope = spv::Scope::Max, unsigned int alignment = 0);
983
984    // use accessChain and swizzle to load an r-value
985    Id accessChainLoad(Decoration precision, Decoration l_nonUniform, Decoration r_nonUniform, Id ResultType,
986        spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMask::MaskNone, spv::Scope scope = spv::Scope::Max,
987            unsigned int alignment = 0);
988
989    // Return whether or not the access chain can be represented in SPIR-V
990    // as an l-value.
991    // E.g., a[3].yx cannot be, while a[3].y and a[3].y[x] can be.
992    bool isSpvLvalue() const { return accessChain.swizzle.size() <= 1; }
993
994    // get the direct pointer for an l-value
995    Id accessChainGetLValue();
996
997    // Get the inferred SPIR-V type of the result of the current access chain,
998    // based on the type of the base and the chain of dereferences.
999    Id accessChainGetInferredType();
1000
1001    // Add capabilities, extensions, remove unneeded decorations, etc.,
1002    // based on the resulting SPIR-V.
1003    void postProcess(bool compileOnly);
1004
1005    // Prune unreachable blocks in the CFG and remove unneeded decorations.
1006    void postProcessCFG();
1007
1008    // Add capabilities, extensions based on instructions in the module.
1009    void postProcessFeatures();
1010    // Hook to visit each instruction in a block in a function
1011    void postProcess(Instruction&);
1012    // Hook to visit each non-32-bit sized float/int operation in a block.
1013    void postProcessType(const Instruction&, spv::Id typeId);
1014    // move OpSampledImage instructions to be next to their users.
1015    void postProcessSamplers();
1016
1017    void dump(std::vector<unsigned int>&) const;
1018
1019    // Add a branch to the target block.
1020    // If set implicit, the branch instruction shouldn't have debug source location.
1021    void createBranch(bool implicit, Block* block);
1022    void createConditionalBranch(Id condition, Block* thenBlock, Block* elseBlock);
1023    void createLoopMerge(Block* mergeBlock, Block* continueBlock, LoopControlMask control,
1024        const std::vector<unsigned int>& operands);
1025
1026    // Sets to generate opcode for specialization constants.
1027    void setToSpecConstCodeGenMode() { generatingOpCodeForSpecConst = true; }
1028    // Sets to generate opcode for non-specialization constants (normal mode).
1029    void setToNormalCodeGenMode() { generatingOpCodeForSpecConst = false; }
1030    // Check if the builder is generating code for spec constants.
1031    bool isInSpecConstCodeGenMode() { return generatingOpCodeForSpecConst; }
1032
1033    void setUseReplicatedComposites(bool use) { useReplicatedComposites = use; }
1034
1035private:
1036    // Helper to get size of a scalar (in bytes)
1037    unsigned int postProcessGetLargestScalarSize(const Instruction& type);
1038
1039protected:
1040    Id findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned value);
1041    Id findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned v1, unsigned v2);
1042    Id findCompositeConstant(Op typeClass, Op opcode, Id typeId, const std::vector<Id>& comps, size_t numMembers);
1043    Id findStructConstant(Id typeId, const std::vector<Id>& comps);
1044    Id collapseAccessChain();
1045    Id getOrCreateDescHeapByteArrayType();
1046    void remapDynamicSwizzle();
1047    void transferAccessChainSwizzle(bool dynamic);
1048    void simplifyAccessChainSwizzle();
1049    void createAndSetNoPredecessorBlock(const char*);
1050    void createSelectionMerge(Block* mergeBlock, SelectionControlMask control);
1051    void dumpSourceInstructions(std::vector<unsigned int>&) const;
1052    void dumpSourceInstructions(const spv::Id fileId, const std::string& text, std::vector<unsigned int>&) const;
1053    template <class Range> void dumpInstructions(std::vector<unsigned int>& out, const Range& instructions) const;
1054    void dumpModuleProcesses(std::vector<unsigned int>&) const;
1055    spv::MemoryAccessMask sanitizeMemoryAccessForStorageClass(spv::MemoryAccessMask memoryAccess, StorageClass sc)
1056        const;
1057    struct DecorationInstructionLessThan {
1058        bool operator()(const std::unique_ptr<Instruction>& lhs, const std::unique_ptr<Instruction>& rhs) const;
1059    };
1060    template <typename SpvUtilsType>
1061    Id makeFloatConstantHelper(float f, Id typeId, bool specConstant);
1062
1063    unsigned int spvVersion;     // the version of SPIR-V to emit in the header
1064    SourceLanguage sourceLang;
1065    int sourceVersion;
1066    spv::Id nonSemanticShaderCompilationUnitId {0};
1067    spv::Id nonSemanticShaderDebugInfo {0};
1068    // Pointer to the OpExtInstImport instruction for NonSemantic.Shader.DebugInfo.
1069    // Kept so requireNonSemanticShaderDebugInfoVersion() can patch the name in place.
1070    Instruction* nonSemanticShaderDebugInfoImportInst {nullptr};
1071    // Spec version encoded in the NonSemantic.Shader.DebugInfo import name.
1072    // Defaults to 100. Promoted to N the first time a version-N opcode is emitted.
1073    unsigned int nonSemanticShaderDebugInfoVersion{100};
1074    spv::Id debugInfoNone {0};
1075    spv::Id debugExpression {0}; // Debug expression with zero operations.
1076    std::string sourceText;
1077
1078    // True if an new OpLine/OpDebugLine may need to be inserted. Either:
1079    // 1. The current debug location changed
1080    // 2. The current build point changed
1081    bool dirtyLineTracker;
1082    int currentLine = 0;
1083    // OpString id of the current file name. Always 0 if debug info is off.
1084    spv::Id currentFileId = 0;
1085    // OpString id of the main file name. Always 0 if debug info is off.
1086    spv::Id mainFileId = 0;
1087
1088    // True if an new OpDebugScope may need to be inserted. Either:
1089    // 1. A new lexical block is pushed
1090    // 2. The current build point changed
1091    bool dirtyScopeTracker;
1092    std::stack<spv::Id> currentDebugScopeId;
1093
1094    // This flag toggles tracking of debug info while building the SPIR-V.
1095    bool trackDebugInfo = false;
1096    // This flag toggles emission of SPIR-V debug instructions, like OpLine and OpSource.
1097    bool emitSpirvDebugInfo = false;
1098    // This flag toggles emission of Non-Semantic Debug extension debug instructions.
1099    bool emitNonSemanticShaderDebugInfo = false;
1100    bool restoreNonSemanticShaderDebugInfo = false;
1101    bool emitNonSemanticShaderDebugSource = false;
1102
1103    std::set<std::string> extensions;
1104    std::vector<const char*> sourceExtensions;
1105    std::vector<const char*> moduleProcesses;
1106    AddressingModel addressModel;
1107    MemoryModel memoryModel;
1108    std::set<spv::Capability> capabilities;
1109    int builderNumber;
1110    Module module;
1111    Block* buildPoint;
1112    Id uniqueId;
1113    Function* entryPointFunction;
1114    // This tracks the current function being built, or nullptr if not in a function.
1115    Function const* currentFunction { nullptr };
1116    bool generatingOpCodeForSpecConst;
1117    bool useReplicatedComposites { false };
1118    AccessChain accessChain;
1119
1120    // special blocks of instructions for output
1121    std::vector<std::unique_ptr<Instruction> > strings;
1122    std::vector<std::unique_ptr<Instruction> > imports;
1123    std::vector<std::unique_ptr<Instruction> > entryPoints;
1124    std::vector<std::unique_ptr<Instruction> > executionModes;
1125    std::vector<std::unique_ptr<Instruction> > names;
1126    std::set<std::unique_ptr<Instruction>, DecorationInstructionLessThan> decorations;
1127    std::vector<std::unique_ptr<Instruction> > constantsTypesGlobals;
1128    std::vector<std::unique_ptr<Instruction> > externals;
1129    std::vector<std::unique_ptr<Function> > functions;
1130
1131    // not output, internally used for quick & dirty canonical (unique) creation
1132
1133    // Key for scalar constants (handles both 32-bit and 64-bit)
1134    struct ScalarConstantKey {
1135        unsigned int typeClass;  // OpTypeInt, OpTypeFloat, OpTypeBool
1136        unsigned int opcode;     // OpConstant, OpSpecConstant, OpConstantTrue, etc.
1137        Id typeId;               // The specific type
1138        unsigned value1;         // First operand (or only operand)
1139        unsigned value2;         // Second operand (0 for single-operand constants)
1140
1141        bool operator==(const ScalarConstantKey& other) const {
1142            return typeClass == other.typeClass &&
1143                   opcode == other.opcode &&
1144                   typeId == other.typeId &&
1145                   value1 == other.value1 &&
1146                   value2 == other.value2;
1147        }
1148    };
1149
1150    struct ScalarConstantKeyHash {
1151        // 64/32 bit mix function from MurmurHash3
1152        inline std::size_t hash_mix(std::size_t h) const {
1153            if constexpr (sizeof(std::size_t) == 8) {
1154                h ^= h >> 33;
1155                h *= UINT64_C(0xff51afd7ed558ccd);
1156                h ^= h >> 33;
1157                h *= UINT64_C(0xc4ceb9fe1a85ec53);
1158                h ^= h >> 33;
1159                return h;
1160            } else {
1161                h ^= h >> 16;
1162                h *= UINT32_C(0x85ebca6b);
1163                h ^= h >> 13;
1164                h *= UINT32_C(0xc2b2ae35);
1165                h ^= h >> 16;
1166                return h;
1167            }
1168        }
1169
1170        // Hash combine from boost
1171        inline std::size_t hash_combine(std::size_t seed, std::size_t v) const {
1172            return hash_mix(seed + 0x9e3779b9 + v);
1173        }
1174        
1175        std::size_t operator()(const ScalarConstantKey& k) const {
1176            size_t hash1 = hash_combine(std::hash<unsigned>{}(k.typeClass), std::hash<unsigned>{}(k.opcode));
1177            size_t hash2 = hash_combine(std::hash<Id>{}(k.value1), std::hash<unsigned>{}(k.value2));
1178            size_t hash3 = hash_combine(hash1, hash2);
1179            return hash_combine(hash3, std::hash<unsigned>{}(k.typeId));
1180        }
1181    };
1182
1183    // map type opcodes to constant inst.
1184    std::unordered_map<unsigned int, std::vector<Instruction*>> groupedCompositeConstants;
1185    // map struct-id to constant instructions
1186    std::unordered_map<unsigned int, std::vector<Instruction*>> groupedStructConstants;
1187    // map type opcodes to type instructions
1188    std::unordered_map<unsigned int, std::vector<Instruction*>> groupedTypes;
1189    // map type opcodes to debug type instructions
1190    std::unordered_map<unsigned int, std::vector<Instruction*>> groupedDebugTypes;
1191    // list of OpConstantNull instructions
1192    std::vector<Instruction*> nullConstants;
1193    // map scalar constants to result IDs
1194    std::unordered_map<ScalarConstantKey, Id, ScalarConstantKeyHash> groupedScalarConstantResultIDs;
1195    // map type ids to OpConstantSizeOfEXT result IDs
1196    std::unordered_map<Id, Id> constantSizeOfEXTIds;
1197
1198    // Descriptor heap shifted base cache.
1199    std::map<std::pair<Id, Id>, Id> descHeapShiftedBaseCache;
1200
1201    // Descriptor heap byte array type.
1202    Id descHeapByteArrayType;
1203
1204    // Track which types have explicit layouts, to avoid reusing in storage classes without layout.
1205    // Currently only tracks array types.
1206    std::unordered_set<unsigned int> explicitlyLaidOut;
1207
1208    // stack of switches
1209    std::stack<Block*> switchMerges;
1210
1211    // Our loop stack.
1212    std::stack<LoopBlocks> loops;
1213
1214    // map from strings to their string ids
1215    std::unordered_map<std::string, spv::Id> stringIds;
1216
1217    // map from include file name ids to their contents
1218    std::map<spv::Id, const std::string*> includeFiles;
1219
1220    // maps from OpTypeXXX id to DebugTypeXXX id
1221    std::unordered_map<spv::Id, spv::Id> debugTypeIdLookup;
1222
1223    // maps from OpFunction id to DebugFunction id
1224    std::unordered_map<spv::Id, spv::Id> debugFuncIdLookup;
1225
1226    // map from file name string id to DebugSource id
1227    std::unordered_map<spv::Id, spv::Id> debugSourceId;
1228
1229    // The stream for outputting warnings and errors.
1230    SpvBuildLogger* logger;
1231};  // end Builder class
1232
1233} // end spv namespace
1234
1235#endif // SpvBuilder_H