yum-mirror/glslang

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

Saqib KhanHandle spirv_literal operands in spirv_instruction with a set (#4454)c97e126b

main
197.4 KiB5372 linesraw
1//
2// Copyright (C) 2014-2015 LunarG, Inc.
3// Copyright (C) 2015-2018 Google, Inc.
4// Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
5//
6// All rights reserved.
7//
8// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
11//
12//    Redistributions of source code must retain the above copyright
13//    notice, this list of conditions and the following disclaimer.
14//
15//    Redistributions in binary form must reproduce the above
16//    copyright notice, this list of conditions and the following
17//    disclaimer in the documentation and/or other materials provided
18//    with the distribution.
19//
20//    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21//    contributors may be used to endorse or promote products derived
22//    from this software without specific prior written permission.
23//
24// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
36
37//
38// Helper for making SPIR-V IR.  Generally, this is documented in the header
39// SpvBuilder.h.
40//
41
42#include <cassert>
43#include <cstdlib>
44
45#include <unordered_set>
46#include <algorithm>
47
48#include "SpvBuilder.h"
49#include "spvUtil.h"
50#include "hex_float.h"
51
52#ifndef _WIN32
53    #include <cstdio>
54#endif
55
56namespace spv {
57
58Builder::Builder(unsigned int spvVersion, unsigned int magicNumber, SpvBuildLogger* buildLogger) :
59    spvVersion(spvVersion),
60    sourceLang(SourceLanguage::Unknown),
61    sourceVersion(0),
62    addressModel(AddressingModel::Logical),
63    memoryModel(MemoryModel::GLSL450),
64    builderNumber(magicNumber),
65    buildPoint(nullptr),
66    uniqueId(0),
67    entryPointFunction(nullptr),
68    generatingOpCodeForSpecConst(false),
69    descHeapByteArrayType(NoResult),
70    logger(buildLogger)
71{
72    clearAccessChain();
73}
74
75Builder::~Builder()
76{
77}
78
79Id Builder::import(const char* name)
80{
81    Instruction* import = new Instruction(getUniqueId(), NoType, Op::OpExtInstImport);
82    import->addStringOperand(name);
83    module.mapInstruction(import);
84
85    imports.push_back(std::unique_ptr<Instruction>(import));
86    return import->getResultId();
87}
88
89// For creating new groupedTypes (will return old type if the requested one was already made).
90Id Builder::makeVoidType()
91{
92    Instruction* type;
93    if (groupedTypes[enumCast(Op::OpTypeVoid)].size() == 0) {
94        Id typeId = getUniqueId();
95        type = new Instruction(typeId, NoType, Op::OpTypeVoid);
96        groupedTypes[enumCast(Op::OpTypeVoid)].push_back(type);
97        constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
98        module.mapInstruction(type);
99        // Core OpTypeVoid used for debug void type
100        if (emitNonSemanticShaderDebugInfo)
101            debugTypeIdLookup[typeId] = typeId;
102    } else
103        type = groupedTypes[enumCast(Op::OpTypeVoid)].back();
104
105    return type->getResultId();
106}
107
108Id Builder::makeBoolType()
109{
110    Instruction* type;
111    if (groupedTypes[enumCast(Op::OpTypeBool)].size() == 0) {
112        type = new Instruction(getUniqueId(), NoType, Op::OpTypeBool);
113        groupedTypes[enumCast(Op::OpTypeBool)].push_back(type);
114        constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
115        module.mapInstruction(type);
116
117        if (emitNonSemanticShaderDebugInfo) {
118            auto const debugResultId = makeBoolDebugType(32);
119            debugTypeIdLookup[type->getResultId()] = debugResultId;
120        }
121
122    } else
123        type = groupedTypes[enumCast(Op::OpTypeBool)].back();
124
125
126    return type->getResultId();
127}
128
129Id Builder::makeSamplerType(const char* debugName)
130{
131    Instruction* type;
132    if (groupedTypes[enumCast(Op::OpTypeSampler)].size() == 0) {
133        type = new Instruction(getUniqueId(), NoType, Op::OpTypeSampler);
134        groupedTypes[enumCast(Op::OpTypeSampler)].push_back(type);
135        constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
136        module.mapInstruction(type);
137    } else
138        type = groupedTypes[enumCast(Op::OpTypeSampler)].back();
139
140    if (emitNonSemanticShaderDebugInfo)
141    {
142        auto const debugResultId = makeOpaqueDebugType(debugName);
143        debugTypeIdLookup[type->getResultId()] = debugResultId;
144    }
145
146    return type->getResultId();
147}
148
149Id Builder::makePointer(StorageClass storageClass, Id pointee)
150{
151    // try to find it
152    Instruction* type;
153    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypePointer)].size(); ++t) {
154        type = groupedTypes[enumCast(Op::OpTypePointer)][t];
155        if (type->getImmediateOperand(0) == (unsigned)storageClass &&
156            type->getIdOperand(1) == pointee)
157            return type->getResultId();
158    }
159
160    // not found, make it
161    type = new Instruction(getUniqueId(), NoType, Op::OpTypePointer);
162    type->reserveOperands(2);
163    type->addImmediateOperand(storageClass);
164    type->addIdOperand(pointee);
165    groupedTypes[enumCast(Op::OpTypePointer)].push_back(type);
166    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
167    module.mapInstruction(type);
168
169    if (emitNonSemanticShaderDebugInfo) {
170        const Id debugResultId = makePointerDebugType(storageClass, pointee);
171        debugTypeIdLookup[type->getResultId()] = debugResultId;
172    }
173
174    return type->getResultId();
175}
176
177Id Builder::makeForwardPointer(StorageClass storageClass)
178{
179    // Caching/uniquifying doesn't work here, because we don't know the
180    // pointee type and there can be multiple forward pointers of the same
181    // storage type. Somebody higher up in the stack must keep track.
182    Instruction* type = new Instruction(getUniqueId(), NoType, Op::OpTypeForwardPointer);
183    type->addImmediateOperand(storageClass);
184    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
185    module.mapInstruction(type);
186
187    if (emitNonSemanticShaderDebugInfo) {
188        const Id debugResultId = makeForwardPointerDebugType(storageClass);
189        debugTypeIdLookup[type->getResultId()] = debugResultId;
190    }
191    return type->getResultId();
192}
193
194Id Builder::makeUntypedPointer(StorageClass storageClass, bool setBufferPointer)
195{
196    // try to find it
197    Instruction* type;
198    // both typeBufferEXT and UntypedPointer only contains storage class info.
199    spv::Op typeOp = setBufferPointer ? Op::OpTypeBufferEXT : Op::OpTypeUntypedPointerKHR;
200    for (int t = 0; t < (int)groupedTypes[enumCast(typeOp)].size(); ++t) {
201        type = groupedTypes[enumCast(typeOp)][t];
202        if (type->getImmediateOperand(0) == (unsigned)storageClass)
203            return type->getResultId();
204    }
205
206    // not found, make it
207    type = new Instruction(getUniqueId(), NoType, typeOp);
208    type->addImmediateOperand(storageClass);
209    groupedTypes[enumCast(typeOp)].push_back(type);
210    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
211    module.mapInstruction(type);
212    return type->getResultId();
213}
214
215Id Builder::makePointerFromForwardPointer(StorageClass storageClass, Id forwardPointerType, Id pointee)
216{
217    // try to find it
218    Instruction* type;
219    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypePointer)].size(); ++t) {
220        type = groupedTypes[enumCast(Op::OpTypePointer)][t];
221        if (type->getImmediateOperand(0) == (unsigned)storageClass &&
222            type->getIdOperand(1) == pointee)
223            return type->getResultId();
224    }
225
226    type = new Instruction(forwardPointerType, NoType, Op::OpTypePointer);
227    type->reserveOperands(2);
228    type->addImmediateOperand(storageClass);
229    type->addIdOperand(pointee);
230    groupedTypes[enumCast(Op::OpTypePointer)].push_back(type);
231    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
232    module.mapInstruction(type);
233
234    // If we are emitting nonsemantic debuginfo, we need to patch the debug pointer type
235    // that was emitted alongside the forward pointer, now that we have a pointee debug
236    // type for it to point to.
237    if (emitNonSemanticShaderDebugInfo) {
238        Instruction *debugForwardPointer = module.getInstruction(getDebugType(forwardPointerType));
239        assert(getDebugType(pointee));
240        debugForwardPointer->setIdOperand(2, getDebugType(pointee));
241    }
242
243    return type->getResultId();
244}
245
246Id Builder::makeIntegerType(int width, bool hasSign)
247{
248    // try to find it
249    Instruction* type;
250    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeInt)].size(); ++t) {
251        type = groupedTypes[enumCast(Op::OpTypeInt)][t];
252        if (type->getImmediateOperand(0) == (unsigned)width &&
253            type->getImmediateOperand(1) == (hasSign ? 1u : 0u))
254            return type->getResultId();
255    }
256
257    // not found, make it
258    type = new Instruction(getUniqueId(), NoType, Op::OpTypeInt);
259    type->reserveOperands(2);
260    type->addImmediateOperand(width);
261    type->addImmediateOperand(hasSign ? 1 : 0);
262    groupedTypes[enumCast(Op::OpTypeInt)].push_back(type);
263    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
264    module.mapInstruction(type);
265
266    // deal with capabilities
267    switch (width) {
268    case 8:
269    case 16:
270        // these are currently handled by storage-type declarations and post processing
271        break;
272    case 64:
273        addCapability(Capability::Int64);
274        break;
275    default:
276        break;
277    }
278
279    if (emitNonSemanticShaderDebugInfo)
280    {
281        auto const debugResultId = makeIntegerDebugType(width, hasSign);
282        debugTypeIdLookup[type->getResultId()] = debugResultId;
283    }
284
285    return type->getResultId();
286}
287
288Id Builder::makeFloatType(int width)
289{
290    // try to find it
291    Instruction* type;
292    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeFloat)].size(); ++t) {
293        type = groupedTypes[enumCast(Op::OpTypeFloat)][t];
294        if (type->getNumOperands() != 1) {
295            continue;
296        }
297        if (type->getImmediateOperand(0) == (unsigned)width)
298            return type->getResultId();
299    }
300
301    // not found, make it
302    type = new Instruction(getUniqueId(), NoType, Op::OpTypeFloat);
303    type->addImmediateOperand(width);
304    groupedTypes[enumCast(Op::OpTypeFloat)].push_back(type);
305    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
306    module.mapInstruction(type);
307
308    // deal with capabilities
309    switch (width) {
310    case 16:
311        // currently handled by storage-type declarations and post processing
312        break;
313    case 64:
314        addCapability(Capability::Float64);
315        break;
316    default:
317        break;
318    }
319
320    if (emitNonSemanticShaderDebugInfo)
321    {
322        auto const debugResultId = makeFloatDebugType(width);
323        debugTypeIdLookup[type->getResultId()] = debugResultId;
324    }
325
326    return type->getResultId();
327}
328
329Id Builder::makeBFloat16Type()
330{
331    // try to find it
332    Instruction* type;
333    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeFloat)].size(); ++t) {
334        type = groupedTypes[enumCast(Op::OpTypeFloat)][t];
335        if (type->getNumOperands() != 2) {
336            continue;
337        }
338        if (type->getImmediateOperand(0) == (unsigned)16 &&
339            type->getImmediateOperand(1) == FPEncoding::BFloat16KHR)
340            return type->getResultId();
341    }
342
343    // not found, make it
344    type = new Instruction(getUniqueId(), NoType, Op::OpTypeFloat);
345    type->addImmediateOperand(16);
346    type->addImmediateOperand(FPEncoding::BFloat16KHR);
347    groupedTypes[enumCast(Op::OpTypeFloat)].push_back(type);
348    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
349    module.mapInstruction(type);
350
351    addExtension(spv::E_SPV_KHR_bfloat16);
352    addCapability(Capability::BFloat16TypeKHR);
353
354    if (emitNonSemanticShaderDebugInfo) {
355        auto const debugResultId = makeFloatDebugType(16, makeUintConstant((unsigned)FPEncoding::BFloat16KHR));
356        debugTypeIdLookup[type->getResultId()] = debugResultId;
357    }
358
359    return type->getResultId();
360}
361
362Id Builder::makeFloatE5M2Type()
363{
364    // try to find it
365    Instruction* type;
366    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeFloat)].size(); ++t) {
367        type = groupedTypes[enumCast(Op::OpTypeFloat)][t];
368        if (type->getNumOperands() != 2) {
369            continue;
370        }
371        if (type->getImmediateOperand(0) == (unsigned)8 &&
372            type->getImmediateOperand(1) == FPEncoding::Float8E5M2EXT)
373            return type->getResultId();
374    }
375
376    // not found, make it
377    type = new Instruction(getUniqueId(), NoType, Op::OpTypeFloat);
378    type->addImmediateOperand(8);
379    type->addImmediateOperand(FPEncoding::Float8E5M2EXT);
380    groupedTypes[enumCast(Op::OpTypeFloat)].push_back(type);
381    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
382    module.mapInstruction(type);
383
384    addExtension(spv::E_SPV_EXT_float8);
385    addCapability(Capability::Float8EXT);
386
387    if (emitNonSemanticShaderDebugInfo) {
388        auto const debugResultId = makeFloatDebugType(8, makeUintConstant((unsigned)FPEncoding::Float8E5M2EXT));
389        debugTypeIdLookup[type->getResultId()] = debugResultId;
390    }
391
392    return type->getResultId();
393}
394
395Id Builder::makeFloatE4M3Type()
396{
397    // try to find it
398    Instruction* type;
399    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeFloat)].size(); ++t) {
400        type = groupedTypes[enumCast(Op::OpTypeFloat)][t];
401        if (type->getNumOperands() != 2) {
402            continue;
403        }
404        if (type->getImmediateOperand(0) == (unsigned)8 &&
405            type->getImmediateOperand(1) == FPEncoding::Float8E4M3EXT)
406            return type->getResultId();
407    }
408
409    // not found, make it
410    type = new Instruction(getUniqueId(), NoType, Op::OpTypeFloat);
411    type->addImmediateOperand(8);
412    type->addImmediateOperand(FPEncoding::Float8E4M3EXT);
413    groupedTypes[enumCast(Op::OpTypeFloat)].push_back(type);
414    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
415    module.mapInstruction(type);
416
417    addExtension(spv::E_SPV_EXT_float8);
418    addCapability(Capability::Float8EXT);
419
420    if (emitNonSemanticShaderDebugInfo) {
421        auto const debugResultId = makeFloatDebugType(8, makeUintConstant((unsigned)FPEncoding::Float8E4M3EXT));
422        debugTypeIdLookup[type->getResultId()] = debugResultId;
423    }
424
425    return type->getResultId();
426}
427
428Id Builder::makeFloatOcpMicroscalingType(uint32_t width, FPEncoding encoding, Capability cap)
429{
430    // try to find it
431    Instruction* type;
432    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeFloat)].size(); ++t) {
433        type = groupedTypes[enumCast(Op::OpTypeFloat)][t];
434        if (type->getNumOperands() != 2) {
435            continue;
436        }
437        if (type->getImmediateOperand(0) == (unsigned)width &&
438            type->getImmediateOperand(1) == encoding)
439            return type->getResultId();
440    }
441
442    // not found, make it
443    type = new Instruction(getUniqueId(), NoType, Op::OpTypeFloat);
444    type->addImmediateOperand(width);
445    type->addImmediateOperand(encoding);
446    groupedTypes[enumCast(Op::OpTypeFloat)].push_back(type);
447    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
448    module.mapInstruction(type);
449
450    addExtension(spv::E_SPV_EXT_ocp_microscaling_types);
451    addCapability(cap);
452
453    if (emitNonSemanticShaderDebugInfo)
454    {
455        auto const debugResultId = makeFloatDebugType(width, makeUintConstant((unsigned)encoding));
456        debugTypeIdLookup[type->getResultId()] = debugResultId;
457    }
458
459    return type->getResultId();
460}
461
462Id Builder::makeFloatE2M1Type()
463{
464    return makeFloatOcpMicroscalingType(4, FPEncoding::Float4E2M1EXT, Capability::Float4EXT);
465}
466
467Id Builder::makeFloatE3M2Type()
468{
469    return makeFloatOcpMicroscalingType(6, FPEncoding::Float6E3M2EXT, Capability::Float6EXT);
470}
471
472Id Builder::makeFloatE2M3Type()
473{
474    return makeFloatOcpMicroscalingType(6, FPEncoding::Float6E2M3EXT, Capability::Float6EXT);
475}
476
477Id Builder::makeFloatUE8M0Type()
478{
479    return makeFloatOcpMicroscalingType(8, FPEncoding::Float8UnsignedE8M0EXT, Capability::Float8UnsignedE8M0EXT);
480}
481
482Id Builder::makeFloatMXINT8Type()
483{
484    return makeFloatOcpMicroscalingType(8, FPEncoding::MXInt8EXT, Capability::MXInt8EXT);
485}
486
487// Make a struct without checking for duplication.
488// See makeStructResultType() for non-decorated structs
489// needed as the result of some instructions, which does
490// check for duplicates.
491// For compiler-generated structs, debug info is ignored.
492Id Builder::makeStructType(const std::vector<Id>& members, const std::vector<spv::StructMemberDebugInfo>& memberDebugInfo,
493                           const char* name, bool const compilerGenerated)
494{
495    // Don't look for previous one, because in the general case,
496    // structs can be duplicated except for decorations.
497
498    // not found, make it
499    Instruction* type = new Instruction(getUniqueId(), NoType, Op::OpTypeStruct);
500    for (int op = 0; op < (int)members.size(); ++op)
501        type->addIdOperand(members[op]);
502    groupedTypes[enumCast(Op::OpTypeStruct)].push_back(type);
503    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
504    module.mapInstruction(type);
505    addName(type->getResultId(), name);
506
507    if (emitNonSemanticShaderDebugInfo && !compilerGenerated) {
508        assert(members.size() == memberDebugInfo.size());
509        auto const debugResultId =
510            makeCompositeDebugType(members, memberDebugInfo, name, NonSemanticShaderDebugInfoStructure);
511        debugTypeIdLookup[type->getResultId()] = debugResultId;
512    }
513
514    return type->getResultId();
515}
516
517// Make a struct for the simple results of several instructions,
518// checking for duplication.
519Id Builder::makeStructResultType(Id type0, Id type1)
520{
521    // try to find it
522    Instruction* type;
523    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeStruct)].size(); ++t) {
524        type = groupedTypes[enumCast(Op::OpTypeStruct)][t];
525        if (type->getNumOperands() != 2)
526            continue;
527        if (type->getIdOperand(0) != type0 ||
528            type->getIdOperand(1) != type1)
529            continue;
530        return type->getResultId();
531    }
532
533    // not found, make it
534    std::vector<spv::Id> members;
535    members.push_back(type0);
536    members.push_back(type1);
537
538    return makeStructType(members, {}, "ResType");
539}
540
541Id Builder::makeVectorType(Id component, int size)
542{
543    // try to find it
544    Instruction* type;
545    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeVector)].size(); ++t) {
546        type = groupedTypes[enumCast(Op::OpTypeVector)][t];
547        if (type->getIdOperand(0) == component &&
548            type->getImmediateOperand(1) == (unsigned)size)
549            return type->getResultId();
550    }
551
552    // not found, make it
553    type = new Instruction(getUniqueId(), NoType, Op::OpTypeVector);
554    type->reserveOperands(2);
555    type->addIdOperand(component);
556    type->addImmediateOperand(size);
557    groupedTypes[enumCast(Op::OpTypeVector)].push_back(type);
558    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
559    module.mapInstruction(type);
560
561    if (emitNonSemanticShaderDebugInfo)
562    {
563        auto const debugResultId = makeVectorDebugType(component, size);
564        debugTypeIdLookup[type->getResultId()] = debugResultId;
565    }
566
567    return type->getResultId();
568}
569
570Id Builder::makeMatrixType(Id component, int cols, int rows)
571{
572    assert(cols <= maxMatrixSize && rows <= maxMatrixSize);
573
574    Id column = makeVectorType(component, rows);
575
576    // try to find it
577    Instruction* type;
578    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeMatrix)].size(); ++t) {
579        type = groupedTypes[enumCast(Op::OpTypeMatrix)][t];
580        if (type->getIdOperand(0) == column &&
581            type->getImmediateOperand(1) == (unsigned)cols)
582            return type->getResultId();
583    }
584
585    // not found, make it
586    type = new Instruction(getUniqueId(), NoType, Op::OpTypeMatrix);
587    type->reserveOperands(2);
588    type->addIdOperand(column);
589    type->addImmediateOperand(cols);
590    groupedTypes[enumCast(Op::OpTypeMatrix)].push_back(type);
591    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
592    module.mapInstruction(type);
593
594    if (emitNonSemanticShaderDebugInfo)
595    {
596        auto const debugResultId = makeMatrixDebugType(column, cols);
597        debugTypeIdLookup[type->getResultId()] = debugResultId;
598    }
599
600    return type->getResultId();
601}
602
603Id Builder::makeCooperativeMatrixTypeKHR(Id component, Id scope, Id rows, Id cols, Id use)
604{
605    // try to find it
606    Instruction* type;
607    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeCooperativeMatrixKHR)].size(); ++t) {
608        type = groupedTypes[enumCast(Op::OpTypeCooperativeMatrixKHR)][t];
609        if (type->getIdOperand(0) == component &&
610            type->getIdOperand(1) == scope &&
611            type->getIdOperand(2) == rows &&
612            type->getIdOperand(3) == cols &&
613            type->getIdOperand(4) == use)
614            return type->getResultId();
615    }
616
617    // not found, make it
618    type = new Instruction(getUniqueId(), NoType, Op::OpTypeCooperativeMatrixKHR);
619    type->reserveOperands(5);
620    type->addIdOperand(component);
621    type->addIdOperand(scope);
622    type->addIdOperand(rows);
623    type->addIdOperand(cols);
624    type->addIdOperand(use);
625    groupedTypes[enumCast(Op::OpTypeCooperativeMatrixKHR)].push_back(type);
626    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
627    module.mapInstruction(type);
628
629    if (emitNonSemanticShaderDebugInfo) {
630        auto const debugResultId = makeCooperativeMatrixDebugTypeKHR(component, scope, rows, cols, use);
631        debugTypeIdLookup[type->getResultId()] = debugResultId;
632    }
633
634    return type->getResultId();
635}
636
637Id Builder::makeCooperativeMatrixTypeNV(Id component, Id scope, Id rows, Id cols)
638{
639    // try to find it
640    Instruction* type;
641    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeCooperativeMatrixNV)].size(); ++t) {
642        type = groupedTypes[enumCast(Op::OpTypeCooperativeMatrixNV)][t];
643        if (type->getIdOperand(0) == component && type->getIdOperand(1) == scope && type->getIdOperand(2) == rows &&
644            type->getIdOperand(3) == cols)
645            return type->getResultId();
646    }
647
648    // not found, make it
649    type = new Instruction(getUniqueId(), NoType, Op::OpTypeCooperativeMatrixNV);
650    type->reserveOperands(4);
651    type->addIdOperand(component);
652    type->addIdOperand(scope);
653    type->addIdOperand(rows);
654    type->addIdOperand(cols);
655    groupedTypes[enumCast(Op::OpTypeCooperativeMatrixNV)].push_back(type);
656    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
657    module.mapInstruction(type);
658
659    return type->getResultId();
660}
661
662Id Builder::makeCooperativeMatrixTypeWithSameShape(Id component, Id otherType)
663{
664    Instruction* instr = module.getInstruction(otherType);
665    if (instr->getOpCode() == Op::OpTypeCooperativeMatrixNV) {
666        return makeCooperativeMatrixTypeNV(component, instr->getIdOperand(1), instr->getIdOperand(2), instr->getIdOperand(3));
667    } else {
668        assert(instr->getOpCode() == Op::OpTypeCooperativeMatrixKHR);
669        return makeCooperativeMatrixTypeKHR(component, instr->getIdOperand(1), instr->getIdOperand(2), instr->getIdOperand(3), instr->getIdOperand(4));
670    }
671}
672
673Id Builder::makeCooperativeVectorTypeNV(Id componentType, Id components)
674{
675    // try to find it
676    Instruction* type;
677    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeCooperativeVectorNV)].size(); ++t) {
678        type = groupedTypes[enumCast(Op::OpTypeCooperativeVectorNV)][t];
679        if (type->getIdOperand(0) == componentType &&
680            type->getIdOperand(1) == components)
681            return type->getResultId();
682    }
683
684    // not found, make it
685    type = new Instruction(getUniqueId(), NoType, Op::OpTypeCooperativeVectorNV);
686    type->addIdOperand(componentType);
687    type->addIdOperand(components);
688    groupedTypes[enumCast(Op::OpTypeCooperativeVectorNV)].push_back(type);
689    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
690    module.mapInstruction(type);
691
692    if (emitNonSemanticShaderDebugInfo) {
693        auto const debugResultId = makeVectorIdDebugType(componentType, components);
694        debugTypeIdLookup[type->getResultId()] = debugResultId;
695    }
696
697    return type->getResultId();
698}
699
700Id Builder::makeTensorTypeARM(Id elementType, Id rank)
701{
702    // See if an OpTypeTensorARM with same element type and rank already exists.
703    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeTensorARM)].size(); ++t) {
704        const Instruction *type = groupedTypes[enumCast(Op::OpTypeTensorARM)][t];
705        if (type->getIdOperand(0) == elementType && type->getIdOperand(1) == rank)
706            return type->getResultId();
707    }
708
709    // Not found, make it.
710    std::unique_ptr<Instruction> type(new Instruction(getUniqueId(), NoType, Op::OpTypeTensorARM));
711    type->addIdOperand(elementType);
712    type->addIdOperand(rank);
713    groupedTypes[enumCast(Op::OpTypeTensorARM)].push_back(type.get());
714    module.mapInstruction(type.get());
715    Id resultID = type->getResultId();
716    constantsTypesGlobals.push_back(std::move(type));
717    return resultID;
718}
719
720Id Builder::makeGenericType(spv::Op opcode, std::vector<spv::IdImmediate>& operands)
721{
722    // try to find it
723    Instruction* type;
724    for (int t = 0; t < (int)groupedTypes[enumCast(opcode)].size(); ++t) {
725        type = groupedTypes[enumCast(opcode)][t];
726        if (static_cast<size_t>(type->getNumOperands()) != operands.size())
727            continue; // Number mismatch, find next
728
729        bool match = true;
730        for (int op = 0; match && op < (int)operands.size(); ++op) {
731            match = (operands[op].isId ? type->getIdOperand(op) : type->getImmediateOperand(op)) == operands[op].word;
732        }
733        if (match)
734            return type->getResultId();
735    }
736
737    // not found, make it
738    type = new Instruction(getUniqueId(), NoType, opcode);
739    type->reserveOperands(operands.size());
740    for (size_t op = 0; op < operands.size(); ++op) {
741        if (operands[op].isId)
742            type->addIdOperand(operands[op].word);
743        else
744            type->addImmediateOperand(operands[op].word);
745    }
746    groupedTypes[enumCast(opcode)].push_back(type);
747    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
748    module.mapInstruction(type);
749
750    return type->getResultId();
751}
752
753// TODO: performance: track arrays per stride
754// If a stride is supplied (non-zero) make an array.
755// If no stride (0), reuse previous array types.
756// 'size' is an Id of a constant or specialization constant of the array size
757Id Builder::makeArrayType(Id element, Id sizeId, int stride)
758{
759    Instruction* type;
760    if (stride == 0) {
761        // try to find existing type
762        for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeArray)].size(); ++t) {
763            type = groupedTypes[enumCast(Op::OpTypeArray)][t];
764            if (type->getIdOperand(0) == element &&
765                type->getIdOperand(1) == sizeId &&
766                explicitlyLaidOut.find(type->getResultId()) == explicitlyLaidOut.end())
767                return type->getResultId();
768        }
769    }
770
771    // not found, make it
772    type = new Instruction(getUniqueId(), NoType, Op::OpTypeArray);
773    type->reserveOperands(2);
774    type->addIdOperand(element);
775    type->addIdOperand(sizeId);
776    groupedTypes[enumCast(Op::OpTypeArray)].push_back(type);
777    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
778    module.mapInstruction(type);
779
780    if (stride != 0) {
781        explicitlyLaidOut.insert(type->getResultId());
782    }
783
784    if (emitNonSemanticShaderDebugInfo)
785    {
786        auto const debugResultId = makeArrayDebugType(element, sizeId);
787        debugTypeIdLookup[type->getResultId()] = debugResultId;
788    }
789
790    return type->getResultId();
791}
792
793Id Builder::makeRuntimeArray(Id element)
794{
795    Instruction* type = new Instruction(getUniqueId(), NoType, Op::OpTypeRuntimeArray);
796    type->addIdOperand(element);
797    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
798    module.mapInstruction(type);
799
800    if (emitNonSemanticShaderDebugInfo)
801    {
802        auto const debugResultId = makeArrayDebugType(element, makeUintConstant(0));
803        debugTypeIdLookup[type->getResultId()] = debugResultId;
804    }
805
806    return type->getResultId();
807}
808
809Id Builder::makeFunctionType(Id returnType, const std::vector<Id>& paramTypes)
810{
811    // try to find it
812    Instruction* type;
813    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeFunction)].size(); ++t) {
814        type = groupedTypes[enumCast(Op::OpTypeFunction)][t];
815        if (type->getIdOperand(0) != returnType || (int)paramTypes.size() != type->getNumOperands() - 1)
816            continue;
817        bool mismatch = false;
818        for (int p = 0; p < (int)paramTypes.size(); ++p) {
819            if (paramTypes[p] != type->getIdOperand(p + 1)) {
820                mismatch = true;
821                break;
822            }
823        }
824        if (! mismatch)
825        {
826            // If compiling HLSL, glslang will create a wrapper function around the entrypoint. Accordingly, a void(void)
827            // function type is created for the wrapper function. However, nonsemantic shader debug information is disabled
828            // while creating the HLSL wrapper. Consequently, if we encounter another void(void) function, we need to create
829            // the associated debug function type if it hasn't been created yet.
830            if(emitNonSemanticShaderDebugInfo && getDebugType(type->getResultId()) == NoType) {
831                assert(sourceLang == spv::SourceLanguage::HLSL);
832                assert(getTypeClass(returnType) == Op::OpTypeVoid && paramTypes.size() == 0);
833
834                Id id = makeDebugFunctionType(returnType, {});
835                debugTypeIdLookup[type->getResultId()] = id;
836            }
837            return type->getResultId();
838        }
839    }
840
841    // not found, make it
842    Id typeId = getUniqueId();
843    type = new Instruction(typeId, NoType, Op::OpTypeFunction);
844    type->reserveOperands(paramTypes.size() + 1);
845    type->addIdOperand(returnType);
846    for (int p = 0; p < (int)paramTypes.size(); ++p)
847        type->addIdOperand(paramTypes[p]);
848    groupedTypes[enumCast(Op::OpTypeFunction)].push_back(type);
849    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
850    module.mapInstruction(type);
851
852    // make debug type and map it
853    if (emitNonSemanticShaderDebugInfo) {
854        Id debugTypeId = makeDebugFunctionType(returnType, paramTypes);
855        debugTypeIdLookup[typeId] = debugTypeId;
856    }
857
858    return type->getResultId();
859}
860
861Id Builder::makeDebugFunctionType(Id returnType, const std::vector<Id>& paramTypes)
862{
863    assert(getDebugType(returnType) != NoType);
864
865    Id typeId = getUniqueId();
866    auto type = new Instruction(typeId, makeVoidType(), Op::OpExtInst);
867    type->reserveOperands(paramTypes.size() + 4);
868    type->addIdOperand(nonSemanticShaderDebugInfo);
869    type->addImmediateOperand(NonSemanticShaderDebugInfoDebugTypeFunction);
870    type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoFlagIsPublic));
871    type->addIdOperand(getDebugType(returnType));
872    for (auto const paramType : paramTypes) {
873        if (isPointerType(paramType) || isArrayType(paramType)) {
874            type->addIdOperand(getDebugType(getContainedTypeId(paramType)));
875        }
876        else {
877            type->addIdOperand(getDebugType(paramType));
878        }
879    }
880    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
881    module.mapInstruction(type);
882    return typeId;
883}
884
885Id Builder::makeImageType(Id sampledType, Dim dim, bool depth, bool arrayed, bool ms, unsigned sampled,
886    ImageFormat format, const char* debugName)
887{
888    assert(sampled == 1 || sampled == 2);
889
890    // try to find it
891    Instruction* type;
892    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeImage)].size(); ++t) {
893        type = groupedTypes[enumCast(Op::OpTypeImage)][t];
894        if (type->getIdOperand(0) == sampledType &&
895            type->getImmediateOperand(1) == (unsigned int)dim &&
896            type->getImmediateOperand(2) == (  depth ? 1u : 0u) &&
897            type->getImmediateOperand(3) == (arrayed ? 1u : 0u) &&
898            type->getImmediateOperand(4) == (     ms ? 1u : 0u) &&
899            type->getImmediateOperand(5) == sampled &&
900            type->getImmediateOperand(6) == (unsigned int)format)
901            return type->getResultId();
902    }
903
904    // not found, make it
905    type = new Instruction(getUniqueId(), NoType, Op::OpTypeImage);
906    type->reserveOperands(7);
907    type->addIdOperand(sampledType);
908    type->addImmediateOperand(   dim);
909    type->addImmediateOperand(  depth ? 1 : 0);
910    type->addImmediateOperand(arrayed ? 1 : 0);
911    type->addImmediateOperand(     ms ? 1 : 0);
912    type->addImmediateOperand(sampled);
913    type->addImmediateOperand((unsigned int)format);
914
915    groupedTypes[enumCast(Op::OpTypeImage)].push_back(type);
916    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
917    module.mapInstruction(type);
918
919    // deal with capabilities
920    switch (dim) {
921    case Dim::Buffer:
922        if (sampled == 1)
923            addCapability(Capability::SampledBuffer);
924        else
925            addCapability(Capability::ImageBuffer);
926        break;
927    case Dim::Dim1D:
928        if (sampled == 1)
929            addCapability(Capability::Sampled1D);
930        else
931            addCapability(Capability::Image1D);
932        break;
933    case Dim::Cube:
934        if (arrayed) {
935            if (sampled == 1)
936                addCapability(Capability::SampledCubeArray);
937            else
938                addCapability(Capability::ImageCubeArray);
939        }
940        break;
941    case Dim::Rect:
942        if (sampled == 1)
943            addCapability(Capability::SampledRect);
944        else
945            addCapability(Capability::ImageRect);
946        break;
947    case Dim::SubpassData:
948        addCapability(Capability::InputAttachment);
949        break;
950    default:
951        break;
952    }
953
954    if (ms) {
955        if (sampled == 2) {
956            // Images used with subpass data are not storage
957            // images, so don't require the capability for them.
958            if (dim != Dim::SubpassData)
959                addCapability(Capability::StorageImageMultisample);
960            if (arrayed)
961                addCapability(Capability::ImageMSArray);
962        }
963    }
964
965    if (emitNonSemanticShaderDebugInfo)
966    {
967        auto const debugResultId = makeOpaqueDebugType(debugName);
968        debugTypeIdLookup[type->getResultId()] = debugResultId;
969    }
970
971    return type->getResultId();
972}
973
974Id Builder::makeSampledImageType(Id imageType, const char* debugName)
975{
976    // try to find it
977    Instruction* type;
978    for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypeSampledImage)].size(); ++t) {
979        type = groupedTypes[enumCast(Op::OpTypeSampledImage)][t];
980        if (type->getIdOperand(0) == imageType)
981            return type->getResultId();
982    }
983
984    // not found, make it
985    type = new Instruction(getUniqueId(), NoType, Op::OpTypeSampledImage);
986    type->addIdOperand(imageType);
987
988    groupedTypes[enumCast(Op::OpTypeSampledImage)].push_back(type);
989    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
990    module.mapInstruction(type);
991
992    if (emitNonSemanticShaderDebugInfo)
993    {
994        auto const debugResultId = makeOpaqueDebugType(debugName);
995        debugTypeIdLookup[type->getResultId()] = debugResultId;
996    }
997
998    return type->getResultId();
999}
1000
1001Id Builder::makeDebugInfoNone()
1002{
1003    if (debugInfoNone != 0)
1004        return debugInfoNone;
1005
1006    Instruction* inst = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1007    inst->reserveOperands(2);
1008    inst->addIdOperand(nonSemanticShaderDebugInfo);
1009    inst->addImmediateOperand(NonSemanticShaderDebugInfoDebugInfoNone);
1010
1011    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
1012    module.mapInstruction(inst);
1013
1014    debugInfoNone = inst->getResultId();
1015
1016    return debugInfoNone;
1017}
1018
1019Id Builder::makeBoolDebugType(int const size)
1020{
1021    // try to find it
1022    Instruction* type;
1023    for (int t = 0; t < (int)groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeBasic].size(); ++t) {
1024        type = groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeBasic][t];
1025        if (type->getIdOperand(0) == getStringId("bool") &&
1026            type->getIdOperand(1) == static_cast<unsigned int>(size) &&
1027            type->getIdOperand(2) == NonSemanticShaderDebugInfoBoolean)
1028            return type->getResultId();
1029    }
1030
1031    type = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1032    type->reserveOperands(6);
1033    type->addIdOperand(nonSemanticShaderDebugInfo);
1034    type->addImmediateOperand(NonSemanticShaderDebugInfoDebugTypeBasic);
1035
1036    type->addIdOperand(getStringId("bool")); // name id
1037    type->addIdOperand(makeUintConstant(size)); // size id
1038    type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoBoolean)); // encoding id
1039    type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoNone)); // flags id
1040
1041    groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeBasic].push_back(type);
1042    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1043    module.mapInstruction(type);
1044
1045    return type->getResultId();
1046}
1047
1048Id Builder::makeIntegerDebugType(int const width, bool const hasSign)
1049{
1050    const char* typeName = nullptr;
1051    switch (width) {
1052        case 8:  typeName = hasSign ? "int8_t" : "uint8_t"; break;
1053        case 16: typeName = hasSign ? "int16_t" : "uint16_t"; break;
1054        case 64: typeName = hasSign ? "int64_t" : "uint64_t"; break;
1055        default: typeName = hasSign ? "int" : "uint";
1056    }
1057    auto nameId = getStringId(typeName);
1058    // try to find it
1059    Instruction* type;
1060    for (int t = 0; t < (int)groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeBasic].size(); ++t) {
1061        type = groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeBasic][t];
1062        if (type->getIdOperand(0) == nameId &&
1063            type->getIdOperand(1) == static_cast<unsigned int>(width) &&
1064            type->getIdOperand(2) == (hasSign ? NonSemanticShaderDebugInfoSigned : NonSemanticShaderDebugInfoUnsigned))
1065            return type->getResultId();
1066    }
1067
1068    // not found, make it
1069    type = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1070    type->reserveOperands(6);
1071    type->addIdOperand(nonSemanticShaderDebugInfo);
1072    type->addImmediateOperand(NonSemanticShaderDebugInfoDebugTypeBasic);
1073    type->addIdOperand(nameId); // name id
1074    type->addIdOperand(makeUintConstant(width)); // size id
1075    if(hasSign == true) {
1076        type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoSigned)); // encoding id
1077    } else {
1078        type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoUnsigned)); // encoding id
1079    }
1080    type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoNone)); // flags id
1081
1082    groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeBasic].push_back(type);
1083    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1084    module.mapInstruction(type);
1085
1086    return type->getResultId();
1087}
1088
1089Id Builder::makeFloatDebugType(int const width, Id const fpEncoding)
1090{
1091    if (fpEncoding != NoType)
1092        requireNonSemanticShaderDebugInfoVersion(101);
1093    // Determine the debug type name. FP-encoded variants have distinct names.
1094    // Id comparison works here because makeUintConstant deduplicates: two calls
1095    // with the same value return the same Id.
1096    const char* typeName = nullptr;
1097    if (fpEncoding != NoType) {
1098        if (fpEncoding == makeUintConstant((unsigned)FPEncoding::BFloat16KHR))
1099            typeName = "bfloat16_t";
1100        else if (fpEncoding == makeUintConstant((unsigned)FPEncoding::Float8E4M3EXT))
1101            typeName = "floate4m3_t";
1102        else if (fpEncoding == makeUintConstant((unsigned)FPEncoding::Float8E5M2EXT))
1103            typeName = "floate5m2_t";
1104        else if (fpEncoding == makeUintConstant((unsigned)FPEncoding::Float4E2M1EXT))
1105            typeName = "floate2m1_t";
1106        else if (fpEncoding == makeUintConstant((unsigned)FPEncoding::Float6E3M2EXT))
1107            typeName = "floate3m2_t";
1108        else if (fpEncoding == makeUintConstant((unsigned)FPEncoding::Float6E2M3EXT))
1109            typeName = "floate2m3_t";
1110        else if (fpEncoding == makeUintConstant((unsigned)FPEncoding::Float8UnsignedE8M0EXT))
1111            typeName = "floatue8m0_t";
1112        else if (fpEncoding == makeUintConstant((unsigned)FPEncoding::MXInt8EXT))
1113            typeName = "floatmxint8_t";
1114        else
1115            typeName = "float";
1116    } else {
1117        switch (width) {
1118            case 16: typeName = "float16_t"; break;
1119            case 64: typeName = "double"; break;
1120            default: typeName = "float"; break;
1121        }
1122    }
1123    auto nameId = getStringId(typeName);
1124    // try to find it
1125    Instruction* type;
1126    for (int t = 0; t < (int)groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeBasic].size(); ++t) {
1127        type = groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeBasic][t];
1128        if (type->getIdOperand(0) == nameId &&
1129            type->getIdOperand(1) == static_cast<unsigned int>(width) &&
1130            type->getIdOperand(2) == NonSemanticShaderDebugInfoFloat) {
1131            if (fpEncoding == NoType) {
1132                if (type->getNumOperands() == 6)
1133                    return type->getResultId();
1134            } else {
1135                if (type->getNumOperands() == 7 && type->getIdOperand(6) == fpEncoding)
1136                    return type->getResultId();
1137            }
1138        }
1139    }
1140
1141    // not found, make it
1142    type = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1143    type->reserveOperands(fpEncoding == NoType ? 6 : 7);
1144    type->addIdOperand(nonSemanticShaderDebugInfo);
1145    type->addImmediateOperand(NonSemanticShaderDebugInfoDebugTypeBasic);
1146    type->addIdOperand(nameId); // name id
1147    type->addIdOperand(makeUintConstant(width)); // size id
1148    type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoFloat)); // encoding id
1149    type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoNone)); // flags id
1150    if (fpEncoding != NoType)
1151        type->addIdOperand(fpEncoding); // optional FPEncoding id (NSDI.101)
1152
1153    groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeBasic].push_back(type);
1154    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1155    module.mapInstruction(type);
1156
1157    return type->getResultId();
1158}
1159
1160Id Builder::makeSequentialDebugType(Id const baseType, Id const componentCount, NonSemanticShaderDebugInfoInstructions const sequenceType)
1161{
1162    assert(sequenceType == NonSemanticShaderDebugInfoDebugTypeArray ||
1163        sequenceType == NonSemanticShaderDebugInfoDebugTypeVector);
1164
1165    // try to find it
1166    Instruction* type;
1167    for (int t = 0; t < (int)groupedDebugTypes[sequenceType].size(); ++t) {
1168        type = groupedDebugTypes[sequenceType][t];
1169        if (type->getIdOperand(0) == baseType &&
1170            type->getIdOperand(1) == makeUintConstant(componentCount))
1171            return type->getResultId();
1172    }
1173
1174    // not found, make it
1175    type = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1176    type->reserveOperands(4);
1177    type->addIdOperand(nonSemanticShaderDebugInfo);
1178    type->addImmediateOperand(sequenceType);
1179    type->addIdOperand(getDebugType(baseType)); // base type
1180    type->addIdOperand(componentCount); // component count
1181
1182    groupedDebugTypes[sequenceType].push_back(type);
1183    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1184    module.mapInstruction(type);
1185
1186    return type->getResultId();
1187}
1188
1189Id Builder::makeArrayDebugType(Id const baseType, Id const componentCount)
1190{
1191    return makeSequentialDebugType(baseType, componentCount, NonSemanticShaderDebugInfoDebugTypeArray);
1192}
1193
1194Id Builder::makeVectorDebugType(Id const baseType, int const componentCount)
1195{
1196    return makeSequentialDebugType(baseType, makeUintConstant(componentCount), NonSemanticShaderDebugInfoDebugTypeVector);
1197}
1198
1199Id Builder::makeMatrixDebugType(Id const vectorType, int const vectorCount, bool columnMajor)
1200{
1201    // try to find it
1202    Instruction* type;
1203    for (int t = 0; t < (int)groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeMatrix].size(); ++t) {
1204        type = groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeMatrix][t];
1205        if (type->getIdOperand(0) == vectorType &&
1206            type->getIdOperand(1) == makeUintConstant(vectorCount))
1207            return type->getResultId();
1208    }
1209
1210    // not found, make it
1211    type = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1212    type->reserveOperands(5);
1213    type->addIdOperand(nonSemanticShaderDebugInfo);
1214    type->addImmediateOperand(NonSemanticShaderDebugInfoDebugTypeMatrix);
1215    type->addIdOperand(getDebugType(vectorType)); // vector type id
1216    type->addIdOperand(makeUintConstant(vectorCount)); // component count id
1217    type->addIdOperand(makeBoolConstant(columnMajor)); // column-major id
1218
1219    groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeMatrix].push_back(type);
1220    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1221    module.mapInstruction(type);
1222
1223    return type->getResultId();
1224}
1225
1226// DebugTypeVectorIdEXT (NSDI.101 opcode 109): describes OpTypeVectorIdEXT and
1227// OpTypeCooperativeVectorNV types whose component count is a SPIR-V Id (not a
1228// literal), including specialization-constant component counts.
1229Id Builder::makeVectorIdDebugType(Id const componentType, Id const componentCount)
1230{
1231    requireNonSemanticShaderDebugInfoVersion(101);
1232    // try to find it
1233    Instruction* type;
1234    for (int t = 0; t < (int)groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeVectorIdEXT].size(); ++t) {
1235        type = groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeVectorIdEXT][t];
1236        if (type->getIdOperand(2) == getDebugType(componentType) &&
1237            type->getIdOperand(3) == componentCount)
1238            return type->getResultId();
1239    }
1240
1241    // not found, make it
1242    type = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1243    type->reserveOperands(4);
1244    type->addIdOperand(nonSemanticShaderDebugInfo);
1245    type->addImmediateOperand(NonSemanticShaderDebugInfoDebugTypeVectorIdEXT);
1246    type->addIdOperand(getDebugType(componentType)); // component debug type
1247    type->addIdOperand(componentCount); // component count (constant instruction Id)
1248
1249    groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeVectorIdEXT].push_back(type);
1250    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1251    module.mapInstruction(type);
1252
1253    return type->getResultId();
1254}
1255
1256// DebugTypeCooperativeMatrixKHR (NSDI.101 opcode 110): describes
1257// OpTypeCooperativeMatrixKHR types.
1258Id Builder::makeCooperativeMatrixDebugTypeKHR(Id const componentType, Id const scope,
1259                                              Id const rows, Id const cols, Id const use)
1260{
1261    requireNonSemanticShaderDebugInfoVersion(101);
1262    // try to find it
1263    Instruction* type;
1264    for (int t = 0; t < (int)groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeCooperativeMatrixKHR].size(); ++t) {
1265        type = groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeCooperativeMatrixKHR][t];
1266        if (type->getIdOperand(2) == getDebugType(componentType) &&
1267            type->getIdOperand(3) == scope &&
1268            type->getIdOperand(4) == rows &&
1269            type->getIdOperand(5) == cols &&
1270            type->getIdOperand(6) == use)
1271            return type->getResultId();
1272    }
1273
1274    // not found, make it
1275    type = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1276    type->reserveOperands(7);
1277    type->addIdOperand(nonSemanticShaderDebugInfo);
1278    type->addImmediateOperand(NonSemanticShaderDebugInfoDebugTypeCooperativeMatrixKHR);
1279    type->addIdOperand(getDebugType(componentType)); // component debug type
1280    type->addIdOperand(scope); // scope
1281    type->addIdOperand(rows); // rows
1282    type->addIdOperand(cols); // columns
1283    type->addIdOperand(use); // use (MatrixA, MatrixB, Accumulator)
1284
1285    groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeCooperativeMatrixKHR].push_back(type);
1286    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1287    module.mapInstruction(type);
1288
1289    return type->getResultId();
1290}
1291
1292Id Builder::makeMemberDebugType(Id const memberType, StructMemberDebugInfo const& debugTypeLoc)
1293{
1294    assert(getDebugType(memberType) != NoType);
1295
1296    Instruction* type = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1297    type->reserveOperands(10);
1298    type->addIdOperand(nonSemanticShaderDebugInfo);
1299    type->addImmediateOperand(NonSemanticShaderDebugInfoDebugTypeMember);
1300    type->addIdOperand(getStringId(debugTypeLoc.name)); // name id
1301    type->addIdOperand(debugTypeLoc.debugTypeOverride != 0 ? debugTypeLoc.debugTypeOverride
1302                                                           : getDebugType(memberType)); // type id
1303    type->addIdOperand(makeDebugSource(currentFileId));                            // source id
1304    type->addIdOperand(makeUintConstant(debugTypeLoc.line));   // line id TODO: currentLine is always zero
1305    type->addIdOperand(makeUintConstant(debugTypeLoc.column)); // TODO: column id
1306    type->addIdOperand(makeUintConstant(0));                   // TODO: offset id
1307    type->addIdOperand(makeUintConstant(0));                   // TODO: size id
1308    type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoFlagIsPublic)); // flags id
1309
1310    groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeMember].push_back(type);
1311    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1312    module.mapInstruction(type);
1313
1314    return type->getResultId();
1315}
1316
1317Id Builder::makeCompositeDebugType(std::vector<Id> const& memberTypes, std::vector<StructMemberDebugInfo> const& memberDebugInfo,
1318                                   char const* const name, NonSemanticShaderDebugInfoDebugCompositeType const tag)
1319{
1320    // Create the debug member types.
1321    std::vector<Id> memberDebugTypes;
1322    assert(memberTypes.size() == memberDebugInfo.size());
1323    for (size_t i = 0; i < memberTypes.size(); i++) {
1324        if (getDebugType(memberTypes[i]) != NoType) {
1325            memberDebugTypes.emplace_back(makeMemberDebugType(memberTypes[i], memberDebugInfo[i]));
1326        }
1327    }
1328
1329    // Create The structure debug type.
1330    Instruction* type = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1331    type->reserveOperands(memberDebugTypes.size() + 11);
1332    type->addIdOperand(nonSemanticShaderDebugInfo);
1333    type->addImmediateOperand(NonSemanticShaderDebugInfoDebugTypeComposite);
1334    type->addIdOperand(getStringId(name)); // name id
1335    type->addIdOperand(makeUintConstant(tag)); // tag id
1336    type->addIdOperand(makeDebugSource(currentFileId)); // source id
1337    type->addIdOperand(makeUintConstant(currentLine)); // line id TODO: currentLine always zero?
1338    type->addIdOperand(makeUintConstant(0)); // TODO: column id
1339    type->addIdOperand(makeDebugCompilationUnit()); // scope id
1340    type->addIdOperand(getStringId(name)); // linkage name id
1341    type->addIdOperand(makeUintConstant(0)); // TODO: size id
1342    type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoFlagIsPublic)); // flags id
1343    for(auto const memberDebugType : memberDebugTypes) {
1344        type->addIdOperand(memberDebugType);
1345    }
1346
1347    groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeComposite].push_back(type);
1348    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1349    module.mapInstruction(type);
1350
1351    return type->getResultId();
1352}
1353
1354// The NonSemantic Shader Debug Info doesn't really have a dedicated opcode for opaque types. Instead, we use DebugTypeComposite.
1355// To represent a source language opaque type, this instruction must have no Members operands, Size operand must be
1356// DebugInfoNone, and Name must start with @ to avoid clashes with user defined names.
1357Id Builder::makeOpaqueDebugType(char const* const name)
1358{
1359    // Create The structure debug type.
1360    Instruction* type = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1361    type->reserveOperands(11);
1362    type->addIdOperand(nonSemanticShaderDebugInfo);
1363    type->addImmediateOperand(NonSemanticShaderDebugInfoDebugTypeComposite);
1364    type->addIdOperand(getStringId(name)); // name id
1365    type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoStructure)); // tag id
1366    type->addIdOperand(makeDebugSource(currentFileId)); // source id
1367    type->addIdOperand(makeUintConstant(currentLine)); // line id TODO: currentLine always zero?
1368    type->addIdOperand(makeUintConstant(0)); // TODO: column id
1369    type->addIdOperand(makeDebugCompilationUnit()); // scope id
1370    // Prepend '@' to opaque types.
1371    type->addIdOperand(getStringId('@' + std::string(name))); // linkage name id
1372    type->addIdOperand(makeDebugInfoNone()); // size id
1373    type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoFlagIsPublic)); // flags id
1374
1375    groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypeComposite].push_back(type);
1376    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1377    module.mapInstruction(type);
1378
1379    return type->getResultId();
1380}
1381
1382Id Builder::makePointerDebugType(StorageClass storageClass, Id const baseType)
1383{
1384    const Id debugBaseType = getDebugType(baseType);
1385    if (!debugBaseType) {
1386        return makeDebugInfoNone();
1387    }
1388    const Id scID = makeUintConstant(storageClass);
1389    for (Instruction* otherType : groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypePointer]) {
1390        if (otherType->getIdOperand(2) == debugBaseType &&
1391            otherType->getIdOperand(3) == scID) {
1392            return otherType->getResultId();
1393        }
1394    }
1395
1396    Instruction* type = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1397    type->reserveOperands(5);
1398    type->addIdOperand(nonSemanticShaderDebugInfo);
1399    type->addImmediateOperand(NonSemanticShaderDebugInfoDebugTypePointer);
1400    type->addIdOperand(debugBaseType);
1401    type->addIdOperand(scID);
1402    type->addIdOperand(makeUintConstant(0));
1403
1404    groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypePointer].push_back(type);
1405    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1406    module.mapInstruction(type);
1407
1408    return type->getResultId();
1409}
1410
1411// Emit a OpExtInstWithForwardRefsKHR nonsemantic instruction for a pointer debug type
1412// where we don't have the pointee yet. Since we don't have the pointee yet, it just
1413// points to itself and we rely on patching it later.
1414Id Builder::makeForwardPointerDebugType(StorageClass storageClass)
1415{
1416    const Id scID = makeUintConstant(storageClass);
1417
1418    this->addExtension(spv::E_SPV_KHR_relaxed_extended_instruction);
1419
1420    Instruction *type = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInstWithForwardRefsKHR);
1421    type->addIdOperand(nonSemanticShaderDebugInfo);
1422    type->addImmediateOperand(NonSemanticShaderDebugInfoDebugTypePointer);
1423    type->addIdOperand(type->getResultId());
1424    type->addIdOperand(scID);
1425    type->addIdOperand(makeUintConstant(0));
1426
1427    groupedDebugTypes[NonSemanticShaderDebugInfoDebugTypePointer].push_back(type);
1428    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1429    module.mapInstruction(type);
1430
1431    return type->getResultId();
1432}
1433
1434Id Builder::makeDebugSource(const Id fileName) {
1435    if (debugSourceId.find(fileName) != debugSourceId.end())
1436        return debugSourceId[fileName];
1437    spv::Id resultId = getUniqueId();
1438    Instruction* sourceInst = new Instruction(resultId, makeVoidType(), Op::OpExtInst);
1439    sourceInst->reserveOperands(3);
1440    sourceInst->addIdOperand(nonSemanticShaderDebugInfo);
1441    sourceInst->addImmediateOperand(NonSemanticShaderDebugInfoDebugSource);
1442    sourceInst->addIdOperand(fileName);
1443    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(sourceInst));
1444    module.mapInstruction(sourceInst);
1445    if (emitNonSemanticShaderDebugSource) {
1446        const int maxWordCount = 0xFFFF;
1447        const int opSourceWordCount = 4;
1448        const int nonNullBytesPerInstruction = 4 * (maxWordCount - opSourceWordCount) - 1;
1449        auto processDebugSource = [&](std::string source) {
1450            if (source.size() > 0) {
1451                int nextByte = 0;
1452                while ((int)source.size() - nextByte > 0) {
1453                    auto subString = source.substr(nextByte, nonNullBytesPerInstruction);
1454                    auto sourceId = getStringId(subString);
1455                    if (nextByte == 0) {
1456                        // DebugSource
1457                        sourceInst->addIdOperand(sourceId);
1458                    } else {
1459                        // DebugSourceContinued
1460                        Instruction* sourceContinuedInst = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1461                        sourceContinuedInst->reserveOperands(2);
1462                        sourceContinuedInst->addIdOperand(nonSemanticShaderDebugInfo);
1463                        sourceContinuedInst->addImmediateOperand(NonSemanticShaderDebugInfoDebugSourceContinued);
1464                        sourceContinuedInst->addIdOperand(sourceId);
1465                        constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(sourceContinuedInst));
1466                        module.mapInstruction(sourceContinuedInst);
1467                    }
1468                    nextByte += nonNullBytesPerInstruction;
1469                }
1470            } else {
1471                auto sourceId = getStringId(source);
1472                sourceInst->addIdOperand(sourceId);
1473            }
1474        };
1475        if (fileName == mainFileId) {
1476            processDebugSource(sourceText);
1477        } else {
1478            auto incItr = includeFiles.find(fileName);
1479            if (incItr != includeFiles.end()) {
1480                processDebugSource(*incItr->second);
1481            } else {
1482                // We omit the optional source text item if not available in glslang
1483            }
1484        }
1485    }
1486    debugSourceId[fileName] = resultId;
1487    return resultId;
1488}
1489
1490Id Builder::makeDebugCompilationUnit() {
1491    if (nonSemanticShaderCompilationUnitId != 0)
1492        return nonSemanticShaderCompilationUnitId;
1493    spv::Id resultId = getUniqueId();
1494    Instruction* sourceInst = new Instruction(resultId, makeVoidType(), Op::OpExtInst);
1495    sourceInst->reserveOperands(6);
1496    sourceInst->addIdOperand(nonSemanticShaderDebugInfo);
1497    sourceInst->addImmediateOperand(NonSemanticShaderDebugInfoDebugCompilationUnit);
1498    sourceInst->addIdOperand(makeUintConstant(1)); // TODO(greg-lunarg): Get rid of magic number
1499    sourceInst->addIdOperand(makeUintConstant(4)); // TODO(greg-lunarg): Get rid of magic number
1500    sourceInst->addIdOperand(makeDebugSource(mainFileId));
1501    sourceInst->addIdOperand(makeUintConstant(sourceLang));
1502    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(sourceInst));
1503    module.mapInstruction(sourceInst);
1504    nonSemanticShaderCompilationUnitId = resultId;
1505
1506    // In the case of non-semantic shader debug info, preserve source text for every include
1507    // even if no debug scope or line record ends up referencing that file.
1508    if (emitNonSemanticShaderDebugSource) {
1509        for (const auto& includeFile : includeFiles) {
1510            makeDebugSource(includeFile.first);
1511        }
1512    }
1513
1514    // We can reasonably assume that makeDebugCompilationUnit will be called before any of
1515    // debug-scope stack. Function scopes and lexical scopes will occur afterward.
1516    assert(currentDebugScopeId.empty());
1517    currentDebugScopeId.push(nonSemanticShaderCompilationUnitId);
1518
1519    return resultId;
1520}
1521
1522Id Builder::createDebugGlobalVariable(Id const type, char const*const name, Id const variable)
1523{
1524    assert(type != 0);
1525
1526    Instruction* inst = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1527    inst->reserveOperands(11);
1528    inst->addIdOperand(nonSemanticShaderDebugInfo);
1529    inst->addImmediateOperand(NonSemanticShaderDebugInfoDebugGlobalVariable);
1530    inst->addIdOperand(getStringId(name)); // name id
1531    inst->addIdOperand(type); // type id
1532    inst->addIdOperand(makeDebugSource(currentFileId)); // source id
1533    inst->addIdOperand(makeUintConstant(currentLine)); // line id TODO: currentLine always zero?
1534    inst->addIdOperand(makeUintConstant(0)); // TODO: column id
1535    inst->addIdOperand(makeDebugCompilationUnit()); // scope id
1536    inst->addIdOperand(getStringId(name)); // linkage name id
1537    inst->addIdOperand(variable); // variable id
1538    inst->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoFlagIsDefinition)); // flags id
1539
1540    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
1541    module.mapInstruction(inst);
1542
1543    return inst->getResultId();
1544}
1545
1546Id Builder::createDebugLocalVariable(Id type, char const*const name, size_t const argNumber)
1547{
1548    assert(name != nullptr);
1549    assert(!currentDebugScopeId.empty());
1550
1551    Instruction* inst = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1552    inst->reserveOperands(9);
1553    inst->addIdOperand(nonSemanticShaderDebugInfo);
1554    inst->addImmediateOperand(NonSemanticShaderDebugInfoDebugLocalVariable);
1555    inst->addIdOperand(getStringId(name)); // name id
1556    inst->addIdOperand(type); // type id
1557    inst->addIdOperand(makeDebugSource(currentFileId)); // source id
1558    inst->addIdOperand(makeUintConstant(currentLine)); // line id
1559    inst->addIdOperand(makeUintConstant(0)); // TODO: column id
1560    inst->addIdOperand(currentDebugScopeId.top()); // scope id
1561    inst->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoFlagIsLocal)); // flags id
1562    if(argNumber != 0) {
1563        inst->addIdOperand(makeUintConstant(static_cast<unsigned int>(argNumber)));
1564    }
1565
1566    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
1567    module.mapInstruction(inst);
1568
1569    return inst->getResultId();
1570}
1571
1572Id Builder::makeDebugExpression()
1573{
1574    if (debugExpression != 0)
1575        return debugExpression;
1576
1577    Instruction* inst = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1578    inst->reserveOperands(2);
1579    inst->addIdOperand(nonSemanticShaderDebugInfo);
1580    inst->addImmediateOperand(NonSemanticShaderDebugInfoDebugExpression);
1581
1582    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
1583    module.mapInstruction(inst);
1584
1585    debugExpression = inst->getResultId();
1586
1587    return debugExpression;
1588}
1589
1590Id Builder::makeDebugDeclare(Id const debugLocalVariable, Id const pointer)
1591{
1592    Instruction* inst = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1593    inst->reserveOperands(5);
1594    inst->addIdOperand(nonSemanticShaderDebugInfo);
1595    inst->addImmediateOperand(NonSemanticShaderDebugInfoDebugDeclare);
1596    inst->addIdOperand(debugLocalVariable); // debug local variable id
1597    inst->addIdOperand(pointer); // pointer to local variable id
1598    inst->addIdOperand(makeDebugExpression()); // expression id
1599    addInstruction(std::unique_ptr<Instruction>(inst));
1600
1601    return inst->getResultId();
1602}
1603
1604Id Builder::makeDebugValue(Id const debugLocalVariable, Id const value)
1605{
1606    Instruction* inst = new Instruction(getUniqueId(), makeVoidType(), Op::OpExtInst);
1607    inst->reserveOperands(5);
1608    inst->addIdOperand(nonSemanticShaderDebugInfo);
1609    inst->addImmediateOperand(NonSemanticShaderDebugInfoDebugValue);
1610    inst->addIdOperand(debugLocalVariable); // debug local variable id
1611    inst->addIdOperand(value); // value of local variable id
1612    inst->addIdOperand(makeDebugExpression()); // expression id
1613    addInstruction(std::unique_ptr<Instruction>(inst));
1614
1615    return inst->getResultId();
1616}
1617
1618Id Builder::makeAccelerationStructureType()
1619{
1620    Instruction *type;
1621    if (groupedTypes[enumCast(Op::OpTypeAccelerationStructureKHR)].size() == 0) {
1622        type = new Instruction(getUniqueId(), NoType, Op::OpTypeAccelerationStructureKHR);
1623        groupedTypes[enumCast(Op::OpTypeAccelerationStructureKHR)].push_back(type);
1624        constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1625        module.mapInstruction(type);
1626        if (emitNonSemanticShaderDebugInfo) {
1627            spv::Id debugType = makeOpaqueDebugType("accelerationStructure");
1628            debugTypeIdLookup[type->getResultId()] = debugType;
1629        }
1630    } else {
1631        type = groupedTypes[enumCast(Op::OpTypeAccelerationStructureKHR)].back();
1632    }
1633
1634    return type->getResultId();
1635}
1636
1637Id Builder::makeRayQueryType()
1638{
1639    Instruction *type;
1640    if (groupedTypes[enumCast(Op::OpTypeRayQueryKHR)].size() == 0) {
1641        type = new Instruction(getUniqueId(), NoType, Op::OpTypeRayQueryKHR);
1642        groupedTypes[enumCast(Op::OpTypeRayQueryKHR)].push_back(type);
1643        constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1644        module.mapInstruction(type);
1645        if (emitNonSemanticShaderDebugInfo) {
1646            spv::Id debugType = makeOpaqueDebugType("rayQuery");
1647            debugTypeIdLookup[type->getResultId()] = debugType;
1648        }
1649    } else {
1650        type = groupedTypes[enumCast(Op::OpTypeRayQueryKHR)].back();
1651    }
1652
1653    return type->getResultId();
1654}
1655
1656Id Builder::makeHitObjectEXTType()
1657{
1658    Instruction *type;
1659    if (groupedTypes[enumCast(Op::OpTypeHitObjectEXT)].size() == 0) {
1660        type = new Instruction(getUniqueId(), NoType, Op::OpTypeHitObjectEXT);
1661        groupedTypes[enumCast(Op::OpTypeHitObjectEXT)].push_back(type);
1662        constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1663        module.mapInstruction(type);
1664    } else {
1665        type = groupedTypes[enumCast(Op::OpTypeHitObjectEXT)].back();
1666    }
1667
1668    return type->getResultId();
1669}
1670Id Builder::makeHitObjectNVType()
1671{
1672    Instruction *type;
1673    if (groupedTypes[enumCast(Op::OpTypeHitObjectNV)].size() == 0) {
1674        type = new Instruction(getUniqueId(), NoType, Op::OpTypeHitObjectNV);
1675        groupedTypes[enumCast(Op::OpTypeHitObjectNV)].push_back(type);
1676        constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
1677        module.mapInstruction(type);
1678        if (emitNonSemanticShaderDebugInfo) {
1679            spv::Id debugType = makeOpaqueDebugType("hitObjectNV");
1680            debugTypeIdLookup[type->getResultId()] = debugType;
1681        }
1682    } else {
1683        type = groupedTypes[enumCast(Op::OpTypeHitObjectNV)].back();
1684    }
1685
1686    return type->getResultId();
1687}
1688
1689Id Builder::getDerefTypeId(Id resultId) const
1690{
1691    Id typeId = getTypeId(resultId);
1692    assert(isPointerType(typeId));
1693
1694    return module.getInstruction(typeId)->getIdOperand(1);
1695}
1696
1697Op Builder::getMostBasicTypeClass(Id typeId) const
1698{
1699    Instruction* instr = module.getInstruction(typeId);
1700
1701    Op typeClass = instr->getOpCode();
1702    switch (typeClass)
1703    {
1704    case Op::OpTypeVector:
1705    case Op::OpTypeMatrix:
1706    case Op::OpTypeArray:
1707    case Op::OpTypeRuntimeArray:
1708        return getMostBasicTypeClass(instr->getIdOperand(0));
1709    case Op::OpTypePointer:
1710        return getMostBasicTypeClass(instr->getIdOperand(1));
1711    default:
1712        return typeClass;
1713    }
1714}
1715
1716unsigned int Builder::getNumTypeConstituents(Id typeId) const
1717{
1718    Instruction* instr = module.getInstruction(typeId);
1719
1720    switch (instr->getOpCode())
1721    {
1722    case Op::OpTypeBool:
1723    case Op::OpTypeInt:
1724    case Op::OpTypeFloat:
1725    case Op::OpTypePointer:
1726        return 1;
1727    case Op::OpTypeVector:
1728    case Op::OpTypeMatrix:
1729        return instr->getImmediateOperand(1);
1730    case Op::OpTypeCooperativeVectorNV:
1731    case Op::OpTypeArray:
1732    {
1733        Id lengthId = instr->getIdOperand(1);
1734        return module.getInstruction(lengthId)->getImmediateOperand(0);
1735    }
1736    case Op::OpTypeStruct:
1737        return instr->getNumOperands();
1738    case Op::OpTypeCooperativeMatrixKHR:
1739    case Op::OpTypeCooperativeMatrixNV:
1740        // has only one constituent when used with OpCompositeConstruct.
1741        return 1;
1742    default:
1743        assert(0);
1744        return 1;
1745    }
1746}
1747
1748// Return the lowest-level type of scalar that an homogeneous composite is made out of.
1749// Typically, this is just to find out if something is made out of ints or floats.
1750// However, it includes returning a structure, if say, it is an array of structure.
1751Id Builder::getScalarTypeId(Id typeId) const
1752{
1753    Instruction* instr = module.getInstruction(typeId);
1754
1755    Op typeClass = instr->getOpCode();
1756    switch (typeClass)
1757    {
1758    case Op::OpTypeVoid:
1759    case Op::OpTypeBool:
1760    case Op::OpTypeInt:
1761    case Op::OpTypeFloat:
1762    case Op::OpTypeStruct:
1763        return instr->getResultId();
1764    case Op::OpTypeVector:
1765    case Op::OpTypeMatrix:
1766    case Op::OpTypeArray:
1767    case Op::OpTypeRuntimeArray:
1768    case Op::OpTypePointer:
1769    case Op::OpTypeCooperativeVectorNV:
1770        return getScalarTypeId(getContainedTypeId(typeId));
1771    default:
1772        assert(0);
1773        return NoResult;
1774    }
1775}
1776
1777// Return the type of 'member' of a composite.
1778Id Builder::getContainedTypeId(Id typeId, int member) const
1779{
1780    Instruction* instr = module.getInstruction(typeId);
1781
1782    Op typeClass = instr->getOpCode();
1783    switch (typeClass)
1784    {
1785    case Op::OpTypeVector:
1786    case Op::OpTypeMatrix:
1787    case Op::OpTypeArray:
1788    case Op::OpTypeRuntimeArray:
1789    case Op::OpTypeCooperativeMatrixKHR:
1790    case Op::OpTypeCooperativeMatrixNV:
1791    case Op::OpTypeCooperativeVectorNV:
1792        return instr->getIdOperand(0);
1793    case Op::OpTypePointer:
1794        return instr->getIdOperand(1);
1795    case Op::OpTypeStruct:
1796        return instr->getIdOperand(member);
1797    default:
1798        assert(0);
1799        return NoResult;
1800    }
1801}
1802
1803// Figure out the final resulting type of the access chain.
1804Id Builder::getResultingAccessChainType() const
1805{
1806    assert(accessChain.base != NoResult);
1807    Id typeId = getTypeId(accessChain.base);
1808
1809    assert(isPointerType(typeId));
1810    typeId = getContainedTypeId(typeId);
1811
1812    for (int i = 0; i < (int)accessChain.indexChain.size(); ++i) {
1813        if (isStructType(typeId)) {
1814            assert(isConstantScalar(accessChain.indexChain[i]));
1815            typeId = getContainedTypeId(typeId, getConstantScalar(accessChain.indexChain[i]));
1816        } else
1817            typeId = getContainedTypeId(typeId, accessChain.indexChain[i]);
1818    }
1819
1820    return typeId;
1821}
1822
1823// Return the immediately contained type of a given composite type.
1824Id Builder::getContainedTypeId(Id typeId) const
1825{
1826    return getContainedTypeId(typeId, 0);
1827}
1828
1829// Returns true if 'typeId' is or contains a scalar type declared with 'typeOp'
1830// of width 'width'. The 'width' is only consumed for int and float types.
1831// Returns false otherwise.
1832bool Builder::containsType(Id typeId, spv::Op typeOp, unsigned int width) const
1833{
1834    const Instruction& instr = *module.getInstruction(typeId);
1835
1836    Op typeClass = instr.getOpCode();
1837    switch (typeClass)
1838    {
1839    case Op::OpTypeInt:
1840    case Op::OpTypeFloat:
1841        return typeClass == typeOp && instr.getImmediateOperand(0) == width;
1842    case Op::OpTypeStruct:
1843        for (int m = 0; m < instr.getNumOperands(); ++m) {
1844            if (containsType(instr.getIdOperand(m), typeOp, width))
1845                return true;
1846        }
1847        return false;
1848    case Op::OpTypePointer:
1849        return false;
1850    case Op::OpTypeVector:
1851    case Op::OpTypeMatrix:
1852    case Op::OpTypeArray:
1853    case Op::OpTypeRuntimeArray:
1854        return containsType(getContainedTypeId(typeId), typeOp, width);
1855    default:
1856        return typeClass == typeOp;
1857    }
1858}
1859
1860// return true if the type is a pointer to PhysicalStorageBufferEXT or an
1861// contains such a pointer. These require restrict/aliased decorations.
1862bool Builder::containsPhysicalStorageBufferOrArray(Id typeId) const
1863{
1864    const Instruction& instr = *module.getInstruction(typeId);
1865
1866    Op typeClass = instr.getOpCode();
1867    switch (typeClass)
1868    {
1869    case Op::OpTypePointer:
1870        return getTypeStorageClass(typeId) == StorageClass::PhysicalStorageBufferEXT;
1871    case Op::OpTypeArray:
1872        return containsPhysicalStorageBufferOrArray(getContainedTypeId(typeId));
1873    case Op::OpTypeStruct:
1874        for (int m = 0; m < instr.getNumOperands(); ++m) {
1875            if (containsPhysicalStorageBufferOrArray(instr.getIdOperand(m)))
1876                return true;
1877        }
1878        return false;
1879    default:
1880        return false;
1881    }
1882}
1883
1884// See if a scalar constant of this type has already been created, so it
1885// can be reused rather than duplicated.  (Required by the specification).
1886Id Builder::findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned value)
1887{
1888    ScalarConstantKey key{ enumCast(typeClass), enumCast(opcode), typeId, value, 0 };
1889    auto it = groupedScalarConstantResultIDs.find(key);
1890    return (it != groupedScalarConstantResultIDs.end()) ? it->second : 0;
1891}
1892
1893// Version of findScalarConstant (see above) for scalars that take two operands (e.g. a 'double' or 'int64').
1894Id Builder::findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned v1, unsigned v2)
1895{
1896    ScalarConstantKey key{ enumCast(typeClass), enumCast(opcode), typeId, v1, v2 };
1897    auto it = groupedScalarConstantResultIDs.find(key);
1898    return (it != groupedScalarConstantResultIDs.end()) ? it->second : 0;
1899}
1900
1901// Return true if consuming 'opcode' means consuming a constant.
1902// "constant" here means after final transform to executable code,
1903// the value consumed will be a constant, so includes specialization.
1904bool Builder::isConstantOpCode(Op opcode) const
1905{
1906    switch (opcode) {
1907    case Op::OpUndef:
1908    case Op::OpConstantTrue:
1909    case Op::OpConstantFalse:
1910    case Op::OpConstant:
1911    case Op::OpConstantDataKHR:
1912    case Op::OpConstantComposite:
1913    case Op::OpConstantCompositeReplicateEXT:
1914    case Op::OpConstantSampler:
1915    case Op::OpConstantNull:
1916    case Op::OpSpecConstantTrue:
1917    case Op::OpSpecConstantFalse:
1918    case Op::OpSpecConstant:
1919    case Op::OpSpecConstantComposite:
1920    case Op::OpSpecConstantCompositeReplicateEXT:
1921    case Op::OpSpecConstantDataKHR:
1922    case Op::OpSpecConstantOp:
1923    case Op::OpConstantSizeOfEXT:
1924        return true;
1925    default:
1926        return false;
1927    }
1928}
1929
1930// Return true if consuming 'opcode' means consuming a specialization constant.
1931bool Builder::isSpecConstantOpCode(Op opcode) const
1932{
1933    switch (opcode) {
1934    case Op::OpSpecConstantTrue:
1935    case Op::OpSpecConstantFalse:
1936    case Op::OpSpecConstant:
1937    case Op::OpSpecConstantComposite:
1938    case Op::OpSpecConstantDataKHR:
1939    case Op::OpSpecConstantOp:
1940    case Op::OpSpecConstantCompositeReplicateEXT:
1941        return true;
1942    default:
1943        return false;
1944    }
1945}
1946
1947Id Builder::makeNullConstant(Id typeId)
1948{
1949    Instruction* constant;
1950
1951    // See if we already made it.
1952    Id existing = NoResult;
1953    for (int i = 0; i < (int)nullConstants.size(); ++i) {
1954        constant = nullConstants[i];
1955        if (constant->getTypeId() == typeId)
1956            existing = constant->getResultId();
1957    }
1958
1959    if (existing != NoResult)
1960        return existing;
1961
1962    // Make it
1963    Instruction* c = new Instruction(getUniqueId(), typeId, Op::OpConstantNull);
1964    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
1965    nullConstants.push_back(c);
1966    module.mapInstruction(c);
1967
1968    return c->getResultId();
1969}
1970
1971Id Builder::makeBoolConstant(bool b, bool specConstant)
1972{
1973    Id typeId = makeBoolType();
1974    Op opcode = specConstant ? (b ? Op::OpSpecConstantTrue : Op::OpSpecConstantFalse) : (b ? Op::OpConstantTrue : Op::OpConstantFalse);
1975
1976    // See if we already made it. Applies only to regular constants, because specialization constants
1977    // must remain distinct for the purpose of applying a SpecId decoration.
1978    if (!specConstant) {
1979        Id existing = findScalarConstant(Op::OpTypeBool, opcode, typeId, 0);
1980        if (existing)
1981            return existing;
1982    }
1983
1984    // Make it
1985    Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
1986    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
1987    module.mapInstruction(c);
1988
1989    Id resultId = c->getResultId();
1990    if (!specConstant) {
1991        ScalarConstantKey key{enumCast(Op::OpTypeBool), enumCast(opcode), typeId, 0, 0};
1992        groupedScalarConstantResultIDs[key] = resultId;
1993    }
1994    return resultId;
1995}
1996
1997Id Builder::makeIntConstant(Id typeId, unsigned value, bool specConstant)
1998{
1999    Op opcode = specConstant ? Op::OpSpecConstant : Op::OpConstant;
2000
2001    // See if we already made it. Applies only to regular constants, because specialization constants
2002    // must remain distinct for the purpose of applying a SpecId decoration.
2003    if (! specConstant) {
2004        Id existing = findScalarConstant(Op::OpTypeInt, opcode, typeId, value);
2005        if (existing)
2006            return existing;
2007    }
2008
2009    Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
2010    c->addImmediateOperand(value);
2011    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
2012    module.mapInstruction(c);
2013
2014    Id resultId = c->getResultId();
2015    if (!specConstant) {
2016        ScalarConstantKey key{ enumCast(Op::OpTypeInt), enumCast(opcode), typeId, value, 0 };
2017        groupedScalarConstantResultIDs[key] = resultId;
2018    }
2019    return resultId;
2020}
2021
2022Id Builder::makeInt64Constant(Id typeId, unsigned long long value, bool specConstant)
2023{
2024    Op opcode = specConstant ? Op::OpSpecConstant : Op::OpConstant;
2025
2026    unsigned op1 = value & 0xFFFFFFFF;
2027    unsigned op2 = value >> 32;
2028
2029    // See if we already made it. Applies only to regular constants, because specialization constants
2030    // must remain distinct for the purpose of applying a SpecId decoration.
2031    if (! specConstant) {
2032        Id existing = findScalarConstant(Op::OpTypeInt, opcode, typeId, op1, op2);
2033        if (existing)
2034            return existing;
2035    }
2036
2037    Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
2038    c->reserveOperands(2);
2039    c->addImmediateOperand(op1);
2040    c->addImmediateOperand(op2);
2041    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
2042    module.mapInstruction(c);
2043
2044    Id resultId = c->getResultId();
2045    if (!specConstant) {
2046        ScalarConstantKey key{ enumCast(Op::OpTypeInt), enumCast(opcode), typeId, op1, op2 };
2047        groupedScalarConstantResultIDs[key] = resultId;
2048    }
2049    return resultId;
2050}
2051
2052Id Builder::makeFloatConstant(float f, bool specConstant)
2053{
2054    Op opcode = specConstant ? Op::OpSpecConstant : Op::OpConstant;
2055    Id typeId = makeFloatType(32);
2056    union { float fl; unsigned int ui; } u;
2057    u.fl = f;
2058    unsigned value = u.ui;
2059
2060    // See if we already made it. Applies only to regular constants, because specialization constants
2061    // must remain distinct for the purpose of applying a SpecId decoration.
2062    if (! specConstant) {
2063        Id existing = findScalarConstant(Op::OpTypeFloat, opcode, typeId, value);
2064        if (existing)
2065            return existing;
2066    }
2067
2068    Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
2069    c->addImmediateOperand(value);
2070    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
2071    module.mapInstruction(c);
2072
2073    Id resultId = c->getResultId();
2074    if (!specConstant) {
2075        ScalarConstantKey key{ enumCast(Op::OpTypeFloat), enumCast(opcode), typeId, value, 0 };
2076        groupedScalarConstantResultIDs[key] = resultId;
2077    }
2078    return resultId;
2079}
2080
2081Id Builder::makeDoubleConstant(double d, bool specConstant)
2082{
2083    Op opcode = specConstant ? Op::OpSpecConstant : Op::OpConstant;
2084    Id typeId = makeFloatType(64);
2085    union { double db; unsigned long long ull; } u;
2086    u.db = d;
2087    unsigned long long value = u.ull;
2088    unsigned op1 = value & 0xFFFFFFFF;
2089    unsigned op2 = value >> 32;
2090
2091    // See if we already made it. Applies only to regular constants, because specialization constants
2092    // must remain distinct for the purpose of applying a SpecId decoration.
2093    if (! specConstant) {
2094        Id existing = findScalarConstant(Op::OpTypeFloat, opcode, typeId, op1, op2);
2095        if (existing)
2096            return existing;
2097    }
2098
2099    Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
2100    c->reserveOperands(2);
2101    c->addImmediateOperand(op1);
2102    c->addImmediateOperand(op2);
2103    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
2104    module.mapInstruction(c);
2105
2106    Id resultId = c->getResultId();
2107    if (!specConstant) {
2108        ScalarConstantKey key{ enumCast(Op::OpTypeFloat), enumCast(opcode), typeId, op1, op2 };
2109        groupedScalarConstantResultIDs[key] = resultId;
2110    }
2111    return resultId;
2112}
2113
2114Id Builder::makeFloat16Constant(float f16, bool specConstant)
2115{
2116    Op opcode = specConstant ? Op::OpSpecConstant : Op::OpConstant;
2117    Id typeId = makeFloatType(16);
2118
2119    spvutils::HexFloat<spvutils::FloatProxy<float>> fVal(f16);
2120    spvutils::HexFloat<spvutils::FloatProxy<spvutils::Float16>> f16Val(0);
2121    fVal.castTo(f16Val, spvutils::kRoundToZero);
2122
2123    unsigned value = f16Val.value().getAsFloat().get_value();
2124
2125    // See if we already made it. Applies only to regular constants, because specialization constants
2126    // must remain distinct for the purpose of applying a SpecId decoration.
2127    if (!specConstant) {
2128        Id existing = findScalarConstant(Op::OpTypeFloat, opcode, typeId, value);
2129        if (existing)
2130            return existing;
2131    }
2132
2133    Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
2134    c->addImmediateOperand(value);
2135    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
2136    module.mapInstruction(c);
2137
2138    Id resultId = c->getResultId();
2139    if (!specConstant) {
2140        ScalarConstantKey key{ enumCast(Op::OpTypeFloat), enumCast(opcode), typeId, value, 0 };
2141        groupedScalarConstantResultIDs[key] = resultId;
2142    }
2143    return resultId;
2144}
2145
2146Id Builder::makeBFloat16Constant(float bf16, bool specConstant)
2147{
2148    Op opcode = specConstant ? Op::OpSpecConstant : Op::OpConstant;
2149    Id typeId = makeBFloat16Type();
2150
2151    union {
2152        float f;
2153        uint32_t u;
2154    } un;
2155    un.f = bf16;
2156
2157    // take high 16b of fp32 value. This is effectively round-to-zero, other than certain NaNs.
2158    unsigned value = un.u >> 16;
2159
2160    // See if we already made it. Applies only to regular constants, because specialization constants
2161    // must remain distinct for the purpose of applying a SpecId decoration.
2162    if (!specConstant) {
2163        Id existing = findScalarConstant(Op::OpTypeFloat, opcode, typeId, value);
2164        if (existing)
2165            return existing;
2166    }
2167
2168    Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
2169    c->addImmediateOperand(value);
2170    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
2171    module.mapInstruction(c);
2172
2173    Id resultId = c->getResultId();
2174    if (!specConstant) {
2175        ScalarConstantKey key{ enumCast(Op::OpTypeFloat), enumCast(opcode), typeId, value, 0 };
2176        groupedScalarConstantResultIDs[key] = resultId;
2177    }
2178    return resultId;
2179}
2180
2181template <typename SpvUtilsType>
2182Id Builder::makeFloatConstantHelper(float f, Id typeId, bool specConstant)
2183{
2184    Op opcode = specConstant ? Op::OpSpecConstant : Op::OpConstant;
2185
2186    spvutils::HexFloat<spvutils::FloatProxy<float>> fVal(f);
2187    spvutils::HexFloat<spvutils::FloatProxy<SpvUtilsType>> smallFloatVal(0);
2188    fVal.castTo(smallFloatVal, spvutils::kRoundToZero);
2189
2190    unsigned value = smallFloatVal.value().getAsFloat().get_value();
2191
2192    // See if we already made it. Applies only to regular constants, because specialization constants
2193    // must remain distinct for the purpose of applying a SpecId decoration.
2194    if (!specConstant) {
2195        Id existing = findScalarConstant(Op::OpTypeFloat, opcode, typeId, value);
2196        if (existing)
2197            return existing;
2198    }
2199
2200    Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
2201    c->addImmediateOperand(value);
2202    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
2203    module.mapInstruction(c);
2204
2205    Id resultId = c->getResultId();
2206    if (!specConstant) {
2207        ScalarConstantKey key{enumCast(Op::OpTypeFloat), enumCast(opcode), typeId, value, 0};
2208        groupedScalarConstantResultIDs[key] = resultId;
2209    }
2210    return resultId;
2211}
2212
2213Id Builder::makeFloatE5M2Constant(float fe5m2, bool specConstant)
2214{
2215    return makeFloatConstantHelper<spvutils::FloatE5M2>(fe5m2, makeFloatE5M2Type(), specConstant);
2216}
2217
2218Id Builder::makeFloatE4M3Constant(float fe4m3, bool specConstant)
2219{
2220    return makeFloatConstantHelper<spvutils::FloatE4M3>(fe4m3, makeFloatE4M3Type(), specConstant);
2221}
2222
2223Id Builder::makeFloatE2M1Constant(float fe2m1, bool specConstant)
2224{
2225    return makeFloatConstantHelper<spvutils::FloatE2M1>(fe2m1, makeFloatE2M1Type(), specConstant);
2226}
2227
2228Id Builder::makeFloatE3M2Constant(float fe3m2, bool specConstant)
2229{
2230    return makeFloatConstantHelper<spvutils::FloatE3M2>(fe3m2, makeFloatE3M2Type(), specConstant);
2231}
2232
2233Id Builder::makeFloatE2M3Constant(float fe2m3, bool specConstant)
2234{
2235    return makeFloatConstantHelper<spvutils::FloatE2M3>(fe2m3, makeFloatE2M3Type(), specConstant);
2236}
2237
2238Id Builder::makeFloatUE8M0Constant(float fue8m0, bool specConstant)
2239{
2240    Op opcode = specConstant ? Op::OpSpecConstant : Op::OpConstant;
2241    Id typeId = makeFloatUE8M0Type();
2242
2243    fue8m0 = std::max(fue8m0, 0.f);
2244    union {
2245        float f;
2246        uint32_t u;
2247    } un;
2248    un.f = fue8m0;
2249    // extract the exponent, this effectively rounds to zero.
2250    uint32_t value = un.u >> 23;
2251
2252    // See if we already made it. Applies only to regular constants, because specialization constants
2253    // must remain distinct for the purpose of applying a SpecId decoration.
2254    if (!specConstant) {
2255        Id existing = findScalarConstant(Op::OpTypeFloat, opcode, typeId, value);
2256        if (existing)
2257            return existing;
2258    }
2259
2260    Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
2261    c->addImmediateOperand(value);
2262    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
2263    module.mapInstruction(c);
2264
2265    Id resultId = c->getResultId();
2266    if (!specConstant) {
2267        ScalarConstantKey key{ enumCast(Op::OpTypeFloat), enumCast(opcode), typeId, value, 0 };
2268        groupedScalarConstantResultIDs[key] = resultId;
2269    }
2270    return resultId;
2271}
2272
2273Id Builder::makeFloatMXINT8Constant(float mxint8, bool specConstant)
2274{
2275    Op opcode = specConstant ? Op::OpSpecConstant : Op::OpConstant;
2276    Id typeId = makeFloatMXINT8Type();
2277
2278    // clamp and convert to fixed point.
2279    mxint8 = std::min(mxint8,  127.f/64.f);
2280    mxint8 = std::max(mxint8, -127.f/64.f);
2281    mxint8 *= 64;
2282    mxint8 = roundf(mxint8);
2283    uint32_t value = ((int32_t)mxint8) & 0xFF;
2284
2285    // See if we already made it. Applies only to regular constants, because specialization constants
2286    // must remain distinct for the purpose of applying a SpecId decoration.
2287    if (!specConstant) {
2288        Id existing = findScalarConstant(Op::OpTypeFloat, opcode, typeId, value);
2289        if (existing)
2290            return existing;
2291    }
2292
2293    Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
2294    c->addImmediateOperand(value);
2295    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
2296    module.mapInstruction(c);
2297
2298    Id resultId = c->getResultId();
2299    if (!specConstant) {
2300        ScalarConstantKey key{ enumCast(Op::OpTypeFloat), enumCast(opcode), typeId, value, 0 };
2301        groupedScalarConstantResultIDs[key] = resultId;
2302    }
2303    return resultId;
2304}
2305
2306Id Builder::makeFpConstant(Id type, double d, bool specConstant)
2307{
2308    const int width = getScalarTypeWidth(type);
2309
2310    assert(isFloatType(type));
2311
2312    switch (width) {
2313    case 16:
2314            return makeFloat16Constant((float)d, specConstant);
2315    case 32:
2316            return makeFloatConstant((float)d, specConstant);
2317    case 64:
2318            return makeDoubleConstant(d, specConstant);
2319    default:
2320            break;
2321    }
2322
2323    assert(false);
2324    return NoResult;
2325}
2326
2327Id Builder::importNonSemanticShaderDebugInfoInstructions()
2328{
2329    assert(emitNonSemanticShaderDebugInfo == true);
2330
2331    if(nonSemanticShaderDebugInfo == 0)
2332    {
2333        this->addExtension(spv::E_SPV_KHR_non_semantic_info);
2334        // Create the import instruction directly so we can save a pointer for later
2335        // patching by requireNonSemanticShaderDebugInfoVersion().
2336        std::string importName = "NonSemantic.Shader.DebugInfo." + std::to_string(nonSemanticShaderDebugInfoVersion);
2337        auto* importInst = new Instruction(getUniqueId(), NoType, Op::OpExtInstImport);
2338        importInst->addStringOperand(importName.c_str());
2339        module.mapInstruction(importInst);
2340        imports.push_back(std::unique_ptr<Instruction>(importInst));
2341        nonSemanticShaderDebugInfo = importInst->getResultId();
2342        nonSemanticShaderDebugInfoImportInst = importInst;
2343    }
2344
2345    return nonSemanticShaderDebugInfo;
2346}
2347
2348void Builder::requireNonSemanticShaderDebugInfoVersion(unsigned version)
2349{
2350    if (nonSemanticShaderDebugInfoVersion >= version)
2351        return;
2352    nonSemanticShaderDebugInfoVersion = version;
2353    if (nonSemanticShaderDebugInfoImportInst != nullptr) {
2354        // The import instruction was already emitted with an older version string.
2355        // Rebuild the string operands in place so all referencing OpExtInst instructions
2356        // automatically pick up the new name without needing new IDs.
2357        std::string importName = "NonSemantic.Shader.DebugInfo." + std::to_string(version);
2358        nonSemanticShaderDebugInfoImportInst->clearOperands();
2359        nonSemanticShaderDebugInfoImportInst->addStringOperand(importName.c_str());
2360    }
2361}
2362
2363Id Builder::findCompositeConstant(Op typeClass, Op opcode, Id typeId, const std::vector<Id>& comps, size_t numMembers)
2364{
2365    auto it = groupedCompositeConstants.find(
2366        CompositeConstantKey(typeClass, opcode, typeId, comps, numMembers));
2367    if (it != groupedCompositeConstants.end()) {
2368        const Instruction* constant = (*it).getInstruction();
2369        return constant->getResultId();
2370    }
2371    return NoResult;
2372}
2373
2374Id Builder::findStructConstant(Id typeId, const std::vector<Id>& comps, size_t numMembers)
2375{
2376    auto it = groupedStructConstants.find(StructConstantKey(typeId, comps, numMembers));
2377    if (it != groupedStructConstants.end()) {
2378        const Instruction* constant = (*it).getInstruction();
2379        return constant->getResultId();
2380    }
2381    return NoResult;
2382}
2383
2384// Comments in header
2385Id Builder::makeCompositeConstant(Id typeId, const std::vector<Id>& members, bool specConstant)
2386{
2387    assert(typeId);
2388    Op typeClass = getTypeClass(typeId);
2389
2390    bool replicate = false;
2391    size_t numMembers = members.size();
2392    if (useReplicatedComposites || typeClass == Op::OpTypeCooperativeVectorNV) {
2393        // use replicate if all members are the same
2394        replicate = numMembers > 0 &&
2395            std::equal(members.begin() + 1, members.end(), members.begin());
2396
2397        if (replicate) {
2398            numMembers = 1;
2399            addCapability(spv::Capability::ReplicatedCompositesEXT);
2400            addExtension(spv::E_SPV_EXT_replicated_composites);
2401        }
2402    }
2403
2404    Op opcode = replicate ?
2405        (specConstant ? Op::OpSpecConstantCompositeReplicateEXT : Op::OpConstantCompositeReplicateEXT) :
2406        (specConstant ? Op::OpSpecConstantComposite : Op::OpConstantComposite);
2407
2408    switch (typeClass) {
2409    case Op::OpTypeVector:
2410    case Op::OpTypeArray:
2411    case Op::OpTypeMatrix:
2412    case Op::OpTypeCooperativeMatrixKHR:
2413    case Op::OpTypeCooperativeMatrixNV:
2414    case Op::OpTypeCooperativeVectorNV:
2415        if (! specConstant) {
2416            Id existing = findCompositeConstant(typeClass, opcode, typeId, members, numMembers);
2417            if (existing)
2418                return existing;
2419        }
2420        break;
2421    case Op::OpTypeStruct:
2422        if (! specConstant) {
2423            Id existing = findStructConstant(typeId, members, numMembers);
2424            if (existing)
2425                return existing;
2426        }
2427        break;
2428    default:
2429        assert(0);
2430        return makeFloatConstant(0.0);
2431    }
2432
2433    Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
2434    c->reserveOperands(members.size());
2435    for (size_t op = 0; op < numMembers; ++op)
2436        c->addIdOperand(members[op]);
2437    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
2438    if (typeClass == Op::OpTypeStruct)
2439        groupedStructConstants.insert(StructConstantKey(c));
2440    else
2441        groupedCompositeConstants.insert(CompositeConstantKey(typeClass, c));
2442    module.mapInstruction(c);
2443
2444    return c->getResultId();
2445}
2446
2447Instruction* Builder::addEntryPoint(ExecutionModel model, Function* function, const char* name)
2448{
2449    Instruction* entryPoint = new Instruction(Op::OpEntryPoint);
2450    entryPoint->reserveOperands(3);
2451    entryPoint->addImmediateOperand(model);
2452    entryPoint->addIdOperand(function->getId());
2453    entryPoint->addStringOperand(name);
2454
2455    entryPoints.push_back(std::unique_ptr<Instruction>(entryPoint));
2456
2457    return entryPoint;
2458}
2459
2460// Currently relying on the fact that all 'value' of interest are small non-negative values.
2461void Builder::addExecutionMode(Function* entryPoint, ExecutionMode mode, int value1, int value2, int value3)
2462{
2463    // entryPoint can be null if we are in compile-only mode
2464    if (!entryPoint)
2465        return;
2466
2467    Instruction* instr = new Instruction(Op::OpExecutionMode);
2468    instr->reserveOperands(3);
2469    instr->addIdOperand(entryPoint->getId());
2470    instr->addImmediateOperand(mode);
2471    if (value1 >= 0)
2472        instr->addImmediateOperand(value1);
2473    if (value2 >= 0)
2474        instr->addImmediateOperand(value2);
2475    if (value3 >= 0)
2476        instr->addImmediateOperand(value3);
2477
2478    executionModes.push_back(std::unique_ptr<Instruction>(instr));
2479}
2480
2481void Builder::addExecutionMode(Function* entryPoint, ExecutionMode mode, const std::vector<unsigned>& literals)
2482{
2483    // entryPoint can be null if we are in compile-only mode
2484    if (!entryPoint)
2485        return;
2486
2487    Instruction* instr = new Instruction(Op::OpExecutionMode);
2488    instr->reserveOperands(literals.size() + 2);
2489    instr->addIdOperand(entryPoint->getId());
2490    instr->addImmediateOperand(mode);
2491    for (auto literal : literals)
2492        instr->addImmediateOperand(literal);
2493
2494    executionModes.push_back(std::unique_ptr<Instruction>(instr));
2495}
2496
2497void Builder::addExecutionModeId(Function* entryPoint, ExecutionMode mode, const std::vector<Id>& operandIds)
2498{
2499    // entryPoint can be null if we are in compile-only mode
2500    if (!entryPoint)
2501        return;
2502
2503    Instruction* instr = new Instruction(Op::OpExecutionModeId);
2504    instr->reserveOperands(operandIds.size() + 2);
2505    instr->addIdOperand(entryPoint->getId());
2506    instr->addImmediateOperand(mode);
2507    for (auto operandId : operandIds)
2508        instr->addIdOperand(operandId);
2509
2510    executionModes.push_back(std::unique_ptr<Instruction>(instr));
2511}
2512
2513void Builder::addName(Id id, const char* string)
2514{
2515    Instruction* name = new Instruction(Op::OpName);
2516    name->reserveOperands(2);
2517    name->addIdOperand(id);
2518    name->addStringOperand(string);
2519
2520    names.push_back(std::unique_ptr<Instruction>(name));
2521}
2522
2523void Builder::addMemberName(Id id, int memberNumber, const char* string)
2524{
2525    Instruction* name = new Instruction(Op::OpMemberName);
2526    name->reserveOperands(3);
2527    name->addIdOperand(id);
2528    name->addImmediateOperand(memberNumber);
2529    name->addStringOperand(string);
2530
2531    names.push_back(std::unique_ptr<Instruction>(name));
2532}
2533
2534void Builder::addDecoration(Id id, Decoration decoration, int num)
2535{
2536    if (decoration == spv::Decoration::Max)
2537        return;
2538
2539    Instruction* dec = new Instruction(Op::OpDecorate);
2540    dec->reserveOperands(2);
2541    dec->addIdOperand(id);
2542    dec->addImmediateOperand(decoration);
2543    if (num >= 0)
2544        dec->addImmediateOperand(num);
2545
2546    decorations.insert(std::unique_ptr<Instruction>(dec));
2547}
2548
2549void Builder::addDecoration(Id id, Decoration decoration, const char* s)
2550{
2551    if (decoration == spv::Decoration::Max)
2552        return;
2553
2554    Instruction* dec = new Instruction(Op::OpDecorateString);
2555    dec->reserveOperands(3);
2556    dec->addIdOperand(id);
2557    dec->addImmediateOperand(decoration);
2558    dec->addStringOperand(s);
2559
2560    decorations.insert(std::unique_ptr<Instruction>(dec));
2561}
2562
2563void Builder::addDecoration(Id id, Decoration decoration, const std::vector<unsigned>& literals)
2564{
2565    if (decoration == spv::Decoration::Max)
2566        return;
2567
2568    Instruction* dec = new Instruction(Op::OpDecorate);
2569    dec->reserveOperands(literals.size() + 2);
2570    dec->addIdOperand(id);
2571    dec->addImmediateOperand(decoration);
2572    for (auto literal : literals)
2573        dec->addImmediateOperand(literal);
2574
2575    decorations.insert(std::unique_ptr<Instruction>(dec));
2576}
2577
2578void Builder::addDecoration(Id id, Decoration decoration, const std::vector<const char*>& strings)
2579{
2580    if (decoration == spv::Decoration::Max)
2581        return;
2582
2583    Instruction* dec = new Instruction(Op::OpDecorateString);
2584    dec->reserveOperands(strings.size() + 2);
2585    dec->addIdOperand(id);
2586    dec->addImmediateOperand(decoration);
2587    for (auto string : strings)
2588        dec->addStringOperand(string);
2589
2590    decorations.insert(std::unique_ptr<Instruction>(dec));
2591}
2592
2593void Builder::addLinkageDecoration(Id id, const char* name, spv::LinkageType linkType) {
2594    Instruction* dec = new Instruction(Op::OpDecorate);
2595    dec->reserveOperands(4);
2596    dec->addIdOperand(id);
2597    dec->addImmediateOperand(spv::Decoration::LinkageAttributes);
2598    dec->addStringOperand(name);
2599    dec->addImmediateOperand(linkType);
2600
2601    decorations.insert(std::unique_ptr<Instruction>(dec));
2602}
2603
2604void Builder::addDecorationId(Id id, Decoration decoration, Id idDecoration)
2605{
2606    if (decoration == spv::Decoration::Max)
2607        return;
2608
2609    Instruction* dec = new Instruction(Op::OpDecorateId);
2610    dec->reserveOperands(3);
2611    dec->addIdOperand(id);
2612    dec->addImmediateOperand(decoration);
2613    dec->addIdOperand(idDecoration);
2614
2615    decorations.insert(std::unique_ptr<Instruction>(dec));
2616}
2617
2618void Builder::addDecorationId(Id id, Decoration decoration, const std::vector<Id>& operandIds)
2619{
2620    if(decoration == spv::Decoration::Max)
2621        return;
2622
2623    Instruction* dec = new Instruction(Op::OpDecorateId);
2624    dec->reserveOperands(operandIds.size() + 2);
2625    dec->addIdOperand(id);
2626    dec->addImmediateOperand(decoration);
2627
2628    for (auto operandId : operandIds)
2629        dec->addIdOperand(operandId);
2630
2631    decorations.insert(std::unique_ptr<Instruction>(dec));
2632}
2633
2634void Builder::addMemberDecorationIdEXT(Id id, unsigned int member, Decoration decoration,
2635                                       const std::vector<unsigned>& operands)
2636{
2637    if (decoration == spv::Decoration::Max)
2638        return;
2639
2640    Instruction* dec = new Instruction(Op::OpMemberDecorateIdEXT);
2641    dec->reserveOperands(operands.size() + 3);
2642    dec->addIdOperand(id);
2643    dec->addImmediateOperand(member);
2644    dec->addImmediateOperand(decoration);
2645    for (auto operand : operands)
2646        dec->addIdOperand(operand);
2647
2648    decorations.insert(std::unique_ptr<Instruction>(dec));
2649}
2650
2651void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, int num)
2652{
2653    if (decoration == spv::Decoration::Max)
2654        return;
2655
2656    Instruction* dec = new Instruction(Op::OpMemberDecorate);
2657    dec->reserveOperands(3);
2658    dec->addIdOperand(id);
2659    dec->addImmediateOperand(member);
2660    dec->addImmediateOperand(decoration);
2661    if (num >= 0)
2662        dec->addImmediateOperand(num);
2663
2664    decorations.insert(std::unique_ptr<Instruction>(dec));
2665}
2666
2667void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, const char *s)
2668{
2669    if (decoration == spv::Decoration::Max)
2670        return;
2671
2672    Instruction* dec = new Instruction(Op::OpMemberDecorateStringGOOGLE);
2673    dec->reserveOperands(4);
2674    dec->addIdOperand(id);
2675    dec->addImmediateOperand(member);
2676    dec->addImmediateOperand(decoration);
2677    dec->addStringOperand(s);
2678
2679    decorations.insert(std::unique_ptr<Instruction>(dec));
2680}
2681
2682void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, const std::vector<unsigned>& literals)
2683{
2684    if (decoration == spv::Decoration::Max)
2685        return;
2686
2687    Instruction* dec = new Instruction(Op::OpMemberDecorate);
2688    dec->reserveOperands(literals.size() + 3);
2689    dec->addIdOperand(id);
2690    dec->addImmediateOperand(member);
2691    dec->addImmediateOperand(decoration);
2692    for (auto literal : literals)
2693        dec->addImmediateOperand(literal);
2694
2695    decorations.insert(std::unique_ptr<Instruction>(dec));
2696}
2697
2698void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, const std::vector<const char*>& strings)
2699{
2700    if (decoration == spv::Decoration::Max)
2701        return;
2702
2703    Instruction* dec = new Instruction(Op::OpMemberDecorateString);
2704    dec->reserveOperands(strings.size() + 3);
2705    dec->addIdOperand(id);
2706    dec->addImmediateOperand(member);
2707    dec->addImmediateOperand(decoration);
2708    for (auto string : strings)
2709        dec->addStringOperand(string);
2710
2711    decorations.insert(std::unique_ptr<Instruction>(dec));
2712}
2713
2714void Builder::addInstruction(std::unique_ptr<Instruction> inst) {
2715    // Phis must appear first in their block, don't insert line tracking instructions
2716    // in front of them, just add the OpPhi and return.
2717    if (inst->getOpCode() == Op::OpPhi) {
2718        buildPoint->addInstruction(std::move(inst));
2719        return;
2720    }
2721    // Optionally insert OpDebugScope
2722    if (emitNonSemanticShaderDebugInfo && dirtyScopeTracker) {
2723        if (buildPoint->updateDebugScope(currentDebugScopeId.top())) {
2724            auto scopeInst = std::make_unique<Instruction>(getUniqueId(), makeVoidType(), Op::OpExtInst);
2725            scopeInst->reserveOperands(3);
2726            scopeInst->addIdOperand(nonSemanticShaderDebugInfo);
2727            scopeInst->addImmediateOperand(NonSemanticShaderDebugInfoDebugScope);
2728            scopeInst->addIdOperand(currentDebugScopeId.top());
2729            buildPoint->addInstruction(std::move(scopeInst));
2730        }
2731
2732        dirtyScopeTracker = false;
2733    }
2734
2735    // Insert OpLine/OpDebugLine if the debug source location has changed
2736    if (trackDebugInfo && dirtyLineTracker) {
2737        if (buildPoint->updateDebugSourceLocation(currentLine, 0, currentFileId)) {
2738            if (emitSpirvDebugInfo) {
2739                auto lineInst = std::make_unique<Instruction>(Op::OpLine);
2740                lineInst->reserveOperands(3);
2741                lineInst->addIdOperand(currentFileId);
2742                lineInst->addImmediateOperand(currentLine);
2743                lineInst->addImmediateOperand(0);
2744                buildPoint->addInstruction(std::move(lineInst));
2745            }
2746            if (emitNonSemanticShaderDebugInfo) {
2747                auto lineInst = std::make_unique<Instruction>(getUniqueId(), makeVoidType(), Op::OpExtInst);
2748                lineInst->reserveOperands(7);
2749                lineInst->addIdOperand(nonSemanticShaderDebugInfo);
2750                lineInst->addImmediateOperand(NonSemanticShaderDebugInfoDebugLine);
2751                lineInst->addIdOperand(makeDebugSource(currentFileId));
2752                lineInst->addIdOperand(makeUintConstant(currentLine));
2753                lineInst->addIdOperand(makeUintConstant(currentLine));
2754                lineInst->addIdOperand(makeUintConstant(0));
2755                lineInst->addIdOperand(makeUintConstant(0));
2756                buildPoint->addInstruction(std::move(lineInst));
2757            }
2758        }
2759
2760        dirtyLineTracker = false;
2761    }
2762
2763    buildPoint->addInstruction(std::move(inst));
2764}
2765
2766void Builder::addInstructionNoDebugInfo(std::unique_ptr<Instruction> inst) {
2767    buildPoint->addInstruction(std::move(inst));
2768}
2769
2770// Comments in header
2771Function* Builder::makeEntryPoint(const char* entryPoint)
2772{
2773    assert(! entryPointFunction);
2774
2775    auto const returnType = makeVoidType();
2776
2777    restoreNonSemanticShaderDebugInfo = emitNonSemanticShaderDebugInfo;
2778    if(sourceLang == spv::SourceLanguage::HLSL) {
2779        emitNonSemanticShaderDebugInfo = false;
2780    }
2781
2782    Block* entry = nullptr;
2783    entryPointFunction = makeFunctionEntry(NoPrecision, returnType, entryPoint, LinkageType::Max, {}, {}, &entry);
2784
2785    emitNonSemanticShaderDebugInfo = restoreNonSemanticShaderDebugInfo;
2786
2787    return entryPointFunction;
2788}
2789
2790// Comments in header
2791Function* Builder::makeFunctionEntry(Decoration precision, Id returnType, const char* name, LinkageType linkType,
2792                                     const std::vector<Id>& paramTypes,
2793                                     const std::vector<std::vector<Decoration>>& decorations, Block** entry)
2794{
2795    // Make the function and initial instructions in it
2796    Id typeId = makeFunctionType(returnType, paramTypes);
2797    Id firstParamId = paramTypes.size() == 0 ? 0 : getUniqueIds((int)paramTypes.size());
2798    Id funcId = getUniqueId();
2799    Function* function = new Function(funcId, returnType, typeId, firstParamId, linkType, name, module);
2800
2801    // Set up the precisions
2802    setPrecision(function->getId(), precision);
2803    function->setReturnPrecision(precision);
2804    for (unsigned p = 0; p < (unsigned)decorations.size(); ++p) {
2805        for (int d = 0; d < (int)decorations[p].size(); ++d) {
2806            addDecoration(firstParamId + p, decorations[p][d]);
2807            function->addParamPrecision(p, decorations[p][d]);
2808        }
2809    }
2810
2811    // reset last debug scope
2812    if (emitNonSemanticShaderDebugInfo) {
2813        dirtyScopeTracker = true;
2814    }
2815
2816    // CFG
2817    assert(entry != nullptr);
2818    *entry = new Block(getUniqueId(), *function);
2819    function->addBlock(*entry);
2820    setBuildPoint(*entry);
2821
2822    if (name)
2823        addName(function->getId(), name);
2824
2825    functions.push_back(std::unique_ptr<Function>(function));
2826
2827    return function;
2828}
2829
2830void Builder::setupFunctionDebugInfo(Function* function, const char* name, const std::vector<Id>& paramTypes,
2831                                     const std::vector<char const*>& paramNames)
2832{
2833
2834    if (!emitNonSemanticShaderDebugInfo)
2835        return;
2836
2837    Id nameId = getStringId(unmangleFunctionName(name));
2838    Id funcTypeId = function->getFuncTypeId();
2839    assert(getDebugType(funcTypeId) != NoType);
2840    Id funcId = function->getId();
2841
2842    assert(funcId != 0);
2843
2844    // Make the debug function instruction
2845    Id debugFuncId = makeDebugFunction(function, nameId, funcTypeId);
2846    debugFuncIdLookup[funcId] = debugFuncId;
2847    currentDebugScopeId.push(debugFuncId);
2848
2849    // DebugScope and DebugLine for parameter DebugDeclares
2850    assert(paramTypes.size() == paramNames.size());
2851    if ((int)paramTypes.size() > 0) {
2852        Id firstParamId = function->getParamId(0);
2853
2854        for (size_t p = 0; p < paramTypes.size(); ++p) {
2855            bool passByRef = false;
2856            Id paramTypeId = paramTypes[p];
2857
2858            // For pointer-typed parameters, they are actually passed by reference and we need unwrap the pointer to get the actual parameter type.
2859            if (isPointerType(paramTypeId) || isArrayType(paramTypeId)) {
2860                passByRef = true;
2861                paramTypeId = getContainedTypeId(paramTypeId);
2862            }
2863
2864            auto const& paramName = paramNames[p];
2865            auto const debugLocalVariableId = createDebugLocalVariable(getDebugType(paramTypeId), paramName, p + 1);
2866            auto const paramId = static_cast<Id>(firstParamId + p);
2867
2868            if (passByRef) {
2869                makeDebugDeclare(debugLocalVariableId, paramId);
2870            } else {
2871                makeDebugValue(debugLocalVariableId, paramId);
2872            }
2873        }
2874    }
2875
2876    // Clear debug scope stack
2877    if (emitNonSemanticShaderDebugInfo)
2878        currentDebugScopeId.pop();
2879}
2880
2881Id Builder::makeDebugFunction([[maybe_unused]] Function* function, Id nameId, Id funcTypeId)
2882{
2883    assert(function != nullptr);
2884    assert(nameId != 0);
2885    assert(funcTypeId != 0);
2886    assert(getDebugType(funcTypeId) != NoType);
2887
2888    Id funcId = getUniqueId();
2889    auto type = new Instruction(funcId, makeVoidType(), Op::OpExtInst);
2890    type->reserveOperands(11);
2891    type->addIdOperand(nonSemanticShaderDebugInfo);
2892    type->addImmediateOperand(NonSemanticShaderDebugInfoDebugFunction);
2893    type->addIdOperand(nameId);
2894    type->addIdOperand(getDebugType(funcTypeId));
2895    type->addIdOperand(makeDebugSource(currentFileId)); // TODO: This points to file of definition instead of declaration
2896    type->addIdOperand(makeUintConstant(currentLine)); // TODO: This points to line of definition instead of declaration
2897    type->addIdOperand(makeUintConstant(0)); // column
2898    type->addIdOperand(makeDebugCompilationUnit()); // scope
2899    type->addIdOperand(nameId); // linkage name
2900    type->addIdOperand(makeUintConstant(NonSemanticShaderDebugInfoFlagIsPublic));
2901    type->addIdOperand(makeUintConstant(currentLine));
2902    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
2903    module.mapInstruction(type);
2904    return funcId;
2905}
2906
2907Id Builder::makeDebugEntryPoint(Function* function, const char* compilerSignature, const char* commandLineArguments,
2908                                const char* currentWorkingDirectory)
2909{
2910    assert(function != nullptr);
2911    assert(compilerSignature != nullptr);
2912    assert(commandLineArguments != nullptr);
2913
2914    const Id debugFunction = getDebugFunction(function->getId());
2915    assert(debugFunction != NoResult);
2916
2917    if (currentWorkingDirectory != nullptr)
2918        requireNonSemanticShaderDebugInfoVersion(NonSemanticShaderDebugInfoVersion);
2919
2920    const Id entryPointId = getUniqueId();
2921    auto entryPoint = new Instruction(entryPointId, makeVoidType(), Op::OpExtInst);
2922    entryPoint->reserveOperands(currentWorkingDirectory == nullptr ? 6 : 7);
2923    entryPoint->addIdOperand(nonSemanticShaderDebugInfo);
2924    entryPoint->addImmediateOperand(NonSemanticShaderDebugInfoDebugEntryPoint);
2925    entryPoint->addIdOperand(debugFunction);
2926    entryPoint->addIdOperand(makeDebugCompilationUnit());
2927    entryPoint->addIdOperand(getStringId(compilerSignature));
2928    entryPoint->addIdOperand(getStringId(commandLineArguments));
2929    if (currentWorkingDirectory != nullptr)
2930        entryPoint->addIdOperand(getStringId(currentWorkingDirectory));
2931    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(entryPoint));
2932    module.mapInstruction(entryPoint);
2933    return entryPointId;
2934}
2935
2936Id Builder::makeDebugLexicalBlock(uint32_t line, uint32_t column) {
2937    assert(!currentDebugScopeId.empty());
2938
2939    Id lexId = getUniqueId();
2940    auto lex = new Instruction(lexId, makeVoidType(), Op::OpExtInst);
2941    lex->reserveOperands(6);
2942    lex->addIdOperand(nonSemanticShaderDebugInfo);
2943    lex->addImmediateOperand(NonSemanticShaderDebugInfoDebugLexicalBlock);
2944    lex->addIdOperand(makeDebugSource(currentFileId));
2945    lex->addIdOperand(makeUintConstant(line));
2946    lex->addIdOperand(makeUintConstant(column)); // column
2947    lex->addIdOperand(currentDebugScopeId.top()); // scope
2948    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(lex));
2949    module.mapInstruction(lex);
2950    return lexId;
2951}
2952
2953std::string Builder::unmangleFunctionName(std::string const& name) const
2954{
2955    assert(name.length() > 0);
2956
2957    if(name.rfind('(') != std::string::npos) {
2958        return name.substr(0, name.rfind('('));
2959    } else {
2960        return name;
2961    }
2962}
2963
2964// Comments in header
2965void Builder::makeReturn(bool implicit, Id retVal)
2966{
2967    if (retVal) {
2968        Instruction* inst = new Instruction(NoResult, NoType, Op::OpReturnValue);
2969        inst->addIdOperand(retVal);
2970        addInstruction(std::unique_ptr<Instruction>(inst));
2971    } else
2972        addInstruction(std::unique_ptr<Instruction>(new Instruction(NoResult, NoType, Op::OpReturn)));
2973
2974    if (! implicit)
2975        createAndSetNoPredecessorBlock("post-return");
2976}
2977
2978// Comments in header
2979void Builder::enterLexicalBlock(uint32_t line, uint32_t column)
2980{
2981    if (!emitNonSemanticShaderDebugInfo) {
2982        return;
2983    }
2984
2985    // Generate new lexical scope debug instruction
2986    Id lexId = makeDebugLexicalBlock(line, column);
2987    currentDebugScopeId.push(lexId);
2988    dirtyScopeTracker = true;
2989}
2990
2991// Comments in header
2992void Builder::leaveLexicalBlock()
2993{
2994    if (!emitNonSemanticShaderDebugInfo) {
2995        return;
2996    }
2997
2998    // Pop current scope from stack and clear current scope
2999    currentDebugScopeId.pop();
3000    dirtyScopeTracker = true;
3001}
3002
3003// Comments in header
3004void Builder::enterFunction(Function const* function)
3005{
3006    currentFunction = function;
3007
3008    // Save and disable debugInfo for HLSL entry point function. It is a wrapper
3009    // function with no user code in it.
3010    restoreNonSemanticShaderDebugInfo = emitNonSemanticShaderDebugInfo;
3011    if (sourceLang == spv::SourceLanguage::HLSL && function == entryPointFunction) {
3012        emitNonSemanticShaderDebugInfo = false;
3013    }
3014
3015    if (emitNonSemanticShaderDebugInfo) {
3016        // Initialize scope state
3017        Id funcId = function->getFuncId();
3018        Id debugFuncId = getDebugFunction(funcId);
3019        currentDebugScopeId.push(debugFuncId);
3020        // Create DebugFunctionDefinition
3021        spv::Id resultId = getUniqueId();
3022        Instruction* defInst = new Instruction(resultId, makeVoidType(), Op::OpExtInst);
3023        defInst->reserveOperands(4);
3024        defInst->addIdOperand(nonSemanticShaderDebugInfo);
3025        defInst->addImmediateOperand(NonSemanticShaderDebugInfoDebugFunctionDefinition);
3026        defInst->addIdOperand(debugFuncId);
3027        defInst->addIdOperand(funcId);
3028        addInstruction(std::unique_ptr<Instruction>(defInst));
3029    }
3030
3031    if (auto linkType = function->getLinkType(); linkType != LinkageType::Max) {
3032        Id funcId = function->getFuncId();
3033        addCapability(Capability::Linkage);
3034        addLinkageDecoration(funcId, function->getExportName(), linkType);
3035    }
3036}
3037
3038// Comments in header
3039void Builder::leaveFunction()
3040{
3041    Block* block = buildPoint;
3042    Function& function = buildPoint->getParent();
3043    assert(block);
3044
3045    // If our function did not contain a return, add a return void now.
3046    if (! block->isTerminated()) {
3047        if (function.getReturnType() == makeVoidType())
3048            makeReturn(true);
3049        else {
3050            makeReturn(true, createUndefined(function.getReturnType()));
3051        }
3052    }
3053
3054    // Clear function scope from debug scope stack
3055    if (emitNonSemanticShaderDebugInfo)
3056        currentDebugScopeId.pop();
3057
3058    emitNonSemanticShaderDebugInfo = restoreNonSemanticShaderDebugInfo;
3059
3060    // Clear current function record
3061    currentFunction = nullptr;
3062}
3063
3064// Comments in header
3065void Builder::makeStatementTerminator(spv::Op opcode, const char *name)
3066{
3067    addInstruction(std::unique_ptr<Instruction>(new Instruction(opcode)));
3068    createAndSetNoPredecessorBlock(name);
3069}
3070
3071// Comments in header
3072void Builder::makeStatementTerminator(spv::Op opcode, const std::vector<Id>& operands, const char* name)
3073{
3074    // It's assumed that the terminator instruction is always of void return type
3075    // However in future if there is a need for non void return type, new helper
3076    // methods can be created.
3077    createNoResultOp(opcode, operands);
3078    createAndSetNoPredecessorBlock(name);
3079}
3080
3081void Builder::createConstVariable(Id type, const char* name, Id constant, bool isGlobal)
3082{
3083    if (emitNonSemanticShaderDebugInfo) {
3084        Id debugType = getDebugType(type);
3085        if (isGlobal) {
3086            createDebugGlobalVariable(debugType, name, constant);
3087        }
3088        else {
3089            auto debugLocal = createDebugLocalVariable(debugType, name);
3090            makeDebugValue(debugLocal, constant);
3091        }
3092    }
3093}
3094
3095// Comments in header
3096Id Builder::createUntypedVariable(Decoration precision, StorageClass storageClass, const char* name, Id dataType,
3097                                  Id initializer)
3098{
3099    Id resultUntypedPointerType = makeUntypedPointer(storageClass);
3100    Instruction* inst = new Instruction(getUniqueId(), resultUntypedPointerType, Op::OpUntypedVariableKHR);
3101    inst->addImmediateOperand(storageClass);
3102    if (dataType != NoResult) {
3103        Id dataPointerType = makePointer(storageClass, dataType);
3104        inst->addIdOperand(dataPointerType);
3105    }
3106    if (initializer != NoResult)
3107        inst->addIdOperand(initializer);
3108
3109    switch (storageClass) {
3110    case StorageClass::Function:
3111        // Validation rules require the declaration in the entry block
3112        buildPoint->getParent().addLocalVariable(std::unique_ptr<Instruction>(inst));
3113        break;
3114    default:
3115        constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
3116        module.mapInstruction(inst);
3117        break;
3118    }
3119
3120    if (name)
3121        addName(inst->getResultId(), name);
3122    setPrecision(inst->getResultId(), precision);
3123
3124    return inst->getResultId();
3125}
3126
3127// Comments in header
3128Id Builder::createVariable(Decoration precision, StorageClass storageClass, Id type, const char* name, Id initializer,
3129    bool const compilerGenerated)
3130{
3131    Id pointerType = makePointer(storageClass, type);
3132    Instruction* inst = new Instruction(getUniqueId(), pointerType, Op::OpVariable);
3133    inst->addImmediateOperand(storageClass);
3134    if (initializer != NoResult)
3135        inst->addIdOperand(initializer);
3136
3137    if (storageClass == StorageClass::Function) {
3138        // Validation rules require the declaration in the entry block
3139        buildPoint->getParent().addLocalVariable(std::unique_ptr<Instruction>(inst));
3140    }
3141    else {
3142        constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
3143        module.mapInstruction(inst);
3144    }
3145
3146    if (emitNonSemanticShaderDebugInfo && !compilerGenerated)
3147    {
3148        // For debug info, we prefer respecting how the variable is declared in source code.
3149        // We may emulate some local variables as global variable with private storage in SPIR-V, but we still want to
3150        // treat them as local variables in debug info.
3151        if (storageClass == StorageClass::Function || (currentFunction && storageClass == StorageClass::Private)) {
3152            auto const debugLocalVariableId = createDebugLocalVariable(getDebugType(type), name);
3153            makeDebugDeclare(debugLocalVariableId, inst->getResultId());
3154        }
3155        else {
3156            createDebugGlobalVariable(getDebugType(type), name, inst->getResultId());
3157        }
3158    }
3159
3160    if (name)
3161        addName(inst->getResultId(), name);
3162    setPrecision(inst->getResultId(), precision);
3163
3164    return inst->getResultId();
3165}
3166
3167// Comments in header
3168Id Builder::createUndefined(Id type)
3169{
3170  Instruction* inst = new Instruction(getUniqueId(), type, Op::OpUndef);
3171  addInstruction(std::unique_ptr<Instruction>(inst));
3172  return inst->getResultId();
3173}
3174
3175// av/vis/nonprivate are unnecessary and illegal for some storage classes.
3176spv::MemoryAccessMask Builder::sanitizeMemoryAccessForStorageClass(spv::MemoryAccessMask memoryAccess, StorageClass sc)
3177    const
3178{
3179    switch (sc) {
3180    case spv::StorageClass::Uniform:
3181    case spv::StorageClass::Workgroup:
3182    case spv::StorageClass::StorageBuffer:
3183    case spv::StorageClass::PhysicalStorageBufferEXT:
3184        break;
3185    default:
3186        memoryAccess = spv::MemoryAccessMask(memoryAccess &
3187                        ~(spv::MemoryAccessMask::MakePointerAvailableKHR |
3188                          spv::MemoryAccessMask::MakePointerVisibleKHR |
3189                          spv::MemoryAccessMask::NonPrivatePointerKHR));
3190        break;
3191    }
3192    return memoryAccess;
3193}
3194
3195// Comments in header
3196void Builder::createStore(Id rValue, Id lValue, spv::MemoryAccessMask memoryAccess, spv::Scope scope,
3197    unsigned int alignment)
3198{
3199    Instruction* store = nullptr;
3200    if (isUntypedPointer(lValue))
3201        store = createDescHeapLoadStoreBaseRemap(lValue, Op::OpStore);
3202    else {
3203        store = new Instruction(Op::OpStore);
3204        store->reserveOperands(2);
3205        store->addIdOperand(lValue);
3206    }
3207    store->addIdOperand(rValue);
3208
3209    memoryAccess = sanitizeMemoryAccessForStorageClass(memoryAccess, getStorageClass(lValue));
3210
3211    if (memoryAccess != MemoryAccessMask::MaskNone) {
3212        store->addImmediateOperand(memoryAccess);
3213        if (anySet(memoryAccess, spv::MemoryAccessMask::Aligned)) {
3214            store->addImmediateOperand(alignment);
3215        }
3216        if (anySet(memoryAccess, spv::MemoryAccessMask::MakePointerAvailableKHR)) {
3217            store->addIdOperand(makeUintConstant(scope));
3218        }
3219    }
3220
3221    addInstruction(std::unique_ptr<Instruction>(store));
3222}
3223
3224// Comments in header
3225Id Builder::createLoad(Id lValue, spv::Decoration precision, spv::MemoryAccessMask memoryAccess,
3226    spv::Scope scope, unsigned int alignment)
3227{
3228    Instruction* load = nullptr;
3229    if (isUntypedPointer(lValue))
3230        load = createDescHeapLoadStoreBaseRemap(lValue, Op::OpLoad);
3231    else {
3232        load = new Instruction(getUniqueId(), getDerefTypeId(lValue), Op::OpLoad);
3233        load->addIdOperand(lValue);
3234    }
3235
3236    memoryAccess = sanitizeMemoryAccessForStorageClass(memoryAccess, getStorageClass(lValue));
3237
3238    if (memoryAccess != MemoryAccessMask::MaskNone) {
3239        load->addImmediateOperand(memoryAccess);
3240        if (anySet(memoryAccess, spv::MemoryAccessMask::Aligned)) {
3241            load->addImmediateOperand(alignment);
3242        }
3243        if (anySet(memoryAccess, spv::MemoryAccessMask::MakePointerVisibleKHR)) {
3244            load->addIdOperand(makeUintConstant(scope));
3245        }
3246    }
3247
3248    addInstruction(std::unique_ptr<Instruction>(load));
3249    setPrecision(load->getResultId(), precision);
3250
3251    return load->getResultId();
3252}
3253
3254Instruction* Builder::createDescHeapLoadStoreBaseRemap(Id baseId, Op op)
3255{
3256    // could only be untypedAccessChain op.
3257    spv::Op instOp = module.getInstruction(baseId)->getOpCode();
3258    spv::Id baseVal = baseId;
3259    // base type (from run time array)
3260    spv::Id resultTy = getIdOperand(baseId, 0);
3261    // Descriptor heap using run time array.
3262    if (accessChain.descHeapInfo.descStorageClass != StorageClass::Max)
3263        resultTy = getIdOperand(resultTy, 0);
3264    if (instOp != Op::OpUntypedAccessChainKHR) {
3265        assert(false && "Not a untyped load type");
3266    }
3267
3268    Instruction* inst = nullptr;
3269    if (op == Op::OpStore)
3270        inst = new Instruction(Op::OpStore);
3271    else {
3272        inst = new Instruction(getUniqueId(), resultTy, Op::OpLoad);
3273        accessChain.descHeapInfo.descHeapInstId.push_back(inst);
3274    }
3275    inst->addIdOperand(baseVal);
3276    return inst;
3277}
3278
3279spv::Id Builder::getOrCreateDescHeapByteArrayType()
3280{
3281    if (descHeapByteArrayType != NoResult)
3282        return descHeapByteArrayType;
3283
3284    addCapability(Capability::Int8);
3285    descHeapByteArrayType = makeRuntimeArray(makeUintType(8));
3286    addDecoration(descHeapByteArrayType, Decoration::ArrayStride, 1);
3287    return descHeapByteArrayType;
3288}
3289
3290// Comments in header
3291Id Builder::createDescHeapAccessChain()
3292{
3293    std::vector<Id>& heapOffsets = accessChain.descHeapInfo.descHeapIndexChain;
3294    assert(heapOffsets.size() != 0);
3295
3296    Id heapBase = accessChain.base;
3297    Id heapBaseTy = accessChain.descHeapInfo.descHeapBaseTy;
3298    Id heapBaseOffset = accessChain.descHeapInfo.descHeapBaseOffset;
3299    StorageClass storageClass = (StorageClass)accessChain.descHeapInfo.descStorageClass;
3300
3301    if (heapBaseOffset != NoResult) {
3302        const std::pair<Id, Id> cacheKey(heapBase, heapBaseOffset);
3303        auto cachedShiftedBase = descHeapShiftedBaseCache.find(cacheKey);
3304        if (cachedShiftedBase != descHeapShiftedBaseCache.end()) {
3305            heapBase = cachedShiftedBase->second;
3306        } else {
3307            Id shiftedBaseId = getUniqueId();
3308            const std::vector<Id> shiftedBaseOffsets(1, heapBaseOffset);
3309            heapBase = createUntypedAccessChain(getOrCreateDescHeapByteArrayType(), heapBase,
3310                shiftedBaseOffsets, shiftedBaseId);
3311            descHeapShiftedBaseCache.insert(std::make_pair(cacheKey, heapBase));
3312        }
3313    }
3314
3315    // First descriptor heap access chain
3316    Id chain = createUntypedAccessChain(heapBaseTy, heapBase, heapOffsets);
3317
3318    // Create OpBufferPointer for loading target buffer descriptor
3319    if (storageClass == spv::StorageClass::Uniform || storageClass == spv::StorageClass::StorageBuffer) {
3320        // Create OpBufferPointer for the descriptor, then use a typed access chain for buffer data.
3321        Id descriptorTy = accessChain.descHeapInfo.descTy;
3322        Id bufferPtrTy = makePointer(storageClass, descriptorTy);
3323        Instruction* bufferDataPtr = new Instruction(getUniqueId(), bufferPtrTy, Op::OpBufferPointerEXT);
3324        bufferDataPtr->addIdOperand(chain);
3325        addInstruction(std::unique_ptr<Instruction>(bufferDataPtr));
3326        if (accessChain.descHeapInfo.descWriteonly)
3327            addDecoration(bufferDataPtr->getResultId(), Decoration::NonReadable);
3328        if (accessChain.descHeapInfo.descReadonly && storageClass == StorageClass::StorageBuffer)
3329            addDecoration(bufferDataPtr->getResultId(), Decoration::NonWritable);
3330
3331        std::vector<Id>& offsets = accessChain.indexChain;
3332        if (offsets.empty())
3333            return bufferDataPtr->getResultId();
3334
3335        // Form a second, typed access chain for accessing buffer data.
3336        Id resultTy = descriptorTy;
3337        for (int i = 0; i < (int)offsets.size(); ++i) {
3338            if (isStructType(resultTy)) {
3339                assert(isConstantScalar(offsets[i]));
3340                resultTy = getContainedTypeId(resultTy, getConstantScalar(offsets[i]));
3341            } else
3342                resultTy = getContainedTypeId(resultTy, offsets[i]);
3343        }
3344        resultTy = makePointer(storageClass, resultTy);
3345
3346        Instruction* bufferChain = new Instruction(getUniqueId(), resultTy, Op::OpAccessChain);
3347        bufferChain->reserveOperands(offsets.size() + 1);
3348        bufferChain->addIdOperand(bufferDataPtr->getResultId());
3349        for (int i = 0; i < (int)offsets.size(); ++i)
3350            bufferChain->addIdOperand(offsets[i]);
3351        addInstruction(std::unique_ptr<Instruction>(bufferChain));
3352        return bufferChain->getResultId();
3353    }
3354
3355    return chain;
3356}
3357
3358// Comments in header
3359Id Builder::createAccessChain(StorageClass storageClass, Id base, const std::vector<Id>& offsets)
3360{
3361    // Figure out the final resulting type.
3362    Id typeId = getResultingAccessChainType();
3363    typeId = makePointer(storageClass, typeId);
3364
3365    // Make the instruction
3366    Instruction* chain = new Instruction(getUniqueId(), typeId, Op::OpAccessChain);
3367    chain->reserveOperands(offsets.size() + 1);
3368    chain->addIdOperand(base);
3369    for (int i = 0; i < (int)offsets.size(); ++i)
3370        chain->addIdOperand(offsets[i]);
3371    addInstruction(std::unique_ptr<Instruction>(chain));
3372
3373    return chain->getResultId();
3374}
3375
3376// Comments in header
3377Id Builder::createUntypedAccessChain(Id resultType, Id base, const std::vector<Id>& offsets, Id resultId)
3378{
3379    if (resultId == NoResult)
3380        resultId = getUniqueId();
3381
3382    Instruction* chain = new Instruction(resultId, makeUntypedPointer(getStorageClass(base)),
3383        Op::OpUntypedAccessChainKHR);
3384    chain->reserveOperands(offsets.size() + 2);
3385    chain->addIdOperand(resultType);
3386    chain->addIdOperand(base);
3387    for (int i = 0; i < (int)offsets.size(); ++i)
3388        chain->addIdOperand(offsets[i]);
3389    addInstruction(std::unique_ptr<Instruction>(chain));
3390
3391    return chain->getResultId();
3392}
3393
3394Id Builder::createArrayLength(Id base, unsigned int member, unsigned int bits)
3395{
3396    spv::Id intType = makeUintType(bits);
3397    Instruction* length = new Instruction(getUniqueId(), intType, Op::OpArrayLength);
3398    length->reserveOperands(2);
3399    length->addIdOperand(base);
3400    length->addImmediateOperand(member);
3401    addInstruction(std::unique_ptr<Instruction>(length));
3402
3403    return length->getResultId();
3404}
3405
3406Id Builder::createCooperativeMatrixLengthKHR(Id type)
3407{
3408    spv::Id intType = makeUintType(32);
3409
3410    // Generate code for spec constants if in spec constant operation
3411    // generation mode.
3412    if (generatingOpCodeForSpecConst) {
3413        return createSpecConstantOp(Op::OpCooperativeMatrixLengthKHR, intType, std::vector<Id>(1, type), std::vector<Id>());
3414    }
3415
3416    Instruction* length = new Instruction(getUniqueId(), intType, Op::OpCooperativeMatrixLengthKHR);
3417    length->addIdOperand(type);
3418    addInstruction(std::unique_ptr<Instruction>(length));
3419
3420    return length->getResultId();
3421}
3422
3423Id Builder::createCooperativeMatrixLengthNV(Id type)
3424{
3425    spv::Id intType = makeUintType(32);
3426
3427    // Generate code for spec constants if in spec constant operation
3428    // generation mode.
3429    if (generatingOpCodeForSpecConst) {
3430        return createSpecConstantOp(Op::OpCooperativeMatrixLengthNV, intType, std::vector<Id>(1, type), std::vector<Id>());
3431    }
3432
3433    Instruction* length = new Instruction(getUniqueId(), intType, Op::OpCooperativeMatrixLengthNV);
3434    length->addIdOperand(type);
3435    addInstruction(std::unique_ptr<Instruction>(length));
3436
3437    return length->getResultId();
3438}
3439
3440Id Builder::createCompositeExtract(Id composite, Id typeId, unsigned index)
3441{
3442    // Generate code for spec constants if in spec constant operation
3443    // generation mode.
3444    if (generatingOpCodeForSpecConst) {
3445        return createSpecConstantOp(Op::OpCompositeExtract, typeId, std::vector<Id>(1, composite),
3446            std::vector<Id>(1, index));
3447    }
3448    Instruction* extract = new Instruction(getUniqueId(), typeId, Op::OpCompositeExtract);
3449    extract->reserveOperands(2);
3450    extract->addIdOperand(composite);
3451    extract->addImmediateOperand(index);
3452    addInstruction(std::unique_ptr<Instruction>(extract));
3453
3454    return extract->getResultId();
3455}
3456
3457Id Builder::createCompositeExtract(Id composite, Id typeId, const std::vector<unsigned>& indexes)
3458{
3459    // Generate code for spec constants if in spec constant operation
3460    // generation mode.
3461    if (generatingOpCodeForSpecConst) {
3462        return createSpecConstantOp(Op::OpCompositeExtract, typeId, std::vector<Id>(1, composite), indexes);
3463    }
3464    Instruction* extract = new Instruction(getUniqueId(), typeId, Op::OpCompositeExtract);
3465    extract->reserveOperands(indexes.size() + 1);
3466    extract->addIdOperand(composite);
3467    for (int i = 0; i < (int)indexes.size(); ++i)
3468        extract->addImmediateOperand(indexes[i]);
3469    addInstruction(std::unique_ptr<Instruction>(extract));
3470
3471    return extract->getResultId();
3472}
3473
3474Id Builder::createCompositeInsert(Id object, Id composite, Id typeId, unsigned index)
3475{
3476    Instruction* insert = new Instruction(getUniqueId(), typeId, Op::OpCompositeInsert);
3477    insert->reserveOperands(3);
3478    insert->addIdOperand(object);
3479    insert->addIdOperand(composite);
3480    insert->addImmediateOperand(index);
3481    addInstruction(std::unique_ptr<Instruction>(insert));
3482
3483    return insert->getResultId();
3484}
3485
3486Id Builder::createCompositeInsert(Id object, Id composite, Id typeId, const std::vector<unsigned>& indexes)
3487{
3488    Instruction* insert = new Instruction(getUniqueId(), typeId, Op::OpCompositeInsert);
3489    insert->reserveOperands(indexes.size() + 2);
3490    insert->addIdOperand(object);
3491    insert->addIdOperand(composite);
3492    for (int i = 0; i < (int)indexes.size(); ++i)
3493        insert->addImmediateOperand(indexes[i]);
3494    addInstruction(std::unique_ptr<Instruction>(insert));
3495
3496    return insert->getResultId();
3497}
3498
3499Id Builder::createVectorExtractDynamic(Id vector, Id typeId, Id componentIndex)
3500{
3501    Instruction* extract = new Instruction(getUniqueId(), typeId, Op::OpVectorExtractDynamic);
3502    extract->reserveOperands(2);
3503    extract->addIdOperand(vector);
3504    extract->addIdOperand(componentIndex);
3505    addInstruction(std::unique_ptr<Instruction>(extract));
3506
3507    return extract->getResultId();
3508}
3509
3510Id Builder::createVectorInsertDynamic(Id vector, Id typeId, Id component, Id componentIndex)
3511{
3512    Instruction* insert = new Instruction(getUniqueId(), typeId, Op::OpVectorInsertDynamic);
3513    insert->reserveOperands(3);
3514    insert->addIdOperand(vector);
3515    insert->addIdOperand(component);
3516    insert->addIdOperand(componentIndex);
3517    addInstruction(std::unique_ptr<Instruction>(insert));
3518
3519    return insert->getResultId();
3520}
3521
3522// An opcode that has no operands, no result id, and no type
3523void Builder::createNoResultOp(Op opCode)
3524{
3525    Instruction* op = new Instruction(opCode);
3526    addInstruction(std::unique_ptr<Instruction>(op));
3527}
3528
3529// An opcode that has one id operand, no result id, and no type
3530void Builder::createNoResultOp(Op opCode, Id operand)
3531{
3532    Instruction* op = new Instruction(opCode);
3533    op->addIdOperand(operand);
3534    addInstruction(std::unique_ptr<Instruction>(op));
3535}
3536
3537// An opcode that has one or more operands, no result id, and no type
3538void Builder::createNoResultOp(Op opCode, const std::vector<Id>& operands)
3539{
3540    Instruction* op = new Instruction(opCode);
3541    op->reserveOperands(operands.size());
3542    for (auto id : operands) {
3543        op->addIdOperand(id);
3544    }
3545    addInstruction(std::unique_ptr<Instruction>(op));
3546}
3547
3548// An opcode that has multiple operands, no result id, and no type
3549void Builder::createNoResultOp(Op opCode, const std::vector<IdImmediate>& operands)
3550{
3551    Instruction* op = new Instruction(opCode);
3552    op->reserveOperands(operands.size());
3553    for (auto it = operands.cbegin(); it != operands.cend(); ++it) {
3554        if (it->isId)
3555            op->addIdOperand(it->word);
3556        else
3557            op->addImmediateOperand(it->word);
3558    }
3559    addInstruction(std::unique_ptr<Instruction>(op));
3560}
3561
3562void Builder::createControlBarrier(Scope execution, Scope memory, MemorySemanticsMask semantics)
3563{
3564    Instruction* op = new Instruction(Op::OpControlBarrier);
3565    op->reserveOperands(3);
3566    op->addIdOperand(makeUintConstant(execution));
3567    op->addIdOperand(makeUintConstant(memory));
3568    op->addIdOperand(makeUintConstant(semantics));
3569    addInstruction(std::unique_ptr<Instruction>(op));
3570}
3571
3572void Builder::createSplitControlBarrier(Op opcode, Scope execution, Scope memory, MemorySemanticsMask semantics)
3573{
3574    Instruction* op = new Instruction(opcode);
3575    op->reserveOperands(3);
3576    op->addIdOperand(makeUintConstant(execution));
3577    op->addIdOperand(makeUintConstant(memory));
3578    op->addIdOperand(makeUintConstant(semantics));
3579    addInstruction(std::unique_ptr<Instruction>(op));
3580}
3581
3582void Builder::createMemoryBarrier(Scope executionScope, MemorySemanticsMask memorySemantics)
3583{
3584    Instruction* op = new Instruction(Op::OpMemoryBarrier);
3585    op->reserveOperands(2);
3586    op->addIdOperand(makeUintConstant((unsigned)executionScope));
3587    op->addIdOperand(makeUintConstant((unsigned)memorySemantics));
3588    addInstruction(std::unique_ptr<Instruction>(op));
3589}
3590
3591// An opcode that has one operands, a result id, and a type
3592Id Builder::createUnaryOp(Op opCode, Id typeId, Id operand)
3593{
3594    // Generate code for spec constants if in spec constant operation
3595    // generation mode.
3596    if (generatingOpCodeForSpecConst) {
3597        return createSpecConstantOp(opCode, typeId, std::vector<Id>(1, operand), std::vector<Id>());
3598    }
3599    Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
3600    op->addIdOperand(operand);
3601    addInstruction(std::unique_ptr<Instruction>(op));
3602
3603    return op->getResultId();
3604}
3605
3606Id Builder::createBinOp(Op opCode, Id typeId, Id left, Id right)
3607{
3608    // Generate code for spec constants if in spec constant operation
3609    // generation mode.
3610    if (generatingOpCodeForSpecConst) {
3611        std::vector<Id> operands(2);
3612        operands[0] = left; operands[1] = right;
3613        return createSpecConstantOp(opCode, typeId, operands, std::vector<Id>());
3614    }
3615    Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
3616    op->reserveOperands(2);
3617    op->addIdOperand(left);
3618    op->addIdOperand(right);
3619    addInstruction(std::unique_ptr<Instruction>(op));
3620
3621    return op->getResultId();
3622}
3623
3624Id Builder::createTriOp(Op opCode, Id typeId, Id op1, Id op2, Id op3)
3625{
3626    // Generate code for spec constants if in spec constant operation
3627    // generation mode.
3628    if (generatingOpCodeForSpecConst) {
3629        std::vector<Id> operands(3);
3630        operands[0] = op1;
3631        operands[1] = op2;
3632        operands[2] = op3;
3633        return createSpecConstantOp(
3634            opCode, typeId, operands, std::vector<Id>());
3635    }
3636    Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
3637    op->reserveOperands(3);
3638    op->addIdOperand(op1);
3639    op->addIdOperand(op2);
3640    op->addIdOperand(op3);
3641    addInstruction(std::unique_ptr<Instruction>(op));
3642
3643    return op->getResultId();
3644}
3645
3646Id Builder::createConstData(Op opCode, Id typeId, const std::vector<const char*> operands)
3647{
3648    Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
3649    op->reserveOperands(operands.size());
3650    for (auto id : operands)
3651        op->addStringOperand(id);
3652    module.mapInstruction(op);
3653    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(op));
3654
3655    return op->getResultId();
3656}
3657
3658Id Builder::createOp(Op opCode, Id typeId, const std::vector<Id>& operands)
3659{
3660    Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
3661    op->reserveOperands(operands.size());
3662    for (auto id : operands)
3663        op->addIdOperand(id);
3664    addInstruction(std::unique_ptr<Instruction>(op));
3665
3666    return op->getResultId();
3667}
3668
3669Id Builder::createOp(Op opCode, Id typeId, const std::vector<IdImmediate>& operands)
3670{
3671    Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
3672    op->reserveOperands(operands.size());
3673    for (auto it = operands.cbegin(); it != operands.cend(); ++it) {
3674        if (it->isId)
3675            op->addIdOperand(it->word);
3676        else
3677            op->addImmediateOperand(it->word);
3678    }
3679    addInstruction(std::unique_ptr<Instruction>(op));
3680
3681    return op->getResultId();
3682}
3683
3684Id Builder::createSpecConstantOp(Op opCode, Id typeId, const std::vector<Id>& operands,
3685    const std::vector<unsigned>& literals)
3686{
3687    Instruction* op = new Instruction(getUniqueId(), typeId, Op::OpSpecConstantOp);
3688    op->reserveOperands(operands.size() + literals.size() + 1);
3689    op->addImmediateOperand((unsigned) opCode);
3690    for (auto it = operands.cbegin(); it != operands.cend(); ++it)
3691        op->addIdOperand(*it);
3692    for (auto it = literals.cbegin(); it != literals.cend(); ++it)
3693        op->addImmediateOperand(*it);
3694    module.mapInstruction(op);
3695    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(op));
3696
3697    // OpSpecConstantOp's using 8 or 16 bit types require the associated capability
3698    if (containsType(typeId, Op::OpTypeInt, 8))
3699        addCapability(Capability::Int8);
3700    if (containsType(typeId, Op::OpTypeInt, 16))
3701        addCapability(Capability::Int16);
3702    if (containsType(typeId, Op::OpTypeFloat, 16))
3703        addCapability(Capability::Float16);
3704
3705    return op->getResultId();
3706}
3707
3708Id Builder::createSpecConstantAlignTo(Id value, Id alignment)
3709{
3710    Id valueModAlignment = createSpecConstantOp(Op::OpUMod, makeUintType(32), {value, alignment}, {});
3711    Id paddingToAlignment = createSpecConstantOp(Op::OpISub, makeUintType(32), {alignment, valueModAlignment}, {});
3712    Id padding = createSpecConstantOp(Op::OpUMod, makeUintType(32), {paddingToAlignment, alignment}, {});
3713    return createSpecConstantOp(Op::OpIAdd, makeUintType(32), {value, padding}, {});
3714}
3715
3716Id Builder::createSpecConstantSelectMax(Id lhs, Id rhs)
3717{
3718    Id lhsGreater = createSpecConstantOp(Op::OpUGreaterThan, makeBoolType(), {lhs, rhs}, {});
3719    return createSpecConstantOp(Op::OpSelect, makeUintType(32), {lhsGreater, lhs, rhs}, {});
3720}
3721
3722Id Builder::createFunctionCall(spv::Function* function, const std::vector<spv::Id>& args)
3723{
3724    Instruction* op = new Instruction(getUniqueId(), function->getReturnType(), Op::OpFunctionCall);
3725    op->reserveOperands(args.size() + 1);
3726    op->addIdOperand(function->getId());
3727    for (int a = 0; a < (int)args.size(); ++a)
3728        op->addIdOperand(args[a]);
3729    addInstruction(std::unique_ptr<Instruction>(op));
3730
3731    return op->getResultId();
3732}
3733
3734// Comments in header
3735Id Builder::createRvalueSwizzle(Decoration precision, Id typeId, Id source, const std::vector<unsigned>& channels)
3736{
3737    if (channels.size() == 1)
3738        return setPrecision(createCompositeExtract(source, typeId, channels.front()), precision);
3739
3740    if (generatingOpCodeForSpecConst) {
3741        std::vector<Id> operands(2);
3742        operands[0] = operands[1] = source;
3743        return setPrecision(createSpecConstantOp(Op::OpVectorShuffle, typeId, operands, channels), precision);
3744    }
3745    Instruction* swizzle = new Instruction(getUniqueId(), typeId, Op::OpVectorShuffle);
3746    assert(isVector(source));
3747    swizzle->reserveOperands(channels.size() + 2);
3748    swizzle->addIdOperand(source);
3749    swizzle->addIdOperand(source);
3750    for (int i = 0; i < (int)channels.size(); ++i)
3751        swizzle->addImmediateOperand(channels[i]);
3752    addInstruction(std::unique_ptr<Instruction>(swizzle));
3753
3754    return setPrecision(swizzle->getResultId(), precision);
3755}
3756
3757// Comments in header
3758Id Builder::createLvalueSwizzle(Id typeId, Id target, Id source, const std::vector<unsigned>& channels)
3759{
3760    if (channels.size() == 1 && getNumComponents(source) == 1)
3761        return createCompositeInsert(source, target, typeId, channels.front());
3762
3763    Instruction* swizzle = new Instruction(getUniqueId(), typeId, Op::OpVectorShuffle);
3764
3765    assert(isVector(target));
3766    swizzle->reserveOperands(2);
3767    swizzle->addIdOperand(target);
3768
3769    assert(getNumComponents(source) == channels.size());
3770    assert(isVector(source));
3771    swizzle->addIdOperand(source);
3772
3773    // Set up an identity shuffle from the base value to the result value
3774    unsigned int components[4];
3775    int numTargetComponents = getNumComponents(target);
3776    for (int i = 0; i < numTargetComponents; ++i)
3777        components[i] = i;
3778
3779    // Punch in the l-value swizzle
3780    for (int i = 0; i < (int)channels.size(); ++i)
3781        components[channels[i]] = numTargetComponents + i;
3782
3783    // finish the instruction with these components selectors
3784    swizzle->reserveOperands(numTargetComponents);
3785    for (int i = 0; i < numTargetComponents; ++i)
3786        swizzle->addImmediateOperand(components[i]);
3787    addInstruction(std::unique_ptr<Instruction>(swizzle));
3788
3789    return swizzle->getResultId();
3790}
3791
3792// Comments in header
3793void Builder::promoteScalar(Decoration precision, Id& left, Id& right)
3794{
3795    // choose direction of promotion (+1 for left to right, -1 for right to left)
3796    int direction = !isScalar(right) - !isScalar(left);
3797
3798    auto const &makeVec = [&](Id component, Id other) {
3799        if (isCooperativeVector(other)) {
3800            return makeCooperativeVectorTypeNV(getTypeId(component), getCooperativeVectorNumComponents(getTypeId(other)));
3801        } else {
3802            return makeVectorType(getTypeId(component), getNumComponents(other));
3803        }
3804    };
3805
3806    if (direction > 0)
3807        left = smearScalar(precision, left, makeVec(left, right));
3808    else if (direction < 0)
3809        right = smearScalar(precision, right, makeVec(right, left));
3810
3811    return;
3812}
3813
3814// Comments in header
3815Id Builder::smearScalar(Decoration precision, Id scalar, Id vectorType)
3816{
3817    assert(getNumComponents(scalar) == 1);
3818    assert(getTypeId(scalar) == getScalarTypeId(vectorType));
3819
3820    int numComponents = getNumTypeComponents(vectorType);
3821    if (numComponents == 1 && !isCooperativeVectorType(vectorType) && !isVectorType(vectorType))
3822        return scalar;
3823
3824    Instruction* smear = nullptr;
3825    if (generatingOpCodeForSpecConst) {
3826        auto members = std::vector<spv::Id>(numComponents, scalar);
3827        // Sometime even in spec-constant-op mode, the temporary vector created by
3828        // promoting a scalar might not be a spec constant. This should depend on
3829        // the scalar.
3830        // e.g.:
3831        //  const vec2 spec_const_result = a_spec_const_vec2 + a_front_end_const_scalar;
3832        // In such cases, the temporary vector created from a_front_end_const_scalar
3833        // is not a spec constant vector, even though the binary operation node is marked
3834        // as 'specConstant' and we are in spec-constant-op mode.
3835        auto result_id = makeCompositeConstant(vectorType, members, isSpecConstant(scalar));
3836        smear = module.getInstruction(result_id);
3837    } else {
3838        bool replicate = (useReplicatedComposites || isCooperativeVectorType(vectorType)) && (numComponents > 0);
3839
3840        if (replicate) {
3841            numComponents = 1;
3842            addCapability(spv::Capability::ReplicatedCompositesEXT);
3843            addExtension(spv::E_SPV_EXT_replicated_composites);
3844        }
3845
3846        Op opcode = replicate ? Op::OpCompositeConstructReplicateEXT : Op::OpCompositeConstruct;
3847
3848        smear = new Instruction(getUniqueId(), vectorType, opcode);
3849        smear->reserveOperands(numComponents);
3850        for (int c = 0; c < numComponents; ++c)
3851            smear->addIdOperand(scalar);
3852        addInstruction(std::unique_ptr<Instruction>(smear));
3853    }
3854
3855    return setPrecision(smear->getResultId(), precision);
3856}
3857
3858// Comments in header
3859Id Builder::createBuiltinCall(Id resultType, Id builtins, int entryPoint, const std::vector<Id>& args)
3860{
3861    Instruction* inst = new Instruction(getUniqueId(), resultType, Op::OpExtInst);
3862    inst->reserveOperands(args.size() + 2);
3863    inst->addIdOperand(builtins);
3864    inst->addImmediateOperand(entryPoint);
3865    for (int arg = 0; arg < (int)args.size(); ++arg)
3866        inst->addIdOperand(args[arg]);
3867
3868    addInstruction(std::unique_ptr<Instruction>(inst));
3869
3870    return inst->getResultId();
3871}
3872
3873// Comments in header
3874Id Builder::createBuiltinCall(Id resultType, Id builtins, int entryPoint, const std::vector<IdImmediate>& args)
3875{
3876    Instruction* inst = new Instruction(getUniqueId(), resultType, Op::OpExtInst);
3877    inst->reserveOperands(args.size() + 2);
3878    inst->addIdOperand(builtins);
3879    inst->addImmediateOperand(entryPoint);
3880    for (auto it = args.cbegin(); it != args.cend(); ++it) {
3881        if (it->isId)
3882            inst->addIdOperand(it->word);
3883        else
3884            inst->addImmediateOperand(it->word);
3885    }
3886
3887    addInstruction(std::unique_ptr<Instruction>(inst));
3888
3889    return inst->getResultId();
3890}
3891
3892// Accept all parameters needed to create a texture instruction.
3893// Create the correct instruction based on the inputs, and make the call.
3894Id Builder::createTextureCall(Decoration precision, Id resultType, bool sparse, bool fetch, bool proj, bool gather,
3895    bool noImplicitLod, const TextureParameters& parameters, ImageOperandsMask signExtensionMask)
3896{
3897    std::vector<Id> texArgs;
3898
3899    //
3900    // Set up the fixed arguments
3901    //
3902    bool explicitLod = false;
3903    texArgs.push_back(parameters.sampler);
3904    texArgs.push_back(parameters.coords);
3905    if (parameters.Dref != NoResult)
3906        texArgs.push_back(parameters.Dref);
3907    if (parameters.component != NoResult)
3908        texArgs.push_back(parameters.component);
3909    if (gather && parameters.gatherMode != NoResult)
3910        texArgs.push_back(parameters.gatherMode);
3911
3912    if (parameters.granularity != NoResult)
3913        texArgs.push_back(parameters.granularity);
3914    if (parameters.coarse != NoResult)
3915        texArgs.push_back(parameters.coarse);
3916
3917    //
3918    // Set up the optional arguments
3919    //
3920    size_t optArgNum = texArgs.size(); // the position of the mask for the optional arguments, if any.
3921    ImageOperandsMask mask = ImageOperandsMask::MaskNone; // the mask operand
3922    if (parameters.bias) {
3923        mask = (ImageOperandsMask)(mask | ImageOperandsMask::Bias);
3924        texArgs.push_back(parameters.bias);
3925    }
3926    if (parameters.lod) {
3927        mask = (ImageOperandsMask)(mask | ImageOperandsMask::Lod);
3928        texArgs.push_back(parameters.lod);
3929        explicitLod = true;
3930    } else if (parameters.gradX) {
3931        mask = (ImageOperandsMask)(mask | ImageOperandsMask::Grad);
3932        texArgs.push_back(parameters.gradX);
3933        texArgs.push_back(parameters.gradY);
3934        explicitLod = true;
3935    } else if (noImplicitLod && ! fetch && ! gather) {
3936        // have to explicitly use lod of 0 if not allowed to have them be implicit, and
3937        // we would otherwise be about to issue an implicit instruction
3938        mask = (ImageOperandsMask)(mask | ImageOperandsMask::Lod);
3939        texArgs.push_back(makeFloatConstant(0.0));
3940        explicitLod = true;
3941    }
3942    if (parameters.offset) {
3943        if (isConstant(parameters.offset))
3944            mask = (ImageOperandsMask)(mask | ImageOperandsMask::ConstOffset);
3945        else {
3946            addCapability(Capability::ImageGatherExtended);
3947            mask = (ImageOperandsMask)(mask | ImageOperandsMask::Offset);
3948        }
3949        texArgs.push_back(parameters.offset);
3950    }
3951    if (parameters.offsets) {
3952        if (!isConstant(parameters.offsets) && sourceLang == spv::SourceLanguage::GLSL) {
3953            mask = (ImageOperandsMask)(mask | ImageOperandsMask::Offsets);
3954        } else {
3955            addCapability(Capability::ImageGatherExtended);
3956            mask = (ImageOperandsMask)(mask | ImageOperandsMask::ConstOffsets);
3957        }
3958        texArgs.push_back(parameters.offsets);
3959    }
3960    if (parameters.sample) {
3961        mask = (ImageOperandsMask)(mask | ImageOperandsMask::Sample);
3962        texArgs.push_back(parameters.sample);
3963    }
3964    if (parameters.lodClamp) {
3965        // capability if this bit is used
3966        addCapability(Capability::MinLod);
3967
3968        mask = (ImageOperandsMask)(mask | ImageOperandsMask::MinLod);
3969        texArgs.push_back(parameters.lodClamp);
3970    }
3971    if (parameters.nonprivate) {
3972        mask = mask | ImageOperandsMask::NonPrivateTexelKHR;
3973    }
3974    if (parameters.volatil) {
3975        mask = mask | ImageOperandsMask::VolatileTexelKHR;
3976    }
3977    if (parameters.nontemporal) {
3978        mask = mask | ImageOperandsMask::Nontemporal;
3979    }
3980    mask = mask | signExtensionMask;
3981    // insert the operand for the mask, if any bits were set.
3982    if (mask != ImageOperandsMask::MaskNone)
3983        texArgs.insert(texArgs.begin() + optArgNum, (Id)mask);
3984
3985    bool isTextureGatherExtended = (gather && parameters.gatherMode != NoResult);
3986
3987    //
3988    // Set up the instruction
3989    //
3990    Op opCode = Op::OpNop;  // All paths below need to set this
3991    if (fetch) {
3992        if (sparse)
3993            opCode = Op::OpImageSparseFetch;
3994        else
3995            opCode = Op::OpImageFetch;
3996    } else if (parameters.granularity && parameters.coarse) {
3997        opCode = Op::OpImageSampleFootprintNV;
3998    } else if (gather) {
3999        if (parameters.Dref)
4000            if (sparse)
4001                opCode = Op::OpImageSparseDrefGather;
4002            else
4003                opCode = Op::OpImageDrefGather;
4004        else
4005            if (sparse)
4006                opCode = Op::OpImageSparseGather;
4007            else if (isTextureGatherExtended)
4008                opCode = Op::OpImageGatherQCOM;
4009            else
4010                opCode = Op::OpImageGather;
4011    } else if (explicitLod) {
4012        if (parameters.Dref) {
4013            if (proj)
4014                if (sparse)
4015                    opCode = Op::OpImageSparseSampleProjDrefExplicitLod;
4016                else
4017                    opCode = Op::OpImageSampleProjDrefExplicitLod;
4018            else
4019                if (sparse)
4020                    opCode = Op::OpImageSparseSampleDrefExplicitLod;
4021                else
4022                    opCode = Op::OpImageSampleDrefExplicitLod;
4023        } else {
4024            if (proj)
4025                if (sparse)
4026                    opCode = Op::OpImageSparseSampleProjExplicitLod;
4027                else
4028                    opCode = Op::OpImageSampleProjExplicitLod;
4029            else
4030                if (sparse)
4031                    opCode = Op::OpImageSparseSampleExplicitLod;
4032                else
4033                    opCode = Op::OpImageSampleExplicitLod;
4034        }
4035    } else {
4036        if (parameters.Dref) {
4037            if (proj)
4038                if (sparse)
4039                    opCode = Op::OpImageSparseSampleProjDrefImplicitLod;
4040                else
4041                    opCode = Op::OpImageSampleProjDrefImplicitLod;
4042            else
4043                if (sparse)
4044                    opCode = Op::OpImageSparseSampleDrefImplicitLod;
4045                else
4046                    opCode = Op::OpImageSampleDrefImplicitLod;
4047        } else {
4048            if (proj)
4049                if (sparse)
4050                    opCode = Op::OpImageSparseSampleProjImplicitLod;
4051                else
4052                    opCode = Op::OpImageSampleProjImplicitLod;
4053            else
4054                if (sparse)
4055                    opCode = Op::OpImageSparseSampleImplicitLod;
4056                else
4057                    opCode = Op::OpImageSampleImplicitLod;
4058        }
4059    }
4060
4061    // See if the result type is expecting a smeared result.
4062    // This happens when a legacy shadow*() call is made, which
4063    // gets a vec4 back instead of a float.
4064    Id smearedType = resultType;
4065    if (! isScalarType(resultType)) {
4066        switch (opCode) {
4067        case Op::OpImageSampleDrefImplicitLod:
4068        case Op::OpImageSampleDrefExplicitLod:
4069        case Op::OpImageSampleProjDrefImplicitLod:
4070        case Op::OpImageSampleProjDrefExplicitLod:
4071            resultType = getScalarTypeId(resultType);
4072            break;
4073        default:
4074            break;
4075        }
4076    }
4077
4078    Id typeId0 = 0;
4079    Id typeId1 = 0;
4080
4081    if (sparse) {
4082        typeId0 = resultType;
4083        typeId1 = getDerefTypeId(parameters.texelOut);
4084        resultType = makeStructResultType(typeId0, typeId1);
4085    }
4086
4087    // Build the SPIR-V instruction
4088    Instruction* textureInst = new Instruction(getUniqueId(), resultType, opCode);
4089    textureInst->reserveOperands(optArgNum + (texArgs.size() - (optArgNum + 1)));
4090    for (size_t op = 0; op < optArgNum; ++op)
4091        textureInst->addIdOperand(texArgs[op]);
4092    if (optArgNum < texArgs.size())
4093        textureInst->addImmediateOperand(texArgs[optArgNum]);
4094    for (size_t op = optArgNum + 1; op < texArgs.size(); ++op)
4095        textureInst->addIdOperand(texArgs[op]);
4096    setPrecision(textureInst->getResultId(), precision);
4097    addInstruction(std::unique_ptr<Instruction>(textureInst));
4098
4099    Id resultId = textureInst->getResultId();
4100
4101    if (sparse) {
4102        // set capability
4103        addCapability(Capability::SparseResidency);
4104
4105        // Decode the return type that was a special structure
4106        createStore(createCompositeExtract(resultId, typeId1, 1), parameters.texelOut);
4107        resultId = createCompositeExtract(resultId, typeId0, 0);
4108        setPrecision(resultId, precision);
4109    } else {
4110        // When a smear is needed, do it, as per what was computed
4111        // above when resultType was changed to a scalar type.
4112        if (resultType != smearedType)
4113            resultId = smearScalar(precision, resultId, smearedType);
4114    }
4115
4116    return resultId;
4117}
4118
4119// Comments in header
4120Id Builder::createTextureQueryCall(Op opCode, const TextureParameters& parameters, bool isUnsignedResult)
4121{
4122    // Figure out the result type
4123    Id resultType = 0;
4124    switch (opCode) {
4125    case Op::OpImageQuerySize:
4126    case Op::OpImageQuerySizeLod:
4127    {
4128        int numComponents = 0;
4129        switch (getTypeDimensionality(getImageType(parameters.sampler))) {
4130        case Dim::Dim1D:
4131        case Dim::Buffer:
4132            numComponents = 1;
4133            break;
4134        case Dim::Dim2D:
4135        case Dim::Cube:
4136        case Dim::Rect:
4137        case Dim::SubpassData:
4138            numComponents = 2;
4139            break;
4140        case Dim::Dim3D:
4141            numComponents = 3;
4142            break;
4143
4144        default:
4145            assert(0);
4146            break;
4147        }
4148        if (isArrayedImageType(getImageType(parameters.sampler)))
4149            ++numComponents;
4150
4151        Id intType = isUnsignedResult ? makeUintType(32) : makeIntType(32);
4152        if (numComponents == 1)
4153            resultType = intType;
4154        else
4155            resultType = makeVectorType(intType, numComponents);
4156
4157        break;
4158    }
4159    case Op::OpImageQueryLod:
4160        resultType = makeVectorType(getScalarTypeId(getTypeId(parameters.coords)), 2);
4161        break;
4162    case Op::OpImageQueryLevels:
4163    case Op::OpImageQuerySamples:
4164        resultType = isUnsignedResult ? makeUintType(32) : makeIntType(32);
4165        break;
4166    default:
4167        assert(0);
4168        break;
4169    }
4170
4171    Instruction* query = new Instruction(getUniqueId(), resultType, opCode);
4172    query->addIdOperand(parameters.sampler);
4173    if (parameters.coords)
4174        query->addIdOperand(parameters.coords);
4175    if (parameters.lod)
4176        query->addIdOperand(parameters.lod);
4177    addInstruction(std::unique_ptr<Instruction>(query));
4178    addCapability(Capability::ImageQuery);
4179
4180    return query->getResultId();
4181}
4182
4183// External comments in header.
4184// Operates recursively to visit the composite's hierarchy.
4185Id Builder::createCompositeCompare(Decoration precision, Id value1, Id value2, bool equal)
4186{
4187    Id boolType = makeBoolType();
4188    Id valueType = getTypeId(value1);
4189
4190    Id resultId = NoResult;
4191
4192    int numConstituents = getNumTypeConstituents(valueType);
4193
4194    // Scalars and Vectors
4195
4196    if (isScalarType(valueType) || isVectorType(valueType)) {
4197        assert(valueType == getTypeId(value2));
4198        // These just need a single comparison, just have
4199        // to figure out what it is.
4200        Op op;
4201        switch (getMostBasicTypeClass(valueType)) {
4202        case Op::OpTypeFloat:
4203            op = equal ? Op::OpFOrdEqual : Op::OpFUnordNotEqual;
4204            break;
4205        case Op::OpTypeInt:
4206        default:
4207            op = equal ? Op::OpIEqual : Op::OpINotEqual;
4208            break;
4209        case Op::OpTypeBool:
4210            op = equal ? Op::OpLogicalEqual : Op::OpLogicalNotEqual;
4211            precision = NoPrecision;
4212            break;
4213        }
4214
4215        if (isScalarType(valueType)) {
4216            // scalar
4217            resultId = createBinOp(op, boolType, value1, value2);
4218        } else {
4219            // vector
4220            resultId = createBinOp(op, makeVectorType(boolType, numConstituents), value1, value2);
4221            setPrecision(resultId, precision);
4222            // reduce vector compares...
4223            resultId = createUnaryOp(equal ? Op::OpAll : Op::OpAny, boolType, resultId);
4224        }
4225
4226        return setPrecision(resultId, precision);
4227    }
4228
4229    // Only structs, arrays, and matrices should be left.
4230    // They share in common the reduction operation across their constituents.
4231    assert(isAggregateType(valueType) || isMatrixType(valueType));
4232
4233    // Compare each pair of constituents
4234    for (int constituent = 0; constituent < numConstituents; ++constituent) {
4235        std::vector<unsigned> indexes(1, constituent);
4236        Id constituentType1 = getContainedTypeId(getTypeId(value1), constituent);
4237        Id constituentType2 = getContainedTypeId(getTypeId(value2), constituent);
4238        Id constituent1 = createCompositeExtract(value1, constituentType1, indexes);
4239        Id constituent2 = createCompositeExtract(value2, constituentType2, indexes);
4240
4241        Id subResultId = createCompositeCompare(precision, constituent1, constituent2, equal);
4242
4243        if (constituent == 0)
4244            resultId = subResultId;
4245        else
4246            resultId = setPrecision(createBinOp(equal ? Op::OpLogicalAnd : Op::OpLogicalOr, boolType, resultId, subResultId),
4247                                    precision);
4248    }
4249
4250    return resultId;
4251}
4252
4253// OpCompositeConstruct
4254Id Builder::createCompositeConstruct(Id typeId, const std::vector<Id>& constituents)
4255{
4256    assert(isAggregateType(typeId) || (getNumTypeConstituents(typeId) > 1 &&
4257           getNumTypeConstituents(typeId) == constituents.size()) ||
4258           ((isCooperativeVectorType(typeId) || isVectorType(typeId)) && constituents.size() == 1));
4259
4260    if (generatingOpCodeForSpecConst) {
4261        // Sometime, even in spec-constant-op mode, the constant composite to be
4262        // constructed may not be a specialization constant.
4263        // e.g.:
4264        //  const mat2 m2 = mat2(a_spec_const, a_front_end_const, another_front_end_const, third_front_end_const);
4265        // The first column vector should be a spec constant one, as a_spec_const is a spec constant.
4266        // The second column vector should NOT be spec constant, as it does not contain any spec constants.
4267        // To handle such cases, we check the constituents of the constant vector to determine whether this
4268        // vector should be created as a spec constant.
4269        return makeCompositeConstant(typeId, constituents,
4270                                     std::any_of(constituents.begin(), constituents.end(),
4271                                                 [&](spv::Id id) { return isSpecConstant(id); }));
4272    }
4273
4274    bool replicate = false;
4275    size_t numConstituents = constituents.size();
4276
4277    if (useReplicatedComposites || isCooperativeVectorType(typeId)) {
4278        replicate = numConstituents > 0 &&
4279            std::equal(constituents.begin() + 1, constituents.end(), constituents.begin());
4280    }
4281
4282    if (replicate) {
4283        numConstituents = 1;
4284        addCapability(spv::Capability::ReplicatedCompositesEXT);
4285        addExtension(spv::E_SPV_EXT_replicated_composites);
4286    }
4287
4288    Op opcode = replicate ? Op::OpCompositeConstructReplicateEXT : Op::OpCompositeConstruct;
4289
4290    Instruction* op = new Instruction(getUniqueId(), typeId, opcode);
4291    op->reserveOperands(constituents.size());
4292    for (size_t c = 0; c < numConstituents; ++c)
4293        op->addIdOperand(constituents[c]);
4294    addInstruction(std::unique_ptr<Instruction>(op));
4295
4296    return op->getResultId();
4297}
4298
4299// coopmat conversion
4300Id Builder::createCooperativeMatrixConversion(Id typeId, Id source)
4301{
4302    Instruction* op = new Instruction(getUniqueId(), typeId, Op::OpCooperativeMatrixConvertNV);
4303    op->addIdOperand(source);
4304    addInstruction(std::unique_ptr<Instruction>(op));
4305
4306    return op->getResultId();
4307}
4308
4309// coopmat reduce
4310Id Builder::createCooperativeMatrixReduce(Op opcode, Id typeId, Id source, unsigned int mask, Id func)
4311{
4312    Instruction* op = new Instruction(getUniqueId(), typeId, opcode);
4313    op->addIdOperand(source);
4314    op->addImmediateOperand(mask);
4315    op->addIdOperand(func);
4316    addInstruction(std::unique_ptr<Instruction>(op));
4317
4318    return op->getResultId();
4319}
4320
4321// coopmat per-element operation
4322Id Builder::createCooperativeMatrixPerElementOp(Id typeId, const std::vector<Id>& operands)
4323{
4324    Instruction* op = new Instruction(getUniqueId(), typeId, spv::Op::OpCooperativeMatrixPerElementOpNV);
4325    // skip operand[0], which is where the result is stored
4326    for (uint32_t i = 1; i < operands.size(); ++i) {
4327        op->addIdOperand(operands[i]);
4328    }
4329    addInstruction(std::unique_ptr<Instruction>(op));
4330
4331    return op->getResultId();
4332}
4333
4334// Vector or scalar constructor
4335Id Builder::createConstructor(Decoration precision, const std::vector<Id>& sources, Id resultTypeId)
4336{
4337    Id result = NoResult;
4338    unsigned int numTargetComponents = getNumTypeComponents(resultTypeId);
4339    unsigned int targetComponent = 0;
4340
4341    // Special case: when calling a vector constructor with a single scalar
4342    // argument, smear the scalar
4343    if (sources.size() == 1 && isScalar(sources[0]) && (numTargetComponents > 1 || isCooperativeVectorType(resultTypeId)))
4344        return smearScalar(precision, sources[0], resultTypeId);
4345
4346    // Special case: 2 vectors of equal size
4347    if (sources.size() == 1 &&
4348        (isVector(sources[0]) || isCooperativeVector(sources[0])) &&
4349        numTargetComponents == getNumComponents(sources[0])) {
4350        if (isCooperativeVector(sources[0]) != isCooperativeVectorType(resultTypeId)) {
4351            assert(isVector(sources[0]) != isVectorType(resultTypeId));
4352            return createUnaryOp(spv::Op::OpBitcast, resultTypeId, sources[0]);
4353        } else {
4354            assert(resultTypeId == getTypeId(sources[0]));
4355            return sources[0];
4356        }
4357    }
4358
4359    // accumulate the arguments for OpCompositeConstruct
4360    std::vector<Id> constituents;
4361    Id scalarTypeId = getScalarTypeId(resultTypeId);
4362
4363    // lambda to store the result of visiting an argument component
4364    const auto latchResult = [&](Id comp) {
4365        if (numTargetComponents > 1 || isVectorType(resultTypeId))
4366            constituents.push_back(comp);
4367        else
4368            result = comp;
4369        ++targetComponent;
4370    };
4371
4372    // lambda to visit a vector argument's components
4373    const auto accumulateVectorConstituents = [&](Id sourceArg) {
4374        unsigned int sourceSize = getNumComponents(sourceArg);
4375        unsigned int sourcesToUse = sourceSize;
4376        if (sourcesToUse + targetComponent > numTargetComponents)
4377            sourcesToUse = numTargetComponents - targetComponent;
4378
4379        for (unsigned int s = 0; s < sourcesToUse; ++s) {
4380            std::vector<unsigned> swiz;
4381            swiz.push_back(s);
4382            latchResult(createRvalueSwizzle(precision, scalarTypeId, sourceArg, swiz));
4383        }
4384    };
4385
4386    // lambda to visit a matrix argument's components
4387    const auto accumulateMatrixConstituents = [&](Id sourceArg) {
4388        unsigned int sourceSize = getNumColumns(sourceArg) * getNumRows(sourceArg);
4389        unsigned int sourcesToUse = sourceSize;
4390        if (sourcesToUse + targetComponent > numTargetComponents)
4391            sourcesToUse = numTargetComponents - targetComponent;
4392
4393        unsigned int col = 0;
4394        unsigned int row = 0;
4395        for (unsigned int s = 0; s < sourcesToUse; ++s) {
4396            if (row >= getNumRows(sourceArg)) {
4397                row = 0;
4398                col++;
4399            }
4400            std::vector<Id> indexes;
4401            indexes.push_back(col);
4402            indexes.push_back(row);
4403            latchResult(createCompositeExtract(sourceArg, scalarTypeId, indexes));
4404            row++;
4405        }
4406    };
4407
4408    // Go through the source arguments, each one could have either
4409    // a single or multiple components to contribute.
4410    for (unsigned int i = 0; i < sources.size(); ++i) {
4411
4412        if (isScalar(sources[i]) || isPointer(sources[i]))
4413            latchResult(sources[i]);
4414        else if (isVector(sources[i]) || isCooperativeVector(sources[i]))
4415            accumulateVectorConstituents(sources[i]);
4416        else if (isMatrix(sources[i]))
4417            accumulateMatrixConstituents(sources[i]);
4418        else
4419            assert(0);
4420
4421        if (targetComponent >= numTargetComponents)
4422            break;
4423    }
4424
4425    // If the result is a vector, make it from the gathered constituents.
4426    if (constituents.size() > 0) {
4427        result = createCompositeConstruct(resultTypeId, constituents);
4428        return setPrecision(result, precision);
4429    } else {
4430      // Precision was set when generating this component.
4431      return result;
4432    }
4433}
4434
4435// Comments in header
4436Id Builder::createMatrixConstructor(Decoration precision, const std::vector<Id>& sources, Id resultTypeId)
4437{
4438    Id componentTypeId = getScalarTypeId(resultTypeId);
4439    unsigned int numCols = getTypeNumColumns(resultTypeId);
4440    unsigned int numRows = getTypeNumRows(resultTypeId);
4441
4442    Instruction* instr = module.getInstruction(componentTypeId);
4443    const unsigned bitCount = instr->getImmediateOperand(0);
4444
4445    // Optimize matrix constructed from a bigger matrix
4446    if (isMatrix(sources[0]) && getNumColumns(sources[0]) >= numCols && getNumRows(sources[0]) >= numRows) {
4447        // To truncate the matrix to a smaller number of rows/columns, we need to:
4448        // 1. For each column, extract the column and truncate it to the required size using shuffle
4449        // 2. Assemble the resulting matrix from all columns
4450        Id matrix = sources[0];
4451        Id columnTypeId = getContainedTypeId(resultTypeId);
4452        Id sourceColumnTypeId = getContainedTypeId(getTypeId(matrix));
4453
4454        std::vector<unsigned> channels;
4455        for (unsigned int row = 0; row < numRows; ++row)
4456            channels.push_back(row);
4457
4458        std::vector<Id> matrixColumns;
4459        for (unsigned int col = 0; col < numCols; ++col) {
4460            std::vector<unsigned> indexes;
4461            indexes.push_back(col);
4462            Id colv = createCompositeExtract(matrix, sourceColumnTypeId, indexes);
4463            setPrecision(colv, precision);
4464
4465            if (numRows != getNumRows(matrix)) {
4466                matrixColumns.push_back(createRvalueSwizzle(precision, columnTypeId, colv, channels));
4467            } else {
4468                matrixColumns.push_back(colv);
4469            }
4470        }
4471
4472        return setPrecision(createCompositeConstruct(resultTypeId, matrixColumns), precision);
4473    }
4474
4475    // Detect a matrix being constructed from a repeated vector of the correct size.
4476    // Create the composite directly from it.
4477    if (sources.size() == numCols && isVector(sources[0]) && getNumComponents(sources[0]) == numRows &&
4478        std::equal(sources.begin() + 1, sources.end(), sources.begin())) {
4479        return setPrecision(createCompositeConstruct(resultTypeId, sources), precision);
4480    }
4481
4482    // Otherwise, will use a two step process
4483    // 1. make a compile-time 2D array of values
4484    // 2. construct a matrix from that array
4485
4486    // Step 1.
4487
4488    // initialize the array to the identity matrix
4489    Id ids[maxMatrixSize][maxMatrixSize];
4490    Id one, zero;
4491    if (bitCount == 64) {
4492        one = makeDoubleConstant(1.0);
4493        zero = makeDoubleConstant(0.0);
4494    } else if (bitCount == 16) {
4495        one = makeFloat16Constant(1.0);
4496        zero = makeFloat16Constant(0.0);
4497    } else {
4498        one = makeFloatConstant(1.0);
4499        zero = makeFloatConstant(0.0);
4500    }
4501    for (int col = 0; col < 4; ++col) {
4502        for (int row = 0; row < 4; ++row) {
4503            if (col == row)
4504                ids[col][row] = one;
4505            else
4506                ids[col][row] = zero;
4507        }
4508    }
4509
4510    // modify components as dictated by the arguments
4511    if (sources.size() == 1 && isScalar(sources[0])) {
4512        // a single scalar; resets the diagonals
4513        for (int col = 0; col < 4; ++col)
4514            ids[col][col] = sources[0];
4515    } else if (isMatrix(sources[0])) {
4516        // constructing from another matrix; copy over the parts that exist in both the argument and constructee
4517        Id matrix = sources[0];
4518        unsigned int minCols = std::min(numCols, getNumColumns(matrix));
4519        unsigned int minRows = std::min(numRows, getNumRows(matrix));
4520        for (unsigned int col = 0; col < minCols; ++col) {
4521            std::vector<unsigned> indexes;
4522            indexes.push_back(col);
4523            for (unsigned int row = 0; row < minRows; ++row) {
4524                indexes.push_back(row);
4525                ids[col][row] = createCompositeExtract(matrix, componentTypeId, indexes);
4526                indexes.pop_back();
4527                setPrecision(ids[col][row], precision);
4528            }
4529        }
4530    } else {
4531        // fill in the matrix in column-major order with whatever argument components are available
4532        unsigned int row = 0;
4533        unsigned int col = 0;
4534
4535        for (unsigned int arg = 0; arg < sources.size() && col < numCols; ++arg) {
4536            Id argComp = sources[arg];
4537            for (unsigned int comp = 0; comp < getNumComponents(sources[arg]); ++comp) {
4538                if (getNumComponents(sources[arg]) > 1) {
4539                    argComp = createCompositeExtract(sources[arg], componentTypeId, comp);
4540                    setPrecision(argComp, precision);
4541                }
4542                ids[col][row++] = argComp;
4543                if (row == numRows) {
4544                    row = 0;
4545                    col++;
4546                }
4547                if (col == numCols) {
4548                    // If more components are provided than fit the matrix, discard the rest.
4549                    break;
4550                }
4551            }
4552        }
4553    }
4554
4555    // Step 2:  Construct a matrix from that array.
4556    // First make the column vectors, then make the matrix.
4557
4558    // make the column vectors
4559    Id columnTypeId = getContainedTypeId(resultTypeId);
4560    std::vector<Id> matrixColumns;
4561    for (unsigned int col = 0; col < numCols; ++col) {
4562        std::vector<Id> vectorComponents;
4563        for (unsigned int row = 0; row < numRows; ++row)
4564            vectorComponents.push_back(ids[col][row]);
4565        Id column = createCompositeConstruct(columnTypeId, vectorComponents);
4566        setPrecision(column, precision);
4567        matrixColumns.push_back(column);
4568    }
4569
4570    // make the matrix
4571    return setPrecision(createCompositeConstruct(resultTypeId, matrixColumns), precision);
4572}
4573
4574// Comments in header
4575Builder::If::If(Id cond, SelectionControlMask ctrl, Builder& gb) :
4576    builder(gb),
4577    condition(cond),
4578    control(ctrl),
4579    elseBlock(nullptr)
4580{
4581    function = &builder.getBuildPoint()->getParent();
4582
4583    // make the blocks, but only put the then-block into the function,
4584    // the else-block and merge-block will be added later, in order, after
4585    // earlier code is emitted
4586    thenBlock = new Block(builder.getUniqueId(), *function);
4587    mergeBlock = new Block(builder.getUniqueId(), *function);
4588
4589    // Save the current block, so that we can add in the flow control split when
4590    // makeEndIf is called.
4591    headerBlock = builder.getBuildPoint();
4592    builder.createSelectionMerge(mergeBlock, control);
4593
4594    function->addBlock(thenBlock);
4595    builder.setBuildPoint(thenBlock);
4596}
4597
4598// Comments in header
4599void Builder::If::makeBeginElse()
4600{
4601    // Close out the "then" by having it jump to the mergeBlock
4602    builder.createBranch(true, mergeBlock);
4603
4604    // Make the first else block and add it to the function
4605    elseBlock = new Block(builder.getUniqueId(), *function);
4606    function->addBlock(elseBlock);
4607
4608    // Start building the else block
4609    builder.setBuildPoint(elseBlock);
4610}
4611
4612// Comments in header
4613void Builder::If::makeEndIf()
4614{
4615    // jump to the merge block
4616    builder.createBranch(true, mergeBlock);
4617
4618    // Go back to the headerBlock and make the flow control split
4619    builder.setBuildPoint(headerBlock);
4620    if (elseBlock)
4621        builder.createConditionalBranch(condition, thenBlock, elseBlock);
4622    else
4623        builder.createConditionalBranch(condition, thenBlock, mergeBlock);
4624
4625    // add the merge block to the function
4626    function->addBlock(mergeBlock);
4627    builder.setBuildPoint(mergeBlock);
4628}
4629
4630// Comments in header
4631void Builder::makeSwitch(Id selector, SelectionControlMask control, int numSegments, const std::vector<int>& caseValues,
4632                         const std::vector<int>& valueIndexToSegment, int defaultSegment,
4633                         std::vector<Block*>& segmentBlocks)
4634{
4635    Function& function = buildPoint->getParent();
4636
4637    // make all the blocks
4638    for (int s = 0; s < numSegments; ++s)
4639        segmentBlocks.push_back(new Block(getUniqueId(), function));
4640
4641    Block* mergeBlock = new Block(getUniqueId(), function);
4642
4643    // make and insert the switch's selection-merge instruction
4644    createSelectionMerge(mergeBlock, control);
4645
4646    // make the switch instruction
4647    Instruction* switchInst = new Instruction(NoResult, NoType, Op::OpSwitch);
4648    switchInst->reserveOperands((caseValues.size() * 2) + 2);
4649    switchInst->addIdOperand(selector);
4650    auto defaultOrMerge = (defaultSegment >= 0) ? segmentBlocks[defaultSegment] : mergeBlock;
4651    switchInst->addIdOperand(defaultOrMerge->getId());
4652    defaultOrMerge->addPredecessor(buildPoint);
4653    for (int i = 0; i < (int)caseValues.size(); ++i) {
4654        switchInst->addImmediateOperand(caseValues[i]);
4655        switchInst->addIdOperand(segmentBlocks[valueIndexToSegment[i]]->getId());
4656        segmentBlocks[valueIndexToSegment[i]]->addPredecessor(buildPoint);
4657    }
4658    addInstruction(std::unique_ptr<Instruction>(switchInst));
4659
4660    // push the merge block
4661    switchMerges.push(mergeBlock);
4662}
4663
4664// Comments in header
4665void Builder::addSwitchBreak(bool implicit)
4666{
4667    // branch to the top of the merge block stack
4668    createBranch(implicit, switchMerges.top());
4669    createAndSetNoPredecessorBlock("post-switch-break");
4670}
4671
4672// Comments in header
4673void Builder::nextSwitchSegment(std::vector<Block*>& segmentBlock, int nextSegment)
4674{
4675    int lastSegment = nextSegment - 1;
4676    if (lastSegment >= 0) {
4677        // Close out previous segment by jumping, if necessary, to next segment
4678        if (! buildPoint->isTerminated())
4679            createBranch(true, segmentBlock[nextSegment]);
4680    }
4681    Block* block = segmentBlock[nextSegment];
4682    block->getParent().addBlock(block);
4683    setBuildPoint(block);
4684}
4685
4686// Comments in header
4687void Builder::endSwitch(std::vector<Block*>& /*segmentBlock*/)
4688{
4689    // Close out previous segment by jumping, if necessary, to next segment
4690    if (! buildPoint->isTerminated())
4691        addSwitchBreak(true);
4692
4693    switchMerges.top()->getParent().addBlock(switchMerges.top());
4694    setBuildPoint(switchMerges.top());
4695
4696    switchMerges.pop();
4697}
4698
4699Block& Builder::makeNewBlock()
4700{
4701    Function& function = buildPoint->getParent();
4702    auto block = new Block(getUniqueId(), function);
4703    function.addBlock(block);
4704    return *block;
4705}
4706
4707Builder::LoopBlocks& Builder::makeNewLoop()
4708{
4709    // This verbosity is needed to simultaneously get the same behavior
4710    // everywhere (id's in the same order), have a syntax that works
4711    // across lots of versions of C++, have no warnings from pedantic
4712    // compilation modes, and leave the rest of the code alone.
4713    Block& head            = makeNewBlock();
4714    Block& body            = makeNewBlock();
4715    Block& merge           = makeNewBlock();
4716    Block& continue_target = makeNewBlock();
4717    LoopBlocks blocks(head, body, merge, continue_target);
4718    loops.push(blocks);
4719    return loops.top();
4720}
4721
4722void Builder::createLoopContinue()
4723{
4724    createBranch(false, &loops.top().continue_target);
4725    // Set up a block for dead code.
4726    createAndSetNoPredecessorBlock("post-loop-continue");
4727}
4728
4729void Builder::createLoopExit()
4730{
4731    createBranch(false, &loops.top().merge);
4732    // Set up a block for dead code.
4733    createAndSetNoPredecessorBlock("post-loop-break");
4734}
4735
4736void Builder::closeLoop()
4737{
4738    loops.pop();
4739}
4740
4741void Builder::clearAccessChain()
4742{
4743    accessChain.base = NoResult;
4744    accessChain.indexChain.clear();
4745    accessChain.instr = NoResult;
4746    accessChain.swizzle.clear();
4747    accessChain.component = NoResult;
4748    accessChain.preSwizzleBaseType = NoType;
4749    accessChain.isRValue = false;
4750    accessChain.coherentFlags.clear();
4751    accessChain.alignment = 0;
4752    accessChain.descHeapInfo.descHeapBaseTy = NoResult;
4753    accessChain.descHeapInfo.descHeapBaseOffset = NoResult;
4754    accessChain.descHeapInfo.descHeapIndexChain.clear();
4755    accessChain.descHeapInfo.descTy = NoResult;
4756    accessChain.descHeapInfo.descStorageClass = StorageClass::Max;
4757    accessChain.descHeapInfo.descReadonly = false;
4758    accessChain.descHeapInfo.descWriteonly = false;
4759    accessChain.descHeapInfo.descHeapInstId.clear();
4760}
4761
4762// Comments in header
4763void Builder::accessChainPushSwizzle(std::vector<unsigned>& swizzle, Id preSwizzleBaseType,
4764    AccessChain::CoherentFlags coherentFlags, unsigned int alignment)
4765{
4766    accessChain.coherentFlags |= coherentFlags;
4767    accessChain.alignment |= alignment;
4768
4769    // swizzles can be stacked in GLSL, but simplified to a single
4770    // one here; the base type doesn't change
4771    if (accessChain.preSwizzleBaseType == NoType)
4772        accessChain.preSwizzleBaseType = preSwizzleBaseType;
4773
4774    // if needed, propagate the swizzle for the current access chain
4775    if (accessChain.swizzle.size() > 0) {
4776        std::vector<unsigned> oldSwizzle = accessChain.swizzle;
4777        accessChain.swizzle.resize(0);
4778        for (unsigned int i = 0; i < swizzle.size(); ++i) {
4779            assert(swizzle[i] < oldSwizzle.size());
4780            accessChain.swizzle.push_back(oldSwizzle[swizzle[i]]);
4781        }
4782    } else
4783        accessChain.swizzle = swizzle;
4784
4785    // determine if we need to track this swizzle anymore
4786    simplifyAccessChainSwizzle();
4787}
4788
4789// Comments in header
4790void Builder::accessChainStore(Id rvalue, Decoration nonUniform, spv::MemoryAccessMask memoryAccess, spv::Scope scope, unsigned int alignment)
4791{
4792    assert(accessChain.isRValue == false);
4793
4794    transferAccessChainSwizzle(true);
4795
4796    // MeshShadingEXT outputs don't support loads, so split swizzled stores
4797    bool isMeshOutput = getStorageClass(accessChain.base) == StorageClass::Output &&
4798                        capabilities.find(spv::Capability::MeshShadingEXT) != capabilities.end();
4799
4800    // If a swizzle exists and is not full and is not dynamic, then the swizzle will be broken into individual stores.
4801    if (accessChain.swizzle.size() > 0 &&
4802        ((getNumTypeComponents(getResultingAccessChainType()) != accessChain.swizzle.size() && accessChain.component == NoResult) || isMeshOutput)) {
4803        for (unsigned int i = 0; i < accessChain.swizzle.size(); ++i) {
4804            accessChain.indexChain.push_back(makeUintConstant(accessChain.swizzle[i]));
4805            accessChain.instr = NoResult;
4806
4807            Id base = collapseAccessChain();
4808            addDecoration(base, nonUniform);
4809
4810            accessChain.indexChain.pop_back();
4811            accessChain.instr = NoResult;
4812
4813            // dynamic component should be gone
4814            assert(accessChain.component == NoResult);
4815
4816            Id source = createCompositeExtract(rvalue, getContainedTypeId(getTypeId(rvalue)), i);
4817
4818            // take LSB of alignment
4819            alignment = alignment & ~(alignment & (alignment-1));
4820            if (getStorageClass(base) == StorageClass::PhysicalStorageBufferEXT) {
4821                memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessMask::Aligned);
4822            }
4823
4824            createStore(source, base, memoryAccess, scope, alignment);
4825        }
4826    }
4827    else {
4828        Id base = collapseAccessChain();
4829        addDecoration(base, nonUniform);
4830
4831        Id source = rvalue;
4832
4833        // dynamic component should be gone
4834        assert(accessChain.component == NoResult);
4835
4836        // take LSB of alignment
4837        alignment = alignment & ~(alignment & (alignment-1));
4838        if (getStorageClass(base) == StorageClass::PhysicalStorageBufferEXT) {
4839            memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessMask::Aligned);
4840        }
4841
4842        // If swizzle still exists, it may be out-of-order, we must load the target vector,
4843        // extract and insert elements to perform writeMask and/or swizzle.
4844        if (accessChain.swizzle.size() > 0) {
4845            // The read-modify-write load hits the same pointer as the store, so it needs the
4846            // same memory operands (while flipping MakePointerAvailable to Visible).
4847            // In particular a PhysicalStorageBuffer access must carry Aligned.
4848            auto loadAccess = memoryAccess & ~spv::MemoryAccessMask::MakePointerAvailableKHR;
4849            if (anySet(memoryAccess, spv::MemoryAccessMask::MakePointerAvailableKHR))
4850                loadAccess = loadAccess | spv::MemoryAccessMask::MakePointerVisibleKHR;
4851            Id tempBaseId = createLoad(base, spv::NoPrecision, loadAccess, scope, alignment);
4852            source = createLvalueSwizzle(getTypeId(tempBaseId), tempBaseId, source, accessChain.swizzle);
4853        }
4854
4855        createStore(source, base, memoryAccess, scope, alignment);
4856    }
4857}
4858
4859// Comments in header
4860Id Builder::accessChainLoad(Decoration precision, Decoration l_nonUniform,
4861    Decoration r_nonUniform, Id resultType, spv::MemoryAccessMask memoryAccess,
4862    spv::Scope scope, unsigned int alignment)
4863{
4864    Id id;
4865
4866    if (accessChain.isRValue) {
4867        // transfer access chain, but try to stay in registers
4868        transferAccessChainSwizzle(false);
4869        if (accessChain.indexChain.size() > 0) {
4870            Id swizzleBase = accessChain.preSwizzleBaseType != NoType ? accessChain.preSwizzleBaseType : resultType;
4871
4872            // if all the accesses are constants, we can use OpCompositeExtract
4873            std::vector<unsigned> indexes;
4874            bool constant = true;
4875            for (int i = 0; i < (int)accessChain.indexChain.size(); ++i) {
4876                if (isConstantScalar(accessChain.indexChain[i]))
4877                    indexes.push_back(getConstantScalar(accessChain.indexChain[i]));
4878                else {
4879                    constant = false;
4880                    break;
4881                }
4882            }
4883
4884            if (constant) {
4885                id = createCompositeExtract(accessChain.base, swizzleBase, indexes);
4886                setPrecision(id, precision);
4887            } else if (isVector(accessChain.base) || isCooperativeVector(accessChain.base)) {
4888                assert(accessChain.indexChain.size() == 1);
4889                id = createVectorExtractDynamic(accessChain.base, resultType, accessChain.indexChain[0]);
4890            } else {
4891                Id lValue = NoResult;
4892                if (spvVersion >= Spv_1_4 && isValidInitializer(accessChain.base)) {
4893                    // make a new function variable for this r-value, using an initializer,
4894                    // and mark it as NonWritable so that downstream it can be detected as a lookup
4895                    // table
4896                    lValue = createVariable(NoPrecision, StorageClass::Function, getTypeId(accessChain.base),
4897                        "indexable", accessChain.base);
4898                    addDecoration(lValue, Decoration::NonWritable);
4899                } else {
4900                    lValue = createVariable(NoPrecision, StorageClass::Function, getTypeId(accessChain.base),
4901                        "indexable");
4902                    // store into it
4903                    createStore(accessChain.base, lValue);
4904                }
4905                // move base to the new variable
4906                accessChain.base = lValue;
4907                accessChain.isRValue = false;
4908
4909                // load through the access chain
4910                id = createLoad(collapseAccessChain(), precision);
4911            }
4912        } else
4913            id = accessChain.base;  // no precision, it was set when this was defined
4914    } else {
4915        transferAccessChainSwizzle(true);
4916
4917        // take LSB of alignment
4918        alignment = alignment & ~(alignment & (alignment-1));
4919        if (getStorageClass(accessChain.base) == StorageClass::PhysicalStorageBufferEXT) {
4920            memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessMask::Aligned);
4921        }
4922
4923        // load through the access chain
4924        id = collapseAccessChain();
4925        // Apply nonuniform both to the access chain and the loaded value.
4926        // Buffer accesses need the access chain decorated, and this is where
4927        // loaded image types get decorated. TODO: This should maybe move to
4928        // createImageTextureFunctionCall.
4929        addDecoration(id, l_nonUniform);
4930        id = createLoad(id, precision, memoryAccess, scope, alignment);
4931        addDecoration(id, r_nonUniform);
4932    }
4933
4934    // Done, unless there are swizzles to do
4935    if (accessChain.swizzle.size() == 0 && accessChain.component == NoResult)
4936        return id;
4937
4938    // Do remaining swizzling
4939
4940    // Do the basic swizzle
4941    if (accessChain.swizzle.size() > 0) {
4942        Id swizzledType = getScalarTypeId(getTypeId(id));
4943        if (accessChain.swizzle.size() > 1)
4944            swizzledType = makeVectorType(swizzledType, (int)accessChain.swizzle.size());
4945        id = createRvalueSwizzle(precision, swizzledType, id, accessChain.swizzle);
4946    }
4947
4948    // Do the dynamic component
4949    if (accessChain.component != NoResult)
4950        id = setPrecision(createVectorExtractDynamic(id, resultType, accessChain.component), precision);
4951
4952    addDecoration(id, r_nonUniform);
4953    return id;
4954}
4955
4956Id Builder::accessChainGetLValue()
4957{
4958    assert(accessChain.isRValue == false);
4959
4960    transferAccessChainSwizzle(true);
4961    Id lvalue = collapseAccessChain();
4962
4963    // If swizzle exists, it is out-of-order or not full, we must load the target vector,
4964    // extract and insert elements to perform writeMask and/or swizzle.  This does not
4965    // go with getting a direct l-value pointer.
4966    assert(accessChain.swizzle.size() == 0);
4967    assert(accessChain.component == NoResult);
4968
4969    return lvalue;
4970}
4971
4972// comment in header
4973Id Builder::accessChainGetInferredType()
4974{
4975    // anything to operate on?
4976    // for untyped pointer, it may be remapped to a descriptor heap.
4977    // for descriptor heap, its base data type will be determined later,
4978    // according to load/store results' types.
4979    if (accessChain.base == NoResult || isUntypedPointer(accessChain.base) ||
4980    !accessChain.descHeapInfo.descHeapIndexChain.empty())
4981        return NoType;
4982    Id type = getTypeId(accessChain.base);
4983    // do initial dereference
4984    if (! accessChain.isRValue)
4985        type = getContainedTypeId(type);
4986
4987    // dereference each index
4988    for (auto it = accessChain.indexChain.cbegin(); it != accessChain.indexChain.cend(); ++it) {
4989        if (isStructType(type))
4990            type = getContainedTypeId(type, getConstantScalar(*it));
4991        else
4992            type = getContainedTypeId(type);
4993    }
4994
4995    // dereference swizzle
4996    if (accessChain.swizzle.size() == 1)
4997        type = getContainedTypeId(type);
4998    else if (accessChain.swizzle.size() > 1)
4999        type = makeVectorType(getContainedTypeId(type), (int)accessChain.swizzle.size());
5000
5001    // dereference component selection
5002    if (accessChain.component)
5003        type = getContainedTypeId(type);
5004
5005    return type;
5006}
5007
5008void Builder::dump(std::vector<unsigned int>& out) const
5009{
5010    // Header, before first instructions:
5011    out.push_back(MagicNumber);
5012    out.push_back(spvVersion);
5013    out.push_back(builderNumber);
5014    out.push_back(uniqueId + 1);
5015    out.push_back(0);
5016
5017    // Capabilities
5018    for (auto it = capabilities.cbegin(); it != capabilities.cend(); ++it) {
5019        Instruction capInst(0, 0, Op::OpCapability);
5020        capInst.addImmediateOperand(*it);
5021        capInst.dump(out);
5022    }
5023
5024    for (auto it = extensions.cbegin(); it != extensions.cend(); ++it) {
5025        Instruction extInst(0, 0, Op::OpExtension);
5026        extInst.addStringOperand(it->c_str());
5027        extInst.dump(out);
5028    }
5029
5030    dumpInstructions(out, imports);
5031    Instruction memInst(0, 0, Op::OpMemoryModel);
5032    memInst.addImmediateOperand(addressModel);
5033    memInst.addImmediateOperand(memoryModel);
5034    memInst.dump(out);
5035
5036    // Instructions saved up while building:
5037    dumpInstructions(out, entryPoints);
5038    dumpInstructions(out, executionModes);
5039
5040    // Debug instructions
5041    dumpInstructions(out, strings);
5042    dumpSourceInstructions(out);
5043    for (int e = 0; e < (int)sourceExtensions.size(); ++e) {
5044        Instruction sourceExtInst(0, 0, Op::OpSourceExtension);
5045        sourceExtInst.addStringOperand(sourceExtensions[e]);
5046        sourceExtInst.dump(out);
5047    }
5048    dumpInstructions(out, names);
5049    dumpModuleProcesses(out);
5050
5051    // Annotation instructions
5052    dumpInstructions(out, decorations);
5053
5054    dumpInstructions(out, constantsTypesGlobals);
5055    dumpInstructions(out, externals);
5056
5057    // The functions
5058    module.dump(out);
5059}
5060
5061//
5062// Protected methods.
5063//
5064
5065// Turn the described access chain in 'accessChain' into an instruction(s)
5066// computing its address.  This *cannot* include complex swizzles, which must
5067// be handled after this is called.
5068//
5069// Can generate code.
5070Id Builder::collapseAccessChain()
5071{
5072    assert(accessChain.isRValue == false);
5073
5074    // did we already emit an access chain for this?
5075    if (accessChain.instr != NoResult)
5076        return accessChain.instr;
5077
5078    // If we have a dynamic component, we can still transfer
5079    // that into a final operand to the access chain.  We need to remap the
5080    // dynamic component through the swizzle to get a new dynamic component to
5081    // update.
5082    //
5083    // This was not done in transferAccessChainSwizzle() because it might
5084    // generate code.
5085    remapDynamicSwizzle();
5086    if (accessChain.component != NoResult) {
5087        // transfer the dynamic component to the access chain
5088        accessChain.indexChain.push_back(accessChain.component);
5089        accessChain.component = NoResult;
5090    }
5091
5092    // note that non-trivial swizzling is left pending
5093
5094    // do we have an access chain?
5095    if (accessChain.indexChain.size() == 0 && accessChain.descHeapInfo.descHeapIndexChain.empty())
5096        return accessChain.base;
5097
5098    // emit the access chain
5099    StorageClass storageClass = (StorageClass)module.getStorageClass(getTypeId(accessChain.base));
5100    // when descHeap info is set, use another access chain process.
5101    if (isUntypedPointer(accessChain.base) || !accessChain.descHeapInfo.descHeapIndexChain.empty()) {
5102        accessChain.instr = createDescHeapAccessChain();
5103    } else {
5104        accessChain.instr = createAccessChain(storageClass, accessChain.base, accessChain.indexChain);
5105    }
5106
5107    return accessChain.instr;
5108}
5109
5110// For a dynamic component selection of a swizzle.
5111//
5112// Turn the swizzle and dynamic component into just a dynamic component.
5113//
5114// Generates code.
5115void Builder::remapDynamicSwizzle()
5116{
5117    // do we have a swizzle to remap a dynamic component through?
5118    if (accessChain.component != NoResult && accessChain.swizzle.size() > 1) {
5119        // build a vector of the swizzle for the component to map into
5120        std::vector<Id> components;
5121        for (int c = 0; c < (int)accessChain.swizzle.size(); ++c)
5122            components.push_back(makeUintConstant(accessChain.swizzle[c]));
5123        Id mapType = makeVectorType(makeUintType(32), (int)accessChain.swizzle.size());
5124        Id map = makeCompositeConstant(mapType, components);
5125
5126        // use it
5127        accessChain.component = createVectorExtractDynamic(map, makeUintType(32), accessChain.component);
5128        accessChain.swizzle.clear();
5129    }
5130}
5131
5132// clear out swizzle if it is redundant, that is reselecting the same components
5133// that would be present without the swizzle.
5134void Builder::simplifyAccessChainSwizzle()
5135{
5136    // If the swizzle has fewer components than the vector, it is subsetting, and must stay
5137    // to preserve that fact.
5138    if (getNumTypeComponents(accessChain.preSwizzleBaseType) > accessChain.swizzle.size())
5139        return;
5140
5141    // if components are out of order, it is a swizzle
5142    for (unsigned int i = 0; i < accessChain.swizzle.size(); ++i) {
5143        if (i != accessChain.swizzle[i])
5144            return;
5145    }
5146
5147    // otherwise, there is no need to track this swizzle
5148    accessChain.swizzle.clear();
5149    if (accessChain.component == NoResult)
5150        accessChain.preSwizzleBaseType = NoType;
5151}
5152
5153// To the extent any swizzling can become part of the chain
5154// of accesses instead of a post operation, make it so.
5155// If 'dynamic' is true, include transferring the dynamic component,
5156// otherwise, leave it pending.
5157//
5158// Does not generate code. just updates the access chain.
5159void Builder::transferAccessChainSwizzle(bool dynamic)
5160{
5161    // non existent?
5162    if (accessChain.swizzle.size() == 0 && accessChain.component == NoResult)
5163        return;
5164
5165    // too complex?
5166    // (this requires either a swizzle, or generating code for a dynamic component)
5167    if (accessChain.swizzle.size() > 1)
5168        return;
5169
5170    // single component, either in the swizzle and/or dynamic component
5171    if (accessChain.swizzle.size() == 1) {
5172        assert(accessChain.component == NoResult);
5173        // handle static component selection
5174        accessChain.indexChain.push_back(makeUintConstant(accessChain.swizzle.front()));
5175        accessChain.swizzle.clear();
5176        accessChain.preSwizzleBaseType = NoType;
5177    } else if (dynamic && accessChain.component != NoResult) {
5178        assert(accessChain.swizzle.size() == 0);
5179        // handle dynamic component
5180        accessChain.indexChain.push_back(accessChain.component);
5181        accessChain.preSwizzleBaseType = NoType;
5182        accessChain.component = NoResult;
5183    }
5184}
5185
5186// Utility method for creating a new block and setting the insert point to
5187// be in it. This is useful for flow-control operations that need a "dummy"
5188// block proceeding them (e.g. instructions after a discard, etc).
5189void Builder::createAndSetNoPredecessorBlock(const char* /*name*/)
5190{
5191    Block* block = new Block(getUniqueId(), buildPoint->getParent());
5192    block->setUnreachable();
5193    buildPoint->getParent().addBlock(block);
5194    setBuildPoint(block);
5195
5196    // if (name)
5197    //    addName(block->getId(), name);
5198}
5199
5200// Comments in header
5201void Builder::createBranch(bool implicit, Block* block)
5202{
5203    Instruction* branch = new Instruction(Op::OpBranch);
5204    branch->addIdOperand(block->getId());
5205    if (implicit) {
5206        addInstructionNoDebugInfo(std::unique_ptr<Instruction>(branch));
5207    }
5208    else {
5209        addInstruction(std::unique_ptr<Instruction>(branch));
5210    }
5211    block->addPredecessor(buildPoint);
5212}
5213
5214// Create OpConstantSizeOfEXT
5215Id Builder::createConstantSizeOfEXT(Id typeId)
5216{
5217    auto constantSize = constantSizeOfEXTIds.find(typeId);
5218    if (constantSize != constantSizeOfEXTIds.end())
5219        return constantSize->second;
5220
5221    Id resultType = makeUintType(32);
5222    Instruction* inst = new Instruction(getUniqueId(), resultType, Op::OpConstantSizeOfEXT);
5223    inst->addIdOperand(typeId);
5224    constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
5225    module.mapInstruction(inst);
5226    constantSizeOfEXTIds[typeId] = inst->getResultId();
5227    return inst->getResultId();
5228}
5229
5230void Builder::createSelectionMerge(Block* mergeBlock, SelectionControlMask control)
5231{
5232    Instruction* merge = new Instruction(Op::OpSelectionMerge);
5233    merge->reserveOperands(2);
5234    merge->addIdOperand(mergeBlock->getId());
5235    merge->addImmediateOperand(control);
5236    addInstruction(std::unique_ptr<Instruction>(merge));
5237}
5238
5239void Builder::createLoopMerge(Block* mergeBlock, Block* continueBlock, LoopControlMask control,
5240                              const std::vector<unsigned int>& operands)
5241{
5242    Instruction* merge = new Instruction(Op::OpLoopMerge);
5243    merge->reserveOperands(operands.size() + 3);
5244    merge->addIdOperand(mergeBlock->getId());
5245    merge->addIdOperand(continueBlock->getId());
5246    merge->addImmediateOperand(control);
5247    for (int op = 0; op < (int)operands.size(); ++op)
5248        merge->addImmediateOperand(operands[op]);
5249    addInstruction(std::unique_ptr<Instruction>(merge));
5250}
5251
5252void Builder::createConditionalBranch(Id condition, Block* thenBlock, Block* elseBlock)
5253{
5254    Instruction* branch = new Instruction(Op::OpBranchConditional);
5255    branch->reserveOperands(3);
5256    branch->addIdOperand(condition);
5257    branch->addIdOperand(thenBlock->getId());
5258    branch->addIdOperand(elseBlock->getId());
5259
5260    // A conditional branch is always attached to a condition expression
5261    addInstructionNoDebugInfo(std::unique_ptr<Instruction>(branch));
5262
5263    thenBlock->addPredecessor(buildPoint);
5264    elseBlock->addPredecessor(buildPoint);
5265}
5266
5267// OpSource
5268// [OpSourceContinued]
5269// ...
5270void Builder::dumpSourceInstructions(const spv::Id fileId, const std::string& text,
5271                                     std::vector<unsigned int>& out) const
5272{
5273    const int maxWordCount = 0xFFFF;
5274    const int opSourceWordCount = 4;
5275    const int nonNullBytesPerInstruction = 4 * (maxWordCount - opSourceWordCount) - 1;
5276
5277    if (sourceLang != SourceLanguage::Unknown) {
5278        // OpSource Language Version File Source
5279        Instruction sourceInst(NoResult, NoType, Op::OpSource);
5280        sourceInst.reserveOperands(3);
5281        sourceInst.addImmediateOperand(sourceLang);
5282        sourceInst.addImmediateOperand(sourceVersion);
5283        // File operand
5284        if (fileId != NoResult) {
5285            sourceInst.addIdOperand(fileId);
5286            // Source operand
5287            if (text.size() > 0) {
5288                int nextByte = 0;
5289                std::string subString;
5290                while ((int)text.size() - nextByte > 0) {
5291                    subString = text.substr(nextByte, nonNullBytesPerInstruction);
5292                    if (nextByte == 0) {
5293                        // OpSource
5294                        sourceInst.addStringOperand(subString.c_str());
5295                        sourceInst.dump(out);
5296                    } else {
5297                        // OpSourcContinued
5298                        Instruction sourceContinuedInst(Op::OpSourceContinued);
5299                        sourceContinuedInst.addStringOperand(subString.c_str());
5300                        sourceContinuedInst.dump(out);
5301                    }
5302                    nextByte += nonNullBytesPerInstruction;
5303                }
5304            } else
5305                sourceInst.dump(out);
5306        } else
5307            sourceInst.dump(out);
5308    }
5309}
5310
5311// Dump an OpSource[Continued] sequence for the source and every include file
5312void Builder::dumpSourceInstructions(std::vector<unsigned int>& out) const
5313{
5314    if (emitNonSemanticShaderDebugInfo) return;
5315    dumpSourceInstructions(mainFileId, sourceText, out);
5316    for (auto iItr = includeFiles.begin(); iItr != includeFiles.end(); ++iItr)
5317        dumpSourceInstructions(iItr->first, *iItr->second, out);
5318}
5319
5320template <class Range> void Builder::dumpInstructions(std::vector<unsigned int>& out, const Range& instructions) const
5321{
5322    for (const auto& inst : instructions) {
5323        inst->dump(out);
5324    }
5325}
5326
5327void Builder::dumpModuleProcesses(std::vector<unsigned int>& out) const
5328{
5329    for (int i = 0; i < (int)moduleProcesses.size(); ++i) {
5330        Instruction moduleProcessed(Op::OpModuleProcessed);
5331        moduleProcessed.addStringOperand(moduleProcesses[i]);
5332        moduleProcessed.dump(out);
5333    }
5334}
5335
5336bool Builder::DecorationInstructionLessThan::operator()(const std::unique_ptr<Instruction>& lhs,
5337                                                        const std::unique_ptr<Instruction>& rhs) const
5338{
5339    // Order by the id to which the decoration applies first. This is more intuitive.
5340    assert(lhs->isIdOperand(0) && rhs->isIdOperand(0));
5341    if (lhs->getIdOperand(0) != rhs->getIdOperand(0)) {
5342        return lhs->getIdOperand(0) < rhs->getIdOperand(0);
5343    }
5344
5345    if (lhs->getOpCode() != rhs->getOpCode())
5346        return lhs->getOpCode() < rhs->getOpCode();
5347
5348    // Now compare the operands.
5349    int minSize = std::min(lhs->getNumOperands(), rhs->getNumOperands());
5350    for (int i = 1; i < minSize; ++i) {
5351        if (lhs->isIdOperand(i) != rhs->isIdOperand(i)) {
5352            return lhs->isIdOperand(i) < rhs->isIdOperand(i);
5353        }
5354
5355        if (lhs->isIdOperand(i)) {
5356            if (lhs->getIdOperand(i) != rhs->getIdOperand(i)) {
5357                return lhs->getIdOperand(i) < rhs->getIdOperand(i);
5358            }
5359        } else {
5360            if (lhs->getImmediateOperand(i) != rhs->getImmediateOperand(i)) {
5361                return lhs->getImmediateOperand(i) < rhs->getImmediateOperand(i);
5362            }
5363        }
5364    }
5365
5366    if (lhs->getNumOperands() != rhs->getNumOperands())
5367        return lhs->getNumOperands() < rhs->getNumOperands();
5368
5369    // In this case they are equal.
5370    return false;
5371}
5372} // end spv namespace