Don't remove SPIR-V blocks before codegen.
[platform/upstream/glslang.git] / SPIRV / SpvBuilder.cpp
1 //
2 //Copyright (C) 2014 LunarG, Inc.
3 //
4 //All rights reserved.
5 //
6 //Redistribution and use in source and binary forms, with or without
7 //modification, are permitted provided that the following conditions
8 //are met:
9 //
10 //    Redistributions of source code must retain the above copyright
11 //    notice, this list of conditions and the following disclaimer.
12 //
13 //    Redistributions in binary form must reproduce the above
14 //    copyright notice, this list of conditions and the following
15 //    disclaimer in the documentation and/or other materials provided
16 //    with the distribution.
17 //
18 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
19 //    contributors may be used to endorse or promote products derived
20 //    from this software without specific prior written permission.
21 //
22 //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 //"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 //LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 //FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 //COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 //BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30 //CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 //LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32 //ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 //POSSIBILITY OF SUCH DAMAGE.
34
35 //
36 // Author: John Kessenich, LunarG
37 //
38
39 //
40 // Helper for making SPIR-V IR.  Generally, this is documented in the header
41 // SpvBuilder.h.
42 //
43
44 #include <assert.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47
48 #include <unordered_set>
49
50 #include "SpvBuilder.h"
51
52 #ifndef _WIN32
53     #include <cstdio>
54 #endif
55
56 namespace spv {
57
58 Builder::Builder(unsigned int magicNumber) :
59     source(SourceLanguageUnknown),
60     sourceVersion(0),
61     addressModel(AddressingModelLogical),
62     memoryModel(MemoryModelGLSL450),
63     builderNumber(magicNumber),
64     buildPoint(0),
65     uniqueId(0),
66     mainFunction(0)
67 {
68     clearAccessChain();
69 }
70
71 Builder::~Builder()
72 {
73 }
74
75 Id Builder::import(const char* name)
76 {
77     Instruction* import = new Instruction(getUniqueId(), NoType, OpExtInstImport);
78     import->addStringOperand(name);
79     
80     imports.push_back(std::unique_ptr<Instruction>(import));
81     return import->getResultId();
82 }
83
84 // For creating new groupedTypes (will return old type if the requested one was already made).
85 Id Builder::makeVoidType()
86 {
87     Instruction* type;
88     if (groupedTypes[OpTypeVoid].size() == 0) {
89         type = new Instruction(getUniqueId(), NoType, OpTypeVoid);
90         groupedTypes[OpTypeVoid].push_back(type);
91         constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
92         module.mapInstruction(type);
93     } else
94         type = groupedTypes[OpTypeVoid].back();
95
96     return type->getResultId();
97 }
98
99 Id Builder::makeBoolType()
100 {
101     Instruction* type;
102     if (groupedTypes[OpTypeBool].size() == 0) {
103         type = new Instruction(getUniqueId(), NoType, OpTypeBool);
104         groupedTypes[OpTypeBool].push_back(type);
105         constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
106         module.mapInstruction(type);
107     } else
108         type = groupedTypes[OpTypeBool].back();
109
110     return type->getResultId();
111 }
112
113 Id Builder::makeSamplerType()
114 {
115     Instruction* type;
116     if (groupedTypes[OpTypeSampler].size() == 0) {
117         type = new Instruction(getUniqueId(), NoType, OpTypeSampler);
118         groupedTypes[OpTypeSampler].push_back(type);
119         constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
120         module.mapInstruction(type);
121     } else
122         type = groupedTypes[OpTypeSampler].back();
123
124     return type->getResultId();
125 }
126
127 Id Builder::makePointer(StorageClass storageClass, Id pointee)
128 {
129     // try to find it
130     Instruction* type;
131     for (int t = 0; t < (int)groupedTypes[OpTypePointer].size(); ++t) {
132         type = groupedTypes[OpTypePointer][t];
133         if (type->getImmediateOperand(0) == (unsigned)storageClass &&
134             type->getIdOperand(1) == pointee)
135             return type->getResultId();
136     }
137
138     // not found, make it
139     type = new Instruction(getUniqueId(), NoType, OpTypePointer);
140     type->addImmediateOperand(storageClass);
141     type->addIdOperand(pointee);
142     groupedTypes[OpTypePointer].push_back(type);
143     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
144     module.mapInstruction(type);
145
146     return type->getResultId();
147 }
148
149 Id Builder::makeIntegerType(int width, bool hasSign)
150 {
151     // try to find it
152     Instruction* type;
153     for (int t = 0; t < (int)groupedTypes[OpTypeInt].size(); ++t) {
154         type = groupedTypes[OpTypeInt][t];
155         if (type->getImmediateOperand(0) == (unsigned)width &&
156             type->getImmediateOperand(1) == (hasSign ? 1u : 0u))
157             return type->getResultId();
158     }
159
160     // not found, make it
161     type = new Instruction(getUniqueId(), NoType, OpTypeInt);
162     type->addImmediateOperand(width);
163     type->addImmediateOperand(hasSign ? 1 : 0);
164     groupedTypes[OpTypeInt].push_back(type);
165     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
166     module.mapInstruction(type);
167
168     return type->getResultId();
169 }
170
171 Id Builder::makeFloatType(int width)
172 {
173     // try to find it
174     Instruction* type;
175     for (int t = 0; t < (int)groupedTypes[OpTypeFloat].size(); ++t) {
176         type = groupedTypes[OpTypeFloat][t];
177         if (type->getImmediateOperand(0) == (unsigned)width)
178             return type->getResultId();
179     }
180
181     // not found, make it
182     type = new Instruction(getUniqueId(), NoType, OpTypeFloat);
183     type->addImmediateOperand(width);
184     groupedTypes[OpTypeFloat].push_back(type);
185     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
186     module.mapInstruction(type);
187
188     return type->getResultId();
189 }
190
191 // Make a struct without checking for duplication.
192 // See makeStructResultType() for non-decorated structs
193 // needed as the result of some instructions, which does
194 // check for duplicates.
195 Id Builder::makeStructType(std::vector<Id>& members, const char* name)
196 {
197     // Don't look for previous one, because in the general case,
198     // structs can be duplicated except for decorations.
199
200     // not found, make it
201     Instruction* type = new Instruction(getUniqueId(), NoType, OpTypeStruct);
202     for (int op = 0; op < (int)members.size(); ++op)
203         type->addIdOperand(members[op]);
204     groupedTypes[OpTypeStruct].push_back(type);
205     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
206     module.mapInstruction(type);
207     addName(type->getResultId(), name);
208
209     return type->getResultId();
210 }
211
212 // Make a struct for the simple results of several instructions,
213 // checking for duplication.
214 Id Builder::makeStructResultType(Id type0, Id type1)
215 {
216     // try to find it
217     Instruction* type;
218     for (int t = 0; t < (int)groupedTypes[OpTypeStruct].size(); ++t) {
219         type = groupedTypes[OpTypeStruct][t];
220         if (type->getNumOperands() != 2)
221             continue;
222         if (type->getIdOperand(0) != type0 || 
223             type->getIdOperand(1) != type1)
224             continue;
225         return type->getResultId();
226     }
227
228     // not found, make it
229     std::vector<spv::Id> members;
230     members.push_back(type0);
231     members.push_back(type1);
232
233     return makeStructType(members, "ResType");
234 }
235
236 Id Builder::makeVectorType(Id component, int size)
237 {
238     // try to find it
239     Instruction* type;
240     for (int t = 0; t < (int)groupedTypes[OpTypeVector].size(); ++t) {
241         type = groupedTypes[OpTypeVector][t];
242         if (type->getIdOperand(0) == component &&
243             type->getImmediateOperand(1) == (unsigned)size)
244             return type->getResultId();
245     }
246
247     // not found, make it
248     type = new Instruction(getUniqueId(), NoType, OpTypeVector);
249     type->addIdOperand(component);
250     type->addImmediateOperand(size);
251     groupedTypes[OpTypeVector].push_back(type);
252     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
253     module.mapInstruction(type);
254
255     return type->getResultId();
256 }
257
258 Id Builder::makeMatrixType(Id component, int cols, int rows)
259 {
260     assert(cols <= maxMatrixSize && rows <= maxMatrixSize);
261
262     Id column = makeVectorType(component, rows);
263
264     // try to find it
265     Instruction* type;
266     for (int t = 0; t < (int)groupedTypes[OpTypeMatrix].size(); ++t) {
267         type = groupedTypes[OpTypeMatrix][t];
268         if (type->getIdOperand(0) == column &&
269             type->getImmediateOperand(1) == (unsigned)cols)
270             return type->getResultId();
271     }
272
273     // not found, make it
274     type = new Instruction(getUniqueId(), NoType, OpTypeMatrix);
275     type->addIdOperand(column);
276     type->addImmediateOperand(cols);
277     groupedTypes[OpTypeMatrix].push_back(type);
278     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
279     module.mapInstruction(type);
280
281     return type->getResultId();
282 }
283
284 // TODO: performance: track arrays per stride
285 // If a stride is supplied (non-zero) make an array.
286 // If no stride (0), reuse previous array types.
287 Id Builder::makeArrayType(Id element, unsigned size, int stride)
288 {
289     // First, we need a constant instruction for the size
290     Id sizeId = makeUintConstant(size);
291
292     Instruction* type;
293     if (stride == 0) {
294         // try to find existing type
295         for (int t = 0; t < (int)groupedTypes[OpTypeArray].size(); ++t) {
296             type = groupedTypes[OpTypeArray][t];
297             if (type->getIdOperand(0) == element &&
298                 type->getIdOperand(1) == sizeId)
299                 return type->getResultId();
300         }
301     }
302
303     // not found, make it
304     type = new Instruction(getUniqueId(), NoType, OpTypeArray);
305     type->addIdOperand(element);
306     type->addIdOperand(sizeId);
307     groupedTypes[OpTypeArray].push_back(type);
308     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
309     module.mapInstruction(type);
310
311     return type->getResultId();
312 }
313
314 Id Builder::makeRuntimeArray(Id element)
315 {
316     Instruction* type = new Instruction(getUniqueId(), NoType, OpTypeRuntimeArray);
317     type->addIdOperand(element);
318     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
319     module.mapInstruction(type);
320
321     return type->getResultId();
322 }
323
324 Id Builder::makeFunctionType(Id returnType, std::vector<Id>& paramTypes)
325 {
326     // try to find it
327     Instruction* type;
328     for (int t = 0; t < (int)groupedTypes[OpTypeFunction].size(); ++t) {
329         type = groupedTypes[OpTypeFunction][t];
330         if (type->getIdOperand(0) != returnType || (int)paramTypes.size() != type->getNumOperands() - 1)
331             continue;
332         bool mismatch = false;
333         for (int p = 0; p < (int)paramTypes.size(); ++p) {
334             if (paramTypes[p] != type->getIdOperand(p + 1)) {
335                 mismatch = true;
336                 break;
337             }
338         }
339         if (! mismatch)
340             return type->getResultId();
341     }
342
343     // not found, make it
344     type = new Instruction(getUniqueId(), NoType, OpTypeFunction);
345     type->addIdOperand(returnType);
346     for (int p = 0; p < (int)paramTypes.size(); ++p)
347         type->addIdOperand(paramTypes[p]);
348     groupedTypes[OpTypeFunction].push_back(type);
349     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
350     module.mapInstruction(type);
351
352     return type->getResultId();
353 }
354
355 Id Builder::makeImageType(Id sampledType, Dim dim, bool depth, bool arrayed, bool ms, unsigned sampled, ImageFormat format)
356 {
357     // try to find it
358     Instruction* type;
359     for (int t = 0; t < (int)groupedTypes[OpTypeImage].size(); ++t) {
360         type = groupedTypes[OpTypeImage][t];
361         if (type->getIdOperand(0) == sampledType &&
362             type->getImmediateOperand(1) == (unsigned int)dim &&
363             type->getImmediateOperand(2) == (  depth ? 1u : 0u) &&
364             type->getImmediateOperand(3) == (arrayed ? 1u : 0u) &&
365             type->getImmediateOperand(4) == (     ms ? 1u : 0u) &&
366             type->getImmediateOperand(5) == sampled &&
367             type->getImmediateOperand(6) == (unsigned int)format)
368             return type->getResultId();
369     }
370
371     // not found, make it
372     type = new Instruction(getUniqueId(), NoType, OpTypeImage);
373     type->addIdOperand(sampledType);
374     type->addImmediateOperand(   dim);
375     type->addImmediateOperand(  depth ? 1 : 0);
376     type->addImmediateOperand(arrayed ? 1 : 0);
377     type->addImmediateOperand(     ms ? 1 : 0);
378     type->addImmediateOperand(sampled);
379     type->addImmediateOperand((unsigned int)format);
380
381     groupedTypes[OpTypeImage].push_back(type);
382     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
383     module.mapInstruction(type);
384
385     return type->getResultId();
386 }
387
388 Id Builder::makeSampledImageType(Id imageType)
389 {
390     // try to find it
391     Instruction* type;
392     for (int t = 0; t < (int)groupedTypes[OpTypeSampledImage].size(); ++t) {
393         type = groupedTypes[OpTypeSampledImage][t];
394         if (type->getIdOperand(0) == imageType)
395             return type->getResultId();
396     }
397
398     // not found, make it
399     type = new Instruction(getUniqueId(), NoType, OpTypeSampledImage);
400     type->addIdOperand(imageType);
401
402     groupedTypes[OpTypeSampledImage].push_back(type);
403     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(type));
404     module.mapInstruction(type);
405
406     return type->getResultId();
407 }
408
409 Id Builder::getDerefTypeId(Id resultId) const
410 {
411     Id typeId = getTypeId(resultId);
412     assert(isPointerType(typeId));
413
414     return module.getInstruction(typeId)->getImmediateOperand(1);
415 }
416
417 Op Builder::getMostBasicTypeClass(Id typeId) const
418 {
419     Instruction* instr = module.getInstruction(typeId);
420
421     Op typeClass = instr->getOpCode();
422     switch (typeClass)
423     {
424     case OpTypeVoid:
425     case OpTypeBool:
426     case OpTypeInt:
427     case OpTypeFloat:
428     case OpTypeStruct:
429         return typeClass;
430     case OpTypeVector:
431     case OpTypeMatrix:
432     case OpTypeArray:
433     case OpTypeRuntimeArray:
434         return getMostBasicTypeClass(instr->getIdOperand(0));
435     case OpTypePointer:
436         return getMostBasicTypeClass(instr->getIdOperand(1));
437     default:
438         assert(0);
439         return OpTypeFloat;
440     }
441 }
442
443 int Builder::getNumTypeConstituents(Id typeId) const
444 {
445     Instruction* instr = module.getInstruction(typeId);
446
447     switch (instr->getOpCode())
448     {
449     case OpTypeBool:
450     case OpTypeInt:
451     case OpTypeFloat:
452         return 1;
453     case OpTypeVector:
454     case OpTypeMatrix:
455     case OpTypeArray:
456         return instr->getImmediateOperand(1);
457     case OpTypeStruct:
458         return instr->getNumOperands();
459     default:
460         assert(0);
461         return 1;
462     }
463 }
464
465 // Return the lowest-level type of scalar that an homogeneous composite is made out of.
466 // Typically, this is just to find out if something is made out of ints or floats.
467 // However, it includes returning a structure, if say, it is an array of structure.
468 Id Builder::getScalarTypeId(Id typeId) const
469 {
470     Instruction* instr = module.getInstruction(typeId);
471
472     Op typeClass = instr->getOpCode();
473     switch (typeClass)
474     {
475     case OpTypeVoid:
476     case OpTypeBool:
477     case OpTypeInt:
478     case OpTypeFloat:
479     case OpTypeStruct:
480         return instr->getResultId();
481     case OpTypeVector:
482     case OpTypeMatrix:
483     case OpTypeArray:
484     case OpTypeRuntimeArray:
485     case OpTypePointer:
486         return getScalarTypeId(getContainedTypeId(typeId));
487     default:
488         assert(0);
489         return NoResult;
490     }
491 }
492
493 // Return the type of 'member' of a composite.
494 Id Builder::getContainedTypeId(Id typeId, int member) const
495 {
496     Instruction* instr = module.getInstruction(typeId);
497
498     Op typeClass = instr->getOpCode();
499     switch (typeClass)
500     {
501     case OpTypeVector:
502     case OpTypeMatrix:
503     case OpTypeArray:
504     case OpTypeRuntimeArray:
505         return instr->getIdOperand(0);
506     case OpTypePointer:
507         return instr->getIdOperand(1);
508     case OpTypeStruct:
509         return instr->getIdOperand(member);
510     default:
511         assert(0);
512         return NoResult;
513     }
514 }
515
516 // Return the immediately contained type of a given composite type.
517 Id Builder::getContainedTypeId(Id typeId) const
518 {
519     return getContainedTypeId(typeId, 0);
520 }
521
522 // See if a scalar constant of this type has already been created, so it
523 // can be reused rather than duplicated.  (Required by the specification).
524 Id Builder::findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned value) const
525 {
526     Instruction* constant;
527     for (int i = 0; i < (int)groupedConstants[typeClass].size(); ++i) {
528         constant = groupedConstants[typeClass][i];
529         if (constant->getOpCode() == opcode &&
530             constant->getTypeId() == typeId &&
531             constant->getImmediateOperand(0) == value)
532             return constant->getResultId();
533     }
534
535     return 0;
536 }
537
538 // Version of findScalarConstant (see above) for scalars that take two operands (e.g. a 'double').
539 Id Builder::findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned v1, unsigned v2) const
540 {
541     Instruction* constant;
542     for (int i = 0; i < (int)groupedConstants[typeClass].size(); ++i) {
543         constant = groupedConstants[typeClass][i];
544         if (constant->getOpCode() == opcode &&
545             constant->getTypeId() == typeId &&
546             constant->getImmediateOperand(0) == v1 &&
547             constant->getImmediateOperand(1) == v2)
548             return constant->getResultId();
549     }
550
551     return 0;
552 }
553
554 // Return true if consuming 'opcode' means consuming a constant.
555 // "constant" here means after final transform to executable code,
556 // the value consumed will be a constant, so includes specialization.
557 bool Builder::isConstantOpCode(Op opcode) const
558 {
559     switch (opcode) {
560     case OpUndef: 
561     case OpConstantTrue:
562     case OpConstantFalse:
563     case OpConstant:
564     case OpConstantComposite:
565     case OpConstantSampler:
566     case OpConstantNull:
567     case OpSpecConstantTrue:
568     case OpSpecConstantFalse:
569     case OpSpecConstant:
570     case OpSpecConstantComposite:
571     case OpSpecConstantOp:
572         return true;
573     default:
574         return false;
575     }
576 }
577
578 Id Builder::makeBoolConstant(bool b, bool specConstant)
579 {
580     Id typeId = makeBoolType();
581     Instruction* constant;
582     Op opcode = specConstant ? (b ? OpSpecConstantTrue : OpSpecConstantFalse) : (b ? OpConstantTrue : OpConstantFalse);
583
584     // See if we already made it
585     Id existing = 0;
586     for (int i = 0; i < (int)groupedConstants[OpTypeBool].size(); ++i) {
587         constant = groupedConstants[OpTypeBool][i];
588         if (constant->getTypeId() == typeId && constant->getOpCode() == opcode)
589             existing = constant->getResultId();
590     }
591
592     if (existing)
593         return existing;
594
595     // Make it
596     Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
597     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
598     groupedConstants[OpTypeBool].push_back(c);
599     module.mapInstruction(c);
600
601     return c->getResultId();
602 }
603
604 Id Builder::makeIntConstant(Id typeId, unsigned value, bool specConstant)
605 {
606     Op opcode = specConstant ? OpSpecConstant : OpConstant;
607     Id existing = findScalarConstant(OpTypeInt, opcode, typeId, value);
608     if (existing)
609         return existing;
610
611     Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
612     c->addImmediateOperand(value);
613     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
614     groupedConstants[OpTypeInt].push_back(c);
615     module.mapInstruction(c);
616
617     return c->getResultId();
618 }
619
620 Id Builder::makeFloatConstant(float f, bool specConstant)
621 {
622     Op opcode = specConstant ? OpSpecConstant : OpConstant;
623     Id typeId = makeFloatType(32);
624     unsigned value = *(unsigned int*)&f;
625     Id existing = findScalarConstant(OpTypeFloat, opcode, typeId, value);
626     if (existing)
627         return existing;
628
629     Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
630     c->addImmediateOperand(value);
631     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
632     groupedConstants[OpTypeFloat].push_back(c);
633     module.mapInstruction(c);
634
635     return c->getResultId();
636 }
637
638 Id Builder::makeDoubleConstant(double d, bool specConstant)
639 {
640     Op opcode = specConstant ? OpSpecConstant : OpConstant;
641     Id typeId = makeFloatType(64);
642     unsigned long long value = *(unsigned long long*)&d;
643     unsigned op1 = value & 0xFFFFFFFF;
644     unsigned op2 = value >> 32;
645     Id existing = findScalarConstant(OpTypeFloat, opcode, typeId, op1, op2);
646     if (existing)
647         return existing;
648
649     Instruction* c = new Instruction(getUniqueId(), typeId, opcode);
650     c->addImmediateOperand(op1);
651     c->addImmediateOperand(op2);
652     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
653     groupedConstants[OpTypeFloat].push_back(c);
654     module.mapInstruction(c);
655
656     return c->getResultId();
657 }
658
659 Id Builder::findCompositeConstant(Op typeClass, std::vector<Id>& comps) const
660 {
661     Instruction* constant = 0;
662     bool found = false;
663     for (int i = 0; i < (int)groupedConstants[typeClass].size(); ++i) {
664         constant = groupedConstants[typeClass][i];
665
666         // same shape?
667         if (constant->getNumOperands() != (int)comps.size())
668             continue;
669
670         // same contents?
671         bool mismatch = false;
672         for (int op = 0; op < constant->getNumOperands(); ++op) {
673             if (constant->getIdOperand(op) != comps[op]) {
674                 mismatch = true;
675                 break;
676             }
677         }
678         if (! mismatch) {
679             found = true;
680             break;
681         }
682     }
683
684     return found ? constant->getResultId() : NoResult;
685 }
686
687 // Comments in header
688 Id Builder::makeCompositeConstant(Id typeId, std::vector<Id>& members)
689 {
690     assert(typeId);
691     Op typeClass = getTypeClass(typeId);
692
693     switch (typeClass) {
694     case OpTypeVector:
695     case OpTypeArray:
696     case OpTypeStruct:
697     case OpTypeMatrix:
698         break;
699     default:
700         assert(0);
701         return makeFloatConstant(0.0);
702     }
703
704     Id existing = findCompositeConstant(typeClass, members);
705     if (existing)
706         return existing;
707
708     Instruction* c = new Instruction(getUniqueId(), typeId, OpConstantComposite);
709     for (int op = 0; op < (int)members.size(); ++op)
710         c->addIdOperand(members[op]);
711     constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(c));
712     groupedConstants[typeClass].push_back(c);
713     module.mapInstruction(c);
714
715     return c->getResultId();
716 }
717
718 Instruction* Builder::addEntryPoint(ExecutionModel model, Function* function, const char* name)
719 {
720     Instruction* entryPoint = new Instruction(OpEntryPoint);
721     entryPoint->addImmediateOperand(model);
722     entryPoint->addIdOperand(function->getId());
723     entryPoint->addStringOperand(name);
724
725     entryPoints.push_back(std::unique_ptr<Instruction>(entryPoint));
726
727     return entryPoint;
728 }
729
730 // Currently relying on the fact that all 'value' of interest are small non-negative values.
731 void Builder::addExecutionMode(Function* entryPoint, ExecutionMode mode, int value1, int value2, int value3)
732 {
733     Instruction* instr = new Instruction(OpExecutionMode);
734     instr->addIdOperand(entryPoint->getId());
735     instr->addImmediateOperand(mode);
736     if (value1 >= 0)
737         instr->addImmediateOperand(value1);
738     if (value2 >= 0)
739         instr->addImmediateOperand(value2);
740     if (value3 >= 0)
741         instr->addImmediateOperand(value3);
742
743     executionModes.push_back(std::unique_ptr<Instruction>(instr));
744 }
745
746 void Builder::addName(Id id, const char* string)
747 {
748     Instruction* name = new Instruction(OpName);
749     name->addIdOperand(id);
750     name->addStringOperand(string);
751
752     names.push_back(std::unique_ptr<Instruction>(name));
753 }
754
755 void Builder::addMemberName(Id id, int memberNumber, const char* string)
756 {
757     Instruction* name = new Instruction(OpMemberName);
758     name->addIdOperand(id);
759     name->addImmediateOperand(memberNumber);
760     name->addStringOperand(string);
761
762     names.push_back(std::unique_ptr<Instruction>(name));
763 }
764
765 void Builder::addLine(Id target, Id fileName, int lineNum, int column)
766 {
767     Instruction* line = new Instruction(OpLine);
768     line->addIdOperand(target);
769     line->addIdOperand(fileName);
770     line->addImmediateOperand(lineNum);
771     line->addImmediateOperand(column);
772
773     lines.push_back(std::unique_ptr<Instruction>(line));
774 }
775
776 void Builder::addDecoration(Id id, Decoration decoration, int num)
777 {
778     if (decoration == (spv::Decoration)spv::BadValue)
779         return;
780     Instruction* dec = new Instruction(OpDecorate);
781     dec->addIdOperand(id);
782     dec->addImmediateOperand(decoration);
783     if (num >= 0)
784         dec->addImmediateOperand(num);
785
786     decorations.push_back(std::unique_ptr<Instruction>(dec));
787 }
788
789 void Builder::addMemberDecoration(Id id, unsigned int member, Decoration decoration, int num)
790 {
791     Instruction* dec = new Instruction(OpMemberDecorate);
792     dec->addIdOperand(id);
793     dec->addImmediateOperand(member);
794     dec->addImmediateOperand(decoration);
795     if (num >= 0)
796         dec->addImmediateOperand(num);
797
798     decorations.push_back(std::unique_ptr<Instruction>(dec));
799 }
800
801 // Comments in header
802 Function* Builder::makeMain()
803 {
804     assert(! mainFunction);
805
806     Block* entry;
807     std::vector<Id> params;
808
809     mainFunction = makeFunctionEntry(makeVoidType(), "main", params, &entry);
810
811     return mainFunction;
812 }
813
814 // Comments in header
815 Function* Builder::makeFunctionEntry(Id returnType, const char* name, std::vector<Id>& paramTypes, Block **entry)
816 {
817     Id typeId = makeFunctionType(returnType, paramTypes);
818     Id firstParamId = paramTypes.size() == 0 ? 0 : getUniqueIds((int)paramTypes.size());
819     Function* function = new Function(getUniqueId(), returnType, typeId, firstParamId, module);
820
821     if (entry) {
822         *entry = new Block(getUniqueId(), *function);
823         function->addBlock(*entry);
824         setBuildPoint(*entry);
825     }
826
827     if (name)
828         addName(function->getId(), name);
829
830     functions.push_back(std::unique_ptr<Function>(function));
831
832     return function;
833 }
834
835 // Comments in header
836 void Builder::makeReturn(bool implicit, Id retVal)
837 {
838     if (retVal) {
839         Instruction* inst = new Instruction(NoResult, NoType, OpReturnValue);
840         inst->addIdOperand(retVal);
841         buildPoint->addInstruction(std::unique_ptr<Instruction>(inst));
842     } else
843         buildPoint->addInstruction(std::unique_ptr<Instruction>(new Instruction(NoResult, NoType, OpReturn)));
844
845     if (! implicit)
846         createAndSetNoPredecessorBlock("post-return");
847 }
848
849 // Comments in header
850 void Builder::leaveFunction()
851 {
852     Block* block = buildPoint;
853     Function& function = buildPoint->getParent();
854     assert(block);
855
856     // If our function did not contain a return, add a return void now.
857     if (! block->isTerminated()) {
858         if (function.getReturnType() == makeVoidType())
859             makeReturn(true);
860         else {
861             makeReturn(true, createUndefined(function.getReturnType()));
862         }
863     }
864 }
865
866 // Comments in header
867 void Builder::makeDiscard()
868 {
869     buildPoint->addInstruction(std::unique_ptr<Instruction>(new Instruction(OpKill)));
870     createAndSetNoPredecessorBlock("post-discard");
871 }
872
873 // Comments in header
874 Id Builder::createVariable(StorageClass storageClass, Id type, const char* name)
875 {
876     Id pointerType = makePointer(storageClass, type);
877     Instruction* inst = new Instruction(getUniqueId(), pointerType, OpVariable);
878     inst->addImmediateOperand(storageClass);
879
880     switch (storageClass) {
881     case StorageClassFunction:
882         // Validation rules require the declaration in the entry block
883         buildPoint->getParent().addLocalVariable(std::unique_ptr<Instruction>(inst));
884         break;
885
886     default:
887         constantsTypesGlobals.push_back(std::unique_ptr<Instruction>(inst));
888         module.mapInstruction(inst);
889         break;
890     }
891
892     if (name)
893         addName(inst->getResultId(), name);
894
895     return inst->getResultId();
896 }
897
898 // Comments in header
899 Id Builder::createUndefined(Id type)
900 {
901   Instruction* inst = new Instruction(getUniqueId(), type, OpUndef);
902   buildPoint->addInstruction(std::unique_ptr<Instruction>(inst));
903   return inst->getResultId();
904 }
905
906 // Comments in header
907 void Builder::createStore(Id rValue, Id lValue)
908 {
909     Instruction* store = new Instruction(OpStore);
910     store->addIdOperand(lValue);
911     store->addIdOperand(rValue);
912     buildPoint->addInstruction(std::unique_ptr<Instruction>(store));
913 }
914
915 // Comments in header
916 Id Builder::createLoad(Id lValue)
917 {
918     Instruction* load = new Instruction(getUniqueId(), getDerefTypeId(lValue), OpLoad);
919     load->addIdOperand(lValue);
920     buildPoint->addInstruction(std::unique_ptr<Instruction>(load));
921
922     return load->getResultId();
923 }
924
925 // Comments in header
926 Id Builder::createAccessChain(StorageClass storageClass, Id base, std::vector<Id>& offsets)
927 {
928     // Figure out the final resulting type.
929     spv::Id typeId = getTypeId(base);
930     assert(isPointerType(typeId) && offsets.size() > 0);
931     typeId = getContainedTypeId(typeId);
932     for (int i = 0; i < (int)offsets.size(); ++i) {
933         if (isStructType(typeId)) {
934             assert(isConstantScalar(offsets[i]));
935             typeId = getContainedTypeId(typeId, getConstantScalar(offsets[i]));
936         } else
937             typeId = getContainedTypeId(typeId, offsets[i]);
938     }
939     typeId = makePointer(storageClass, typeId);
940
941     // Make the instruction
942     Instruction* chain = new Instruction(getUniqueId(), typeId, OpAccessChain);
943     chain->addIdOperand(base);
944     for (int i = 0; i < (int)offsets.size(); ++i)
945         chain->addIdOperand(offsets[i]);
946     buildPoint->addInstruction(std::unique_ptr<Instruction>(chain));
947
948     return chain->getResultId();
949 }
950
951 Id Builder::createArrayLength(Id base, unsigned int member)
952 {
953     Instruction* length = new Instruction(getUniqueId(), makeIntType(32), OpArrayLength);
954     length->addIdOperand(base);
955     length->addImmediateOperand(member);
956     buildPoint->addInstruction(std::unique_ptr<Instruction>(length));
957
958     return length->getResultId();
959 }
960
961 Id Builder::createCompositeExtract(Id composite, Id typeId, unsigned index)
962 {
963     Instruction* extract = new Instruction(getUniqueId(), typeId, OpCompositeExtract);
964     extract->addIdOperand(composite);
965     extract->addImmediateOperand(index);
966     buildPoint->addInstruction(std::unique_ptr<Instruction>(extract));
967
968     return extract->getResultId();
969 }
970
971 Id Builder::createCompositeExtract(Id composite, Id typeId, std::vector<unsigned>& indexes)
972 {
973     Instruction* extract = new Instruction(getUniqueId(), typeId, OpCompositeExtract);
974     extract->addIdOperand(composite);
975     for (int i = 0; i < (int)indexes.size(); ++i)
976         extract->addImmediateOperand(indexes[i]);
977     buildPoint->addInstruction(std::unique_ptr<Instruction>(extract));
978
979     return extract->getResultId();
980 }
981
982 Id Builder::createCompositeInsert(Id object, Id composite, Id typeId, unsigned index)
983 {
984     Instruction* insert = new Instruction(getUniqueId(), typeId, OpCompositeInsert);
985     insert->addIdOperand(object);
986     insert->addIdOperand(composite);
987     insert->addImmediateOperand(index);
988     buildPoint->addInstruction(std::unique_ptr<Instruction>(insert));
989
990     return insert->getResultId();
991 }
992
993 Id Builder::createCompositeInsert(Id object, Id composite, Id typeId, std::vector<unsigned>& indexes)
994 {
995     Instruction* insert = new Instruction(getUniqueId(), typeId, OpCompositeInsert);
996     insert->addIdOperand(object);
997     insert->addIdOperand(composite);
998     for (int i = 0; i < (int)indexes.size(); ++i)
999         insert->addImmediateOperand(indexes[i]);
1000     buildPoint->addInstruction(std::unique_ptr<Instruction>(insert));
1001
1002     return insert->getResultId();
1003 }
1004
1005 Id Builder::createVectorExtractDynamic(Id vector, Id typeId, Id componentIndex)
1006 {
1007     Instruction* extract = new Instruction(getUniqueId(), typeId, OpVectorExtractDynamic);
1008     extract->addIdOperand(vector);
1009     extract->addIdOperand(componentIndex);
1010     buildPoint->addInstruction(std::unique_ptr<Instruction>(extract));
1011
1012     return extract->getResultId();
1013 }
1014
1015 Id Builder::createVectorInsertDynamic(Id vector, Id typeId, Id component, Id componentIndex)
1016 {
1017     Instruction* insert = new Instruction(getUniqueId(), typeId, OpVectorInsertDynamic);
1018     insert->addIdOperand(vector);
1019     insert->addIdOperand(component);
1020     insert->addIdOperand(componentIndex);
1021     buildPoint->addInstruction(std::unique_ptr<Instruction>(insert));
1022
1023     return insert->getResultId();
1024 }
1025
1026 // An opcode that has no operands, no result id, and no type
1027 void Builder::createNoResultOp(Op opCode)
1028 {
1029     Instruction* op = new Instruction(opCode);
1030     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1031 }
1032
1033 // An opcode that has one operand, no result id, and no type
1034 void Builder::createNoResultOp(Op opCode, Id operand)
1035 {
1036     Instruction* op = new Instruction(opCode);
1037     op->addIdOperand(operand);
1038     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1039 }
1040
1041 // An opcode that has one operand, no result id, and no type
1042 void Builder::createNoResultOp(Op opCode, const std::vector<Id>& operands)
1043 {
1044     Instruction* op = new Instruction(opCode);
1045     for (auto operand : operands)
1046         op->addIdOperand(operand);
1047     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1048 }
1049
1050 void Builder::createControlBarrier(Scope execution, Scope memory, MemorySemanticsMask semantics)
1051 {
1052     Instruction* op = new Instruction(OpControlBarrier);
1053     op->addImmediateOperand(makeUintConstant(execution));
1054     op->addImmediateOperand(makeUintConstant(memory));
1055     op->addImmediateOperand(makeUintConstant(semantics));
1056     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1057 }
1058
1059 void Builder::createMemoryBarrier(unsigned executionScope, unsigned memorySemantics)
1060 {
1061     Instruction* op = new Instruction(OpMemoryBarrier);
1062     op->addImmediateOperand(makeUintConstant(executionScope));
1063     op->addImmediateOperand(makeUintConstant(memorySemantics));
1064     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1065 }
1066
1067 // An opcode that has one operands, a result id, and a type
1068 Id Builder::createUnaryOp(Op opCode, Id typeId, Id operand)
1069 {
1070     Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
1071     op->addIdOperand(operand);
1072     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1073
1074     return op->getResultId();
1075 }
1076
1077 Id Builder::createBinOp(Op opCode, Id typeId, Id left, Id right)
1078 {
1079     Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
1080     op->addIdOperand(left);
1081     op->addIdOperand(right);
1082     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1083
1084     return op->getResultId();
1085 }
1086
1087 Id Builder::createTriOp(Op opCode, Id typeId, Id op1, Id op2, Id op3)
1088 {
1089     Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
1090     op->addIdOperand(op1);
1091     op->addIdOperand(op2);
1092     op->addIdOperand(op3);
1093     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1094
1095     return op->getResultId();
1096 }
1097
1098 Id Builder::createOp(Op opCode, Id typeId, const std::vector<Id>& operands)
1099 {
1100     Instruction* op = new Instruction(getUniqueId(), typeId, opCode);
1101     for (auto operand : operands)
1102         op->addIdOperand(operand);
1103     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1104
1105     return op->getResultId();
1106 }
1107
1108 Id Builder::createFunctionCall(spv::Function* function, std::vector<spv::Id>& args)
1109 {
1110     Instruction* op = new Instruction(getUniqueId(), function->getReturnType(), OpFunctionCall);
1111     op->addIdOperand(function->getId());
1112     for (int a = 0; a < (int)args.size(); ++a)
1113         op->addIdOperand(args[a]);
1114     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1115
1116     return op->getResultId();
1117 }
1118
1119 // Comments in header
1120 Id Builder::createRvalueSwizzle(Id typeId, Id source, std::vector<unsigned>& channels)
1121 {
1122     if (channels.size() == 1)
1123         return createCompositeExtract(source, typeId, channels.front());
1124
1125     Instruction* swizzle = new Instruction(getUniqueId(), typeId, OpVectorShuffle);
1126     assert(isVector(source));
1127     swizzle->addIdOperand(source);
1128     swizzle->addIdOperand(source);
1129     for (int i = 0; i < (int)channels.size(); ++i)
1130         swizzle->addImmediateOperand(channels[i]);
1131     buildPoint->addInstruction(std::unique_ptr<Instruction>(swizzle));
1132
1133     return swizzle->getResultId();
1134 }
1135
1136 // Comments in header
1137 Id Builder::createLvalueSwizzle(Id typeId, Id target, Id source, std::vector<unsigned>& channels)
1138 {
1139     assert(getNumComponents(source) == (int)channels.size());
1140     if (channels.size() == 1 && getNumComponents(source) == 1)
1141         return createCompositeInsert(source, target, typeId, channels.front());
1142
1143     Instruction* swizzle = new Instruction(getUniqueId(), typeId, OpVectorShuffle);
1144     assert(isVector(source));
1145     assert(isVector(target));
1146     swizzle->addIdOperand(target);
1147     swizzle->addIdOperand(source);
1148
1149     // Set up an identity shuffle from the base value to the result value
1150     unsigned int components[4];
1151     int numTargetComponents = getNumComponents(target);
1152     for (int i = 0; i < numTargetComponents; ++i)
1153         components[i] = i;
1154
1155     // Punch in the l-value swizzle
1156     for (int i = 0; i < (int)channels.size(); ++i)
1157         components[channels[i]] = numTargetComponents + i;
1158
1159     // finish the instruction with these components selectors
1160     for (int i = 0; i < numTargetComponents; ++i)
1161         swizzle->addImmediateOperand(components[i]);
1162     buildPoint->addInstruction(std::unique_ptr<Instruction>(swizzle));
1163
1164     return swizzle->getResultId();
1165 }
1166
1167 // Comments in header
1168 void Builder::promoteScalar(Decoration precision, Id& left, Id& right)
1169 {
1170     int direction = getNumComponents(right) - getNumComponents(left);
1171
1172     if (direction > 0)
1173         left = smearScalar(precision, left, makeVectorType(getTypeId(left), getNumComponents(right)));
1174     else if (direction < 0)
1175         right = smearScalar(precision, right, makeVectorType(getTypeId(right), getNumComponents(left)));
1176
1177     return;
1178 }
1179
1180 // Comments in header
1181 Id Builder::smearScalar(Decoration /*precision*/, Id scalar, Id vectorType)
1182 {
1183     assert(getNumComponents(scalar) == 1);
1184     assert(getTypeId(scalar) == getScalarTypeId(vectorType));
1185
1186     int numComponents = getNumTypeComponents(vectorType);
1187     if (numComponents == 1)
1188         return scalar;
1189
1190     Instruction* smear = new Instruction(getUniqueId(), vectorType, OpCompositeConstruct);
1191     for (int c = 0; c < numComponents; ++c)
1192         smear->addIdOperand(scalar);
1193     buildPoint->addInstruction(std::unique_ptr<Instruction>(smear));
1194
1195     return smear->getResultId();
1196 }
1197
1198 // Comments in header
1199 Id Builder::createBuiltinCall(Decoration /*precision*/, Id resultType, Id builtins, int entryPoint, std::vector<Id>& args)
1200 {
1201     Instruction* inst = new Instruction(getUniqueId(), resultType, OpExtInst);
1202     inst->addIdOperand(builtins);
1203     inst->addImmediateOperand(entryPoint);
1204     for (int arg = 0; arg < (int)args.size(); ++arg)
1205         inst->addIdOperand(args[arg]);
1206
1207     buildPoint->addInstruction(std::unique_ptr<Instruction>(inst));
1208     return inst->getResultId();
1209 }
1210
1211 // Accept all parameters needed to create a texture instruction.
1212 // Create the correct instruction based on the inputs, and make the call.
1213 Id Builder::createTextureCall(Decoration precision, Id resultType, bool sparse, bool fetch, bool proj, bool gather, const TextureParameters& parameters)
1214 {
1215     static const int maxTextureArgs = 10;
1216     Id texArgs[maxTextureArgs] = {};
1217
1218     //
1219     // Set up the fixed arguments
1220     //
1221     int numArgs = 0;
1222     bool xplicit = false;
1223     texArgs[numArgs++] = parameters.sampler;
1224     texArgs[numArgs++] = parameters.coords;
1225     if (parameters.Dref)
1226         texArgs[numArgs++] = parameters.Dref;
1227     if (parameters.comp)
1228         texArgs[numArgs++] = parameters.comp;
1229
1230     //
1231     // Set up the optional arguments
1232     //
1233     int optArgNum = numArgs;                        // track which operand, if it exists, is the mask of optional arguments
1234     ++numArgs;                                      // speculatively make room for the mask operand
1235     ImageOperandsMask mask = ImageOperandsMaskNone; // the mask operand
1236     if (parameters.bias) {
1237         mask = (ImageOperandsMask)(mask | ImageOperandsBiasMask);
1238         texArgs[numArgs++] = parameters.bias;
1239     }
1240     if (parameters.lod) {
1241         mask = (ImageOperandsMask)(mask | ImageOperandsLodMask);
1242         texArgs[numArgs++] = parameters.lod;
1243         xplicit = true;
1244     }
1245     if (parameters.gradX) {
1246         mask = (ImageOperandsMask)(mask | ImageOperandsGradMask);
1247         texArgs[numArgs++] = parameters.gradX;
1248         texArgs[numArgs++] = parameters.gradY;
1249         xplicit = true;
1250     }
1251     if (parameters.offset) {
1252         if (isConstant(parameters.offset))
1253             mask = (ImageOperandsMask)(mask | ImageOperandsConstOffsetMask);
1254         else
1255             mask = (ImageOperandsMask)(mask | ImageOperandsOffsetMask);
1256         texArgs[numArgs++] = parameters.offset;
1257     }
1258     if (parameters.offsets) {
1259         mask = (ImageOperandsMask)(mask | ImageOperandsConstOffsetsMask);
1260         texArgs[numArgs++] = parameters.offsets;
1261     }
1262     if (parameters.sample) {
1263         mask = (ImageOperandsMask)(mask | ImageOperandsSampleMask);
1264         texArgs[numArgs++] = parameters.sample;
1265     }
1266     if (parameters.lodClamp) {
1267         mask = (ImageOperandsMask)(mask | ImageOperandsMinLodMask);
1268         texArgs[numArgs++] = parameters.lodClamp;
1269     }
1270     if (mask == ImageOperandsMaskNone)
1271         --numArgs;  // undo speculative reservation for the mask argument
1272     else
1273         texArgs[optArgNum] = mask;
1274
1275     //
1276     // Set up the instruction
1277     //
1278     Op opCode;
1279     opCode = OpImageSampleImplicitLod;
1280     if (fetch) {
1281         if (sparse)
1282             opCode = OpImageSparseFetch;
1283         else
1284             opCode = OpImageFetch;
1285     } else if (gather) {
1286         if (parameters.Dref)
1287             if (sparse)
1288                 opCode = OpImageSparseDrefGather;
1289             else
1290                 opCode = OpImageDrefGather;
1291         else
1292             if (sparse)
1293                 opCode = OpImageSparseGather;
1294             else
1295                 opCode = OpImageGather;
1296     } else if (xplicit) {
1297         if (parameters.Dref) {
1298             if (proj)
1299                 if (sparse)
1300                     opCode = OpImageSparseSampleProjDrefExplicitLod;
1301                 else
1302                     opCode = OpImageSampleProjDrefExplicitLod;
1303             else
1304                 if (sparse)
1305                     opCode = OpImageSparseSampleDrefExplicitLod;
1306                 else
1307                     opCode = OpImageSampleDrefExplicitLod;
1308         } else {
1309             if (proj)
1310                 if (sparse)
1311                     opCode = OpImageSparseSampleProjExplicitLod;
1312                 else
1313                     opCode = OpImageSampleProjExplicitLod;
1314             else
1315                 if (sparse)
1316                     opCode = OpImageSparseSampleExplicitLod;
1317                 else
1318                     opCode = OpImageSampleExplicitLod;
1319         }
1320     } else {
1321         if (parameters.Dref) {
1322             if (proj)
1323                 if (sparse)
1324                     opCode = OpImageSparseSampleProjDrefImplicitLod;
1325                 else
1326                     opCode = OpImageSampleProjDrefImplicitLod;
1327             else
1328                 if (sparse)
1329                     opCode = OpImageSparseSampleDrefImplicitLod;
1330                 else
1331                     opCode = OpImageSampleDrefImplicitLod;
1332         } else {
1333             if (proj)
1334                 if (sparse)
1335                     opCode = OpImageSparseSampleProjImplicitLod;
1336                 else
1337                     opCode = OpImageSampleProjImplicitLod;
1338             else
1339                 if (sparse)
1340                     opCode = OpImageSparseSampleImplicitLod;
1341                 else
1342                     opCode = OpImageSampleImplicitLod;
1343         }
1344     }
1345
1346     // See if the result type is expecting a smeared result.
1347     // This happens when a legacy shadow*() call is made, which
1348     // gets a vec4 back instead of a float.
1349     Id smearedType = resultType;
1350     if (! isScalarType(resultType)) {
1351         switch (opCode) {
1352         case OpImageSampleDrefImplicitLod:
1353         case OpImageSampleDrefExplicitLod:
1354         case OpImageSampleProjDrefImplicitLod:
1355         case OpImageSampleProjDrefExplicitLod:
1356             resultType = getScalarTypeId(resultType);
1357             break;
1358         default:
1359             break;
1360         }
1361     }
1362
1363     Id typeId0 = 0;
1364     Id typeId1 = 0;
1365
1366     if (sparse) {
1367         typeId0 = resultType;
1368         typeId1 = getDerefTypeId(parameters.texelOut);
1369         resultType = makeStructResultType(typeId0, typeId1);
1370     }
1371
1372     // Build the SPIR-V instruction
1373     Instruction* textureInst = new Instruction(getUniqueId(), resultType, opCode);
1374     for (int op = 0; op < optArgNum; ++op)
1375         textureInst->addIdOperand(texArgs[op]);
1376     if (optArgNum < numArgs)
1377         textureInst->addImmediateOperand(texArgs[optArgNum]);
1378     for (int op = optArgNum + 1; op < numArgs; ++op)
1379         textureInst->addIdOperand(texArgs[op]);
1380     setPrecision(textureInst->getResultId(), precision);
1381     buildPoint->addInstruction(std::unique_ptr<Instruction>(textureInst));
1382
1383     Id resultId = textureInst->getResultId();
1384
1385     if (sparse) {
1386         // Decode the return type that was a special structure
1387         createStore(createCompositeExtract(resultId, typeId1, 1), parameters.texelOut);
1388         resultId = createCompositeExtract(resultId, typeId0, 0);
1389     } else {
1390         // When a smear is needed, do it, as per what was computed
1391         // above when resultType was changed to a scalar type.
1392         if (resultType != smearedType)
1393             resultId = smearScalar(precision, resultId, smearedType);
1394     }
1395
1396     return resultId;
1397 }
1398
1399 // Comments in header
1400 Id Builder::createTextureQueryCall(Op opCode, const TextureParameters& parameters)
1401 {
1402     // Figure out the result type
1403     Id resultType = 0;
1404     switch (opCode) {
1405     case OpImageQuerySize:
1406     case OpImageQuerySizeLod:
1407     {
1408         int numComponents = 0;
1409         switch (getTypeDimensionality(getImageType(parameters.sampler))) {
1410         case Dim1D:
1411         case DimBuffer:
1412             numComponents = 1;
1413             break;
1414         case Dim2D:
1415         case DimCube:
1416         case DimRect:
1417         case DimSubpassData:
1418             numComponents = 2;
1419             break;
1420         case Dim3D:
1421             numComponents = 3;
1422             break;
1423
1424         default:
1425             assert(0);
1426             break;
1427         }
1428         if (isArrayedImageType(getImageType(parameters.sampler)))
1429             ++numComponents;
1430         if (numComponents == 1)
1431             resultType = makeIntType(32);
1432         else
1433             resultType = makeVectorType(makeIntType(32), numComponents);
1434
1435         break;
1436     }
1437     case OpImageQueryLod:
1438         resultType = makeVectorType(makeFloatType(32), 2);
1439         break;
1440     case OpImageQueryLevels:
1441     case OpImageQuerySamples:
1442         resultType = makeIntType(32);
1443         break;
1444     default:
1445         assert(0);
1446         break;
1447     }
1448
1449     Instruction* query = new Instruction(getUniqueId(), resultType, opCode);
1450     query->addIdOperand(parameters.sampler);
1451     if (parameters.coords)
1452         query->addIdOperand(parameters.coords);
1453     if (parameters.lod)
1454         query->addIdOperand(parameters.lod);
1455     buildPoint->addInstruction(std::unique_ptr<Instruction>(query));
1456
1457     return query->getResultId();
1458 }
1459
1460 // External comments in header.
1461 // Operates recursively to visit the composite's hierarchy.
1462 Id Builder::createCompositeCompare(Decoration precision, Id value1, Id value2, bool equal)
1463 {
1464     Id boolType = makeBoolType();
1465     Id valueType = getTypeId(value1);
1466
1467     Id resultId;
1468
1469     int numConstituents = getNumTypeConstituents(valueType);
1470
1471     // Scalars and Vectors
1472
1473     if (isScalarType(valueType) || isVectorType(valueType)) {
1474         assert(valueType == getTypeId(value2));
1475         // These just need a single comparison, just have
1476         // to figure out what it is.
1477         Op op;
1478         switch (getMostBasicTypeClass(valueType)) {
1479         case OpTypeFloat:
1480             op = equal ? OpFOrdEqual : OpFOrdNotEqual;
1481             break;
1482         case OpTypeInt:
1483             op = equal ? OpIEqual : OpINotEqual;
1484             break;
1485         case OpTypeBool:
1486             op = equal ? OpLogicalEqual : OpLogicalNotEqual;
1487             precision = NoPrecision;
1488             break;
1489         }
1490
1491         if (isScalarType(valueType)) {
1492             // scalar
1493             resultId = createBinOp(op, boolType, value1, value2);
1494             setPrecision(resultId, precision);
1495         } else {
1496             // vector
1497             resultId = createBinOp(op, makeVectorType(boolType, numConstituents), value1, value2);
1498             setPrecision(resultId, precision);
1499             // reduce vector compares...
1500             resultId = createUnaryOp(equal ? OpAll : OpAny, boolType, resultId);
1501         }
1502
1503         return resultId;
1504     }
1505
1506     // Only structs, arrays, and matrices should be left.
1507     // They share in common the reduction operation across their constituents.
1508     assert(isAggregateType(valueType) || isMatrixType(valueType));
1509
1510     // Compare each pair of constituents
1511     for (int constituent = 0; constituent < numConstituents; ++constituent) {
1512         std::vector<unsigned> indexes(1, constituent);
1513         Id constituentType1 = getContainedTypeId(getTypeId(value1), constituent);
1514         Id constituentType2 = getContainedTypeId(getTypeId(value2), constituent);
1515         Id constituent1 = createCompositeExtract(value1, constituentType1, indexes);
1516         Id constituent2 = createCompositeExtract(value2, constituentType2, indexes);
1517
1518         Id subResultId = createCompositeCompare(precision, constituent1, constituent2, equal);
1519
1520         if (constituent == 0)
1521             resultId = subResultId;
1522         else
1523             resultId = createBinOp(equal ? OpLogicalAnd : OpLogicalOr, boolType, resultId, subResultId);
1524     }
1525
1526     return resultId;
1527 }
1528
1529 // OpCompositeConstruct
1530 Id Builder::createCompositeConstruct(Id typeId, std::vector<Id>& constituents)
1531 {
1532     assert(isAggregateType(typeId) || (getNumTypeConstituents(typeId) > 1 && getNumTypeConstituents(typeId) == (int)constituents.size()));
1533
1534     Instruction* op = new Instruction(getUniqueId(), typeId, OpCompositeConstruct);
1535     for (int c = 0; c < (int)constituents.size(); ++c)
1536         op->addIdOperand(constituents[c]);
1537     buildPoint->addInstruction(std::unique_ptr<Instruction>(op));
1538
1539     return op->getResultId();
1540 }
1541
1542 // Vector or scalar constructor
1543 Id Builder::createConstructor(Decoration precision, const std::vector<Id>& sources, Id resultTypeId)
1544 {
1545     Id result = 0;
1546     unsigned int numTargetComponents = getNumTypeComponents(resultTypeId);
1547     unsigned int targetComponent = 0;
1548
1549     // Special case: when calling a vector constructor with a single scalar
1550     // argument, smear the scalar
1551     if (sources.size() == 1 && isScalar(sources[0]) && numTargetComponents > 1)
1552         return smearScalar(precision, sources[0], resultTypeId);
1553
1554     Id scalarTypeId = getScalarTypeId(resultTypeId);
1555     std::vector<Id> constituents;  // accumulate the arguments for OpCompositeConstruct
1556     for (unsigned int i = 0; i < sources.size(); ++i) {
1557         assert(! isAggregate(sources[i]));
1558         unsigned int sourceSize = getNumComponents(sources[i]);
1559         unsigned int sourcesToUse = sourceSize;
1560         if (sourcesToUse + targetComponent > numTargetComponents)
1561             sourcesToUse = numTargetComponents - targetComponent;
1562
1563         for (unsigned int s = 0; s < sourcesToUse; ++s) {
1564             Id arg = sources[i];
1565             if (sourceSize > 1) {
1566                 std::vector<unsigned> swiz;
1567                 swiz.push_back(s);
1568                 arg = createRvalueSwizzle(scalarTypeId, arg, swiz);
1569             }
1570
1571             if (numTargetComponents > 1)
1572                 constituents.push_back(arg);
1573             else
1574                 result = arg;
1575             ++targetComponent;
1576         }
1577
1578         if (targetComponent >= numTargetComponents)
1579             break;
1580     }
1581
1582     if (constituents.size() > 0)
1583         result = createCompositeConstruct(resultTypeId, constituents);
1584
1585     setPrecision(result, precision);
1586
1587     return result;
1588 }
1589
1590 // Comments in header
1591 Id Builder::createMatrixConstructor(Decoration precision, const std::vector<Id>& sources, Id resultTypeId)
1592 {
1593     Id componentTypeId = getScalarTypeId(resultTypeId);
1594     int numCols = getTypeNumColumns(resultTypeId);
1595     int numRows = getTypeNumRows(resultTypeId);
1596
1597     // Will use a two step process
1598     // 1. make a compile-time 2D array of values
1599     // 2. construct a matrix from that array
1600
1601     // Step 1.
1602
1603     // initialize the array to the identity matrix
1604     Id ids[maxMatrixSize][maxMatrixSize];
1605     Id  one = makeFloatConstant(1.0);
1606     Id zero = makeFloatConstant(0.0);
1607     for (int col = 0; col < 4; ++col) {
1608         for (int row = 0; row < 4; ++row) {
1609             if (col == row)
1610                 ids[col][row] = one;
1611             else
1612                 ids[col][row] = zero;
1613         }
1614     }
1615
1616     // modify components as dictated by the arguments
1617     if (sources.size() == 1 && isScalar(sources[0])) {
1618         // a single scalar; resets the diagonals
1619         for (int col = 0; col < 4; ++col)
1620             ids[col][col] = sources[0];
1621     } else if (isMatrix(sources[0])) {
1622         // constructing from another matrix; copy over the parts that exist in both the argument and constructee
1623         Id matrix = sources[0];
1624         int minCols = std::min(numCols, getNumColumns(matrix));
1625         int minRows = std::min(numRows, getNumRows(matrix));
1626         for (int col = 0; col < minCols; ++col) {
1627             std::vector<unsigned> indexes;
1628             indexes.push_back(col);
1629             for (int row = 0; row < minRows; ++row) {
1630                 indexes.push_back(row);
1631                 ids[col][row] = createCompositeExtract(matrix, componentTypeId, indexes);
1632                 indexes.pop_back();
1633                 setPrecision(ids[col][row], precision);
1634             }
1635         }
1636     } else {
1637         // fill in the matrix in column-major order with whatever argument components are available
1638         int row = 0;
1639         int col = 0;
1640
1641         for (int arg = 0; arg < (int)sources.size(); ++arg) {
1642             Id argComp = sources[arg];
1643             for (int comp = 0; comp < getNumComponents(sources[arg]); ++comp) {
1644                 if (getNumComponents(sources[arg]) > 1) {
1645                     argComp = createCompositeExtract(sources[arg], componentTypeId, comp);
1646                     setPrecision(argComp, precision);
1647                 }
1648                 ids[col][row++] = argComp;
1649                 if (row == numRows) {
1650                     row = 0;
1651                     col++;
1652                 }
1653             }
1654         }
1655     }
1656
1657
1658     // Step 2:  Construct a matrix from that array.
1659     // First make the column vectors, then make the matrix.
1660
1661     // make the column vectors
1662     Id columnTypeId = getContainedTypeId(resultTypeId);
1663     std::vector<Id> matrixColumns;
1664     for (int col = 0; col < numCols; ++col) {
1665         std::vector<Id> vectorComponents;
1666         for (int row = 0; row < numRows; ++row)
1667             vectorComponents.push_back(ids[col][row]);
1668         matrixColumns.push_back(createCompositeConstruct(columnTypeId, vectorComponents));
1669     }
1670
1671     // make the matrix
1672     return createCompositeConstruct(resultTypeId, matrixColumns);
1673 }
1674
1675 // Comments in header
1676 Builder::If::If(Id cond, Builder& gb) :
1677     builder(gb),
1678     condition(cond),
1679     elseBlock(0)
1680 {
1681     function = &builder.getBuildPoint()->getParent();
1682
1683     // make the blocks, but only put the then-block into the function,
1684     // the else-block and merge-block will be added later, in order, after
1685     // earlier code is emitted
1686     thenBlock = new Block(builder.getUniqueId(), *function);
1687     mergeBlock = new Block(builder.getUniqueId(), *function);
1688
1689     // Save the current block, so that we can add in the flow control split when
1690     // makeEndIf is called.
1691     headerBlock = builder.getBuildPoint();
1692
1693     function->addBlock(thenBlock);
1694     builder.setBuildPoint(thenBlock);
1695 }
1696
1697 // Comments in header
1698 void Builder::If::makeBeginElse()
1699 {
1700     // Close out the "then" by having it jump to the mergeBlock
1701     builder.createBranch(mergeBlock);
1702
1703     // Make the first else block and add it to the function
1704     elseBlock = new Block(builder.getUniqueId(), *function);
1705     function->addBlock(elseBlock);
1706
1707     // Start building the else block
1708     builder.setBuildPoint(elseBlock);
1709 }
1710
1711 // Comments in header
1712 void Builder::If::makeEndIf()
1713 {
1714     // jump to the merge block
1715     builder.createBranch(mergeBlock);
1716
1717     // Go back to the headerBlock and make the flow control split
1718     builder.setBuildPoint(headerBlock);
1719     builder.createSelectionMerge(mergeBlock, SelectionControlMaskNone);
1720     if (elseBlock)
1721         builder.createConditionalBranch(condition, thenBlock, elseBlock);
1722     else
1723         builder.createConditionalBranch(condition, thenBlock, mergeBlock);
1724
1725     // add the merge block to the function
1726     function->addBlock(mergeBlock);
1727     builder.setBuildPoint(mergeBlock);
1728 }
1729
1730 // Comments in header
1731 void Builder::makeSwitch(Id selector, int numSegments, std::vector<int>& caseValues, std::vector<int>& valueIndexToSegment, int defaultSegment,
1732                          std::vector<Block*>& segmentBlocks)
1733 {
1734     Function& function = buildPoint->getParent();
1735
1736     // make all the blocks
1737     for (int s = 0; s < numSegments; ++s)
1738         segmentBlocks.push_back(new Block(getUniqueId(), function));
1739
1740     Block* mergeBlock = new Block(getUniqueId(), function);
1741
1742     // make and insert the switch's selection-merge instruction
1743     createSelectionMerge(mergeBlock, SelectionControlMaskNone);
1744
1745     // make the switch instruction
1746     Instruction* switchInst = new Instruction(NoResult, NoType, OpSwitch);
1747     switchInst->addIdOperand(selector);
1748     auto defaultOrMerge = (defaultSegment >= 0) ? segmentBlocks[defaultSegment] : mergeBlock;
1749     switchInst->addIdOperand(defaultOrMerge->getId());
1750     defaultOrMerge->addPredecessor(buildPoint);
1751     for (int i = 0; i < (int)caseValues.size(); ++i) {
1752         switchInst->addImmediateOperand(caseValues[i]);
1753         switchInst->addIdOperand(segmentBlocks[valueIndexToSegment[i]]->getId());
1754         segmentBlocks[valueIndexToSegment[i]]->addPredecessor(buildPoint);
1755     }
1756     buildPoint->addInstruction(std::unique_ptr<Instruction>(switchInst));
1757
1758     // push the merge block
1759     switchMerges.push(mergeBlock);
1760 }
1761
1762 // Comments in header
1763 void Builder::addSwitchBreak()
1764 {
1765     // branch to the top of the merge block stack
1766     createBranch(switchMerges.top());
1767     createAndSetNoPredecessorBlock("post-switch-break");
1768 }
1769
1770 // Comments in header
1771 void Builder::nextSwitchSegment(std::vector<Block*>& segmentBlock, int nextSegment)
1772 {
1773     int lastSegment = nextSegment - 1;
1774     if (lastSegment >= 0) {
1775         // Close out previous segment by jumping, if necessary, to next segment
1776         if (! buildPoint->isTerminated())
1777             createBranch(segmentBlock[nextSegment]);
1778     }
1779     Block* block = segmentBlock[nextSegment];
1780     block->getParent().addBlock(block);
1781     setBuildPoint(block);
1782 }
1783
1784 // Comments in header
1785 void Builder::endSwitch(std::vector<Block*>& /*segmentBlock*/)
1786 {
1787     // Close out previous segment by jumping, if necessary, to next segment
1788     if (! buildPoint->isTerminated())
1789         addSwitchBreak();
1790
1791     switchMerges.top()->getParent().addBlock(switchMerges.top());
1792     setBuildPoint(switchMerges.top());
1793
1794     switchMerges.pop();
1795 }
1796
1797 Block& Builder::makeNewBlock()
1798 {
1799     Function& function = buildPoint->getParent();
1800     auto block = new Block(getUniqueId(), function);
1801     function.addBlock(block);
1802     return *block;
1803 }
1804
1805 Builder::LoopBlocks& Builder::makeNewLoop()
1806 {
1807     loops.push({makeNewBlock(), makeNewBlock(), makeNewBlock(), makeNewBlock()});
1808     return loops.top();
1809 }
1810
1811 void Builder::createLoopContinue()
1812 {
1813     createBranch(&loops.top().continue_target);
1814     // Set up a block for dead code.
1815     createAndSetNoPredecessorBlock("post-loop-continue");
1816 }
1817
1818 void Builder::createLoopExit()
1819 {
1820     createBranch(&loops.top().merge);
1821     // Set up a block for dead code.
1822     createAndSetNoPredecessorBlock("post-loop-break");
1823 }
1824
1825 void Builder::closeLoop()
1826 {
1827     loops.pop();
1828 }
1829
1830 void Builder::clearAccessChain()
1831 {
1832     accessChain.base = NoResult;
1833     accessChain.indexChain.clear();
1834     accessChain.instr = NoResult;
1835     accessChain.swizzle.clear();
1836     accessChain.component = NoResult;
1837     accessChain.preSwizzleBaseType = NoType;
1838     accessChain.isRValue = false;
1839 }
1840
1841 // Comments in header
1842 void Builder::accessChainPushSwizzle(std::vector<unsigned>& swizzle, Id preSwizzleBaseType)
1843 {
1844     // swizzles can be stacked in GLSL, but simplified to a single
1845     // one here; the base type doesn't change
1846     if (accessChain.preSwizzleBaseType == NoType)
1847         accessChain.preSwizzleBaseType = preSwizzleBaseType;
1848
1849     // if needed, propagate the swizzle for the current access chain
1850     if (accessChain.swizzle.size()) {
1851         std::vector<unsigned> oldSwizzle = accessChain.swizzle;
1852         accessChain.swizzle.resize(0);
1853         for (unsigned int i = 0; i < swizzle.size(); ++i) {
1854             accessChain.swizzle.push_back(oldSwizzle[swizzle[i]]);
1855         }
1856     } else
1857         accessChain.swizzle = swizzle;
1858
1859     // determine if we need to track this swizzle anymore
1860     simplifyAccessChainSwizzle();
1861 }
1862
1863 // Comments in header
1864 void Builder::accessChainStore(Id rvalue)
1865 {
1866     assert(accessChain.isRValue == false);
1867
1868     transferAccessChainSwizzle(true);
1869     Id base = collapseAccessChain();
1870
1871     if (accessChain.swizzle.size() && accessChain.component != NoResult)
1872         MissingFunctionality("simultaneous l-value swizzle and dynamic component selection");
1873
1874     // If swizzle still exists, it is out-of-order or not full, we must load the target vector,
1875     // extract and insert elements to perform writeMask and/or swizzle.
1876     Id source = NoResult;
1877     if (accessChain.swizzle.size()) {
1878         Id tempBaseId = createLoad(base);
1879         source = createLvalueSwizzle(getTypeId(tempBaseId), tempBaseId, rvalue, accessChain.swizzle);
1880     }
1881
1882     // dynamic component selection
1883     if (accessChain.component != NoResult) {
1884         Id tempBaseId = (source == NoResult) ? createLoad(base) : source;
1885         source = createVectorInsertDynamic(tempBaseId, getTypeId(tempBaseId), rvalue, accessChain.component);
1886     }
1887
1888     if (source == NoResult)
1889         source = rvalue;
1890
1891     createStore(source, base);
1892 }
1893
1894 // Comments in header
1895 Id Builder::accessChainLoad(Id resultType)
1896 {
1897     Id id;
1898
1899     if (accessChain.isRValue) {
1900         // transfer access chain, but keep it static, so we can stay in registers
1901         transferAccessChainSwizzle(false);
1902         if (accessChain.indexChain.size() > 0) {
1903             Id swizzleBase = accessChain.preSwizzleBaseType != NoType ? accessChain.preSwizzleBaseType : resultType;
1904         
1905             // if all the accesses are constants, we can use OpCompositeExtract
1906             std::vector<unsigned> indexes;
1907             bool constant = true;
1908             for (int i = 0; i < (int)accessChain.indexChain.size(); ++i) {
1909                 if (isConstantScalar(accessChain.indexChain[i]))
1910                     indexes.push_back(getConstantScalar(accessChain.indexChain[i]));
1911                 else {
1912                     constant = false;
1913                     break;
1914                 }
1915             }
1916
1917             if (constant)
1918                 id = createCompositeExtract(accessChain.base, swizzleBase, indexes);
1919             else {
1920                 // make a new function variable for this r-value
1921                 Id lValue = createVariable(StorageClassFunction, getTypeId(accessChain.base), "indexable");
1922
1923                 // store into it
1924                 createStore(accessChain.base, lValue);
1925
1926                 // move base to the new variable
1927                 accessChain.base = lValue;
1928                 accessChain.isRValue = false;
1929
1930                 // load through the access chain
1931                 id = createLoad(collapseAccessChain());
1932             }
1933         } else
1934             id = accessChain.base;
1935     } else {
1936         transferAccessChainSwizzle(true);
1937         // load through the access chain
1938         id = createLoad(collapseAccessChain());
1939     }
1940
1941     // Done, unless there are swizzles to do
1942     if (accessChain.swizzle.size() == 0 && accessChain.component == NoResult)
1943         return id;
1944
1945     // Do remaining swizzling
1946     // First, static swizzling
1947     if (accessChain.swizzle.size()) {
1948         // static swizzle
1949         Id swizzledType = getScalarTypeId(getTypeId(id));
1950         if (accessChain.swizzle.size() > 1)
1951             swizzledType = makeVectorType(swizzledType, (int)accessChain.swizzle.size());
1952         id = createRvalueSwizzle(swizzledType, id, accessChain.swizzle);
1953     }
1954
1955     // dynamic single-component selection
1956     if (accessChain.component != NoResult)
1957         id = createVectorExtractDynamic(id, resultType, accessChain.component);
1958
1959     return id;
1960 }
1961
1962 Id Builder::accessChainGetLValue()
1963 {
1964     assert(accessChain.isRValue == false);
1965
1966     transferAccessChainSwizzle(true);
1967     Id lvalue = collapseAccessChain();
1968
1969     // If swizzle exists, it is out-of-order or not full, we must load the target vector,
1970     // extract and insert elements to perform writeMask and/or swizzle.  This does not
1971     // go with getting a direct l-value pointer.
1972     assert(accessChain.swizzle.size() == 0);
1973     assert(accessChain.component == NoResult);
1974
1975     return lvalue;
1976 }
1977
1978 void Builder::dump(std::vector<unsigned int>& out) const
1979 {
1980     // Header, before first instructions:
1981     out.push_back(MagicNumber);
1982     out.push_back(Version);
1983     out.push_back(builderNumber);
1984     out.push_back(uniqueId + 1);
1985     out.push_back(0);
1986
1987     // Capabilities
1988     for (auto cap : capabilities) {
1989         Instruction capInst(0, 0, OpCapability);
1990         capInst.addImmediateOperand(cap);
1991         capInst.dump(out);
1992     }
1993
1994     // TBD: OpExtension ...
1995
1996     dumpInstructions(out, imports);
1997     Instruction memInst(0, 0, OpMemoryModel);
1998     memInst.addImmediateOperand(addressModel);
1999     memInst.addImmediateOperand(memoryModel);
2000     memInst.dump(out);
2001
2002     // Instructions saved up while building:
2003     dumpInstructions(out, entryPoints);
2004     dumpInstructions(out, executionModes);
2005
2006     // Debug instructions
2007     if (source != SourceLanguageUnknown) {
2008         Instruction sourceInst(0, 0, OpSource);
2009         sourceInst.addImmediateOperand(source);
2010         sourceInst.addImmediateOperand(sourceVersion);
2011         sourceInst.dump(out);
2012     }
2013     for (int e = 0; e < (int)extensions.size(); ++e) {
2014         Instruction extInst(0, 0, OpSourceExtension);
2015         extInst.addStringOperand(extensions[e]);
2016         extInst.dump(out);
2017     }
2018     dumpInstructions(out, names);
2019     dumpInstructions(out, lines);
2020
2021     // Annotation instructions
2022     dumpInstructions(out, decorations);
2023
2024     dumpInstructions(out, constantsTypesGlobals);
2025     dumpInstructions(out, externals);
2026
2027     // The functions
2028     module.dump(out);
2029 }
2030
2031 //
2032 // Protected methods.
2033 //
2034
2035 // Turn the described access chain in 'accessChain' into an instruction
2036 // computing its address.  This *cannot* include complex swizzles, which must
2037 // be handled after this is called, but it does include swizzles that select
2038 // an individual element, as a single address of a scalar type can be
2039 // computed by an OpAccessChain instruction.
2040 Id Builder::collapseAccessChain()
2041 {
2042     assert(accessChain.isRValue == false);
2043
2044     if (accessChain.indexChain.size() > 0) {
2045         if (accessChain.instr == 0) {
2046             StorageClass storageClass = (StorageClass)module.getStorageClass(getTypeId(accessChain.base));
2047             accessChain.instr = createAccessChain(storageClass, accessChain.base, accessChain.indexChain);
2048         }
2049
2050         return accessChain.instr;
2051     } else
2052         return accessChain.base;
2053
2054     // note that non-trivial swizzling is left pending...
2055 }
2056
2057 // clear out swizzle if it is redundant, that is reselecting the same components
2058 // that would be present without the swizzle.
2059 void Builder::simplifyAccessChainSwizzle()
2060 {
2061     // If the swizzle has fewer components than the vector, it is subsetting, and must stay
2062     // to preserve that fact.
2063     if (getNumTypeComponents(accessChain.preSwizzleBaseType) > (int)accessChain.swizzle.size())
2064         return;
2065
2066     // if components are out of order, it is a swizzle
2067     for (unsigned int i = 0; i < accessChain.swizzle.size(); ++i) {
2068         if (i != accessChain.swizzle[i])
2069             return;
2070     }
2071
2072     // otherwise, there is no need to track this swizzle
2073     accessChain.swizzle.clear();
2074     if (accessChain.component == NoResult)
2075         accessChain.preSwizzleBaseType = NoType;
2076 }
2077
2078 // To the extent any swizzling can become part of the chain
2079 // of accesses instead of a post operation, make it so.
2080 // If 'dynamic' is true, include transfering a non-static component index,
2081 // otherwise, only transfer static indexes.
2082 //
2083 // Also, Boolean vectors are likely to be special.  While
2084 // for external storage, they should only be integer types,
2085 // function-local bool vectors could use sub-word indexing,
2086 // so keep that as a separate Insert/Extract on a loaded vector.
2087 void Builder::transferAccessChainSwizzle(bool dynamic)
2088 {
2089     // too complex?
2090     if (accessChain.swizzle.size() > 1)
2091         return;
2092
2093     // non existent?
2094     if (accessChain.swizzle.size() == 0 && accessChain.component == NoResult)
2095         return;
2096
2097     // single component...
2098
2099     // skip doing it for Boolean vectors
2100     if (isBoolType(getContainedTypeId(accessChain.preSwizzleBaseType)))
2101         return;
2102
2103     if (accessChain.swizzle.size() == 1) {
2104         // handle static component
2105         accessChain.indexChain.push_back(makeUintConstant(accessChain.swizzle.front()));
2106         accessChain.swizzle.clear();
2107         // note, the only valid remaining dynamic access would be to this one
2108         // component, so don't bother even looking at accessChain.component
2109         accessChain.preSwizzleBaseType = NoType;
2110         accessChain.component = NoResult;
2111     } else if (dynamic && accessChain.component != NoResult) {
2112         // handle dynamic component
2113         accessChain.indexChain.push_back(accessChain.component);
2114         accessChain.preSwizzleBaseType = NoType;
2115         accessChain.component = NoResult;
2116     }
2117 }
2118
2119 // Utility method for creating a new block and setting the insert point to
2120 // be in it. This is useful for flow-control operations that need a "dummy"
2121 // block proceeding them (e.g. instructions after a discard, etc).
2122 void Builder::createAndSetNoPredecessorBlock(const char* /*name*/)
2123 {
2124     Block* block = new Block(getUniqueId(), buildPoint->getParent());
2125     block->setUnreachable();
2126     buildPoint->getParent().addBlock(block);
2127     setBuildPoint(block);
2128
2129     //if (name)
2130     //    addName(block->getId(), name);
2131 }
2132
2133 // Comments in header
2134 void Builder::createBranch(Block* block)
2135 {
2136     Instruction* branch = new Instruction(OpBranch);
2137     branch->addIdOperand(block->getId());
2138     buildPoint->addInstruction(std::unique_ptr<Instruction>(branch));
2139     block->addPredecessor(buildPoint);
2140 }
2141
2142 void Builder::createSelectionMerge(Block* mergeBlock, unsigned int control)
2143 {
2144     Instruction* merge = new Instruction(OpSelectionMerge);
2145     merge->addIdOperand(mergeBlock->getId());
2146     merge->addImmediateOperand(control);
2147     buildPoint->addInstruction(std::unique_ptr<Instruction>(merge));
2148 }
2149
2150 void Builder::createLoopMerge(Block* mergeBlock, Block* continueBlock, unsigned int control)
2151 {
2152     Instruction* merge = new Instruction(OpLoopMerge);
2153     merge->addIdOperand(mergeBlock->getId());
2154     merge->addIdOperand(continueBlock->getId());
2155     merge->addImmediateOperand(control);
2156     buildPoint->addInstruction(std::unique_ptr<Instruction>(merge));
2157 }
2158
2159 void Builder::createConditionalBranch(Id condition, Block* thenBlock, Block* elseBlock)
2160 {
2161     Instruction* branch = new Instruction(OpBranchConditional);
2162     branch->addIdOperand(condition);
2163     branch->addIdOperand(thenBlock->getId());
2164     branch->addIdOperand(elseBlock->getId());
2165     buildPoint->addInstruction(std::unique_ptr<Instruction>(branch));
2166     thenBlock->addPredecessor(buildPoint);
2167     elseBlock->addPredecessor(buildPoint);
2168 }
2169
2170 void Builder::dumpInstructions(std::vector<unsigned int>& out, const std::vector<std::unique_ptr<Instruction> >& instructions) const
2171 {
2172     for (int i = 0; i < (int)instructions.size(); ++i) {
2173         instructions[i]->dump(out);
2174     }
2175 }
2176
2177 void TbdFunctionality(const char* tbd)
2178 {
2179     static std::unordered_set<const char*> issued;
2180
2181     if (issued.find(tbd) == issued.end()) {
2182         printf("TBD functionality: %s\n", tbd);
2183         issued.insert(tbd);
2184     }
2185 }
2186
2187 void MissingFunctionality(const char* fun)
2188 {
2189     printf("Missing functionality: %s\n", fun);
2190 }
2191
2192 }; // end spv namespace