yum-mirror/glslang

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

ChowAdd support for SPV_KHR_constant_data and SPV_KHR_abort08f27157

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