9e9a134f750e116b4b0a04dab3348b230f833f1e
[platform/upstream/VK-GL-CTS.git] / external / vulkancts / modules / vulkan / spirv_assembly / vktSpvAsmInstructionTests.cpp
1 /*-------------------------------------------------------------------------
2  * Vulkan Conformance Tests
3  * ------------------------
4  *
5  * Copyright (c) 2015 Google Inc.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  *//*!
20  * \file
21  * \brief SPIR-V Assembly Tests for Instructions (special opcode/operand)
22  *//*--------------------------------------------------------------------*/
23
24 #include "vktSpvAsmInstructionTests.hpp"
25
26 #include "tcuCommandLine.hpp"
27 #include "tcuFormatUtil.hpp"
28 #include "tcuFloat.hpp"
29 #include "tcuRGBA.hpp"
30 #include "tcuStringTemplate.hpp"
31 #include "tcuTestLog.hpp"
32 #include "tcuVectorUtil.hpp"
33
34 #include "vkDefs.hpp"
35 #include "vkDeviceUtil.hpp"
36 #include "vkMemUtil.hpp"
37 #include "vkPlatform.hpp"
38 #include "vkPrograms.hpp"
39 #include "vkQueryUtil.hpp"
40 #include "vkRef.hpp"
41 #include "vkRefUtil.hpp"
42 #include "vkStrUtil.hpp"
43 #include "vkTypeUtil.hpp"
44
45 #include "deRandom.hpp"
46 #include "deStringUtil.hpp"
47 #include "deUniquePtr.hpp"
48 #include "tcuStringTemplate.hpp"
49
50 #include "vktSpvAsmComputeShaderCase.hpp"
51 #include "vktSpvAsmComputeShaderTestUtil.hpp"
52 #include "vktTestCaseUtil.hpp"
53
54 #include <cmath>
55 #include <limits>
56 #include <map>
57 #include <string>
58 #include <sstream>
59
60 namespace vkt
61 {
62 namespace SpirVAssembly
63 {
64
65 namespace
66 {
67
68 using namespace vk;
69 using std::map;
70 using std::string;
71 using std::vector;
72 using tcu::IVec3;
73 using tcu::IVec4;
74 using tcu::RGBA;
75 using tcu::TestLog;
76 using tcu::TestStatus;
77 using tcu::Vec4;
78 using de::UniquePtr;
79 using tcu::StringTemplate;
80 using tcu::Vec4;
81
82 typedef Unique<VkShaderModule>                  ModuleHandleUp;
83 typedef de::SharedPtr<ModuleHandleUp>   ModuleHandleSp;
84
85 template<typename T>    T                       randomScalar    (de::Random& rnd, T minValue, T maxValue);
86 template<> inline               float           randomScalar    (de::Random& rnd, float minValue, float maxValue)               { return rnd.getFloat(minValue, maxValue);      }
87 template<> inline               deInt32         randomScalar    (de::Random& rnd, deInt32 minValue, deInt32 maxValue)   { return rnd.getInt(minValue, maxValue);        }
88
89 template<typename T>
90 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, int offset = 0)
91 {
92         T* const typedPtr = (T*)dst;
93         for (int ndx = 0; ndx < numValues; ndx++)
94                 typedPtr[offset + ndx] = randomScalar<T>(rnd, minValue, maxValue);
95 }
96
97 static void floorAll (vector<float>& values)
98 {
99         for (size_t i = 0; i < values.size(); i++)
100                 values[i] = deFloatFloor(values[i]);
101 }
102
103 static void floorAll (vector<Vec4>& values)
104 {
105         for (size_t i = 0; i < values.size(); i++)
106                 values[i] = floor(values[i]);
107 }
108
109 struct CaseParameter
110 {
111         const char*             name;
112         string                  param;
113
114         CaseParameter   (const char* case_, const string& param_) : name(case_), param(param_) {}
115 };
116
117 // Assembly code used for testing OpNop, OpConstant{Null|Composite}, Op[No]Line, OpSource[Continued], OpSourceExtension, OpUndef is based on GLSL source code:
118 //
119 // #version 430
120 //
121 // layout(std140, set = 0, binding = 0) readonly buffer Input {
122 //   float elements[];
123 // } input_data;
124 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
125 //   float elements[];
126 // } output_data;
127 //
128 // layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
129 //
130 // void main() {
131 //   uint x = gl_GlobalInvocationID.x;
132 //   output_data.elements[x] = -input_data.elements[x];
133 // }
134
135 static const char* const s_ShaderPreamble =
136         "OpCapability Shader\n"
137         "OpMemoryModel Logical GLSL450\n"
138         "OpEntryPoint GLCompute %main \"main\" %id\n"
139         "OpExecutionMode %main LocalSize 1 1 1\n";
140
141 static const char* const s_CommonTypes =
142         "%bool      = OpTypeBool\n"
143         "%void      = OpTypeVoid\n"
144         "%voidf     = OpTypeFunction %void\n"
145         "%u32       = OpTypeInt 32 0\n"
146         "%i32       = OpTypeInt 32 1\n"
147         "%f32       = OpTypeFloat 32\n"
148         "%uvec3     = OpTypeVector %u32 3\n"
149         "%fvec3     = OpTypeVector %f32 3\n"
150         "%uvec3ptr  = OpTypePointer Input %uvec3\n"
151         "%i32ptr    = OpTypePointer Uniform %i32\n"
152         "%f32ptr    = OpTypePointer Uniform %f32\n"
153         "%i32arr    = OpTypeRuntimeArray %i32\n"
154         "%f32arr    = OpTypeRuntimeArray %f32\n";
155
156 // Declares two uniform variables (indata, outdata) of type "struct { float[] }". Depends on type "f32arr" (for "float[]").
157 static const char* const s_InputOutputBuffer =
158         "%buf     = OpTypeStruct %f32arr\n"
159         "%bufptr  = OpTypePointer Uniform %buf\n"
160         "%indata    = OpVariable %bufptr Uniform\n"
161         "%outdata   = OpVariable %bufptr Uniform\n";
162
163 // Declares buffer type and layout for uniform variables indata and outdata. Both of them are SSBO bounded to descriptor set 0.
164 // indata is at binding point 0, while outdata is at 1.
165 static const char* const s_InputOutputBufferTraits =
166         "OpDecorate %buf BufferBlock\n"
167         "OpDecorate %indata DescriptorSet 0\n"
168         "OpDecorate %indata Binding 0\n"
169         "OpDecorate %outdata DescriptorSet 0\n"
170         "OpDecorate %outdata Binding 1\n"
171         "OpDecorate %f32arr ArrayStride 4\n"
172         "OpMemberDecorate %buf 0 Offset 0\n";
173
174 tcu::TestCaseGroup* createOpNopGroup (tcu::TestContext& testCtx)
175 {
176         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnop", "Test the OpNop instruction"));
177         ComputeShaderSpec                               spec;
178         de::Random                                              rnd                             (deStringHash(group->getName()));
179         const int                                               numElements             = 100;
180         vector<float>                                   positiveFloats  (numElements, 0);
181         vector<float>                                   negativeFloats  (numElements, 0);
182
183         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
184
185         for (size_t ndx = 0; ndx < numElements; ++ndx)
186                 negativeFloats[ndx] = -positiveFloats[ndx];
187
188         spec.assembly =
189                 string(s_ShaderPreamble) +
190
191                 "OpSource GLSL 430\n"
192                 "OpName %main           \"main\"\n"
193                 "OpName %id             \"gl_GlobalInvocationID\"\n"
194
195                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
196
197                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes)
198
199                 + string(s_InputOutputBuffer) +
200
201                 "%id        = OpVariable %uvec3ptr Input\n"
202                 "%zero      = OpConstant %i32 0\n"
203
204                 "%main      = OpFunction %void None %voidf\n"
205                 "%label     = OpLabel\n"
206                 "%idval     = OpLoad %uvec3 %id\n"
207                 "%x         = OpCompositeExtract %u32 %idval 0\n"
208
209                 "             OpNop\n" // Inside a function body
210
211                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
212                 "%inval     = OpLoad %f32 %inloc\n"
213                 "%neg       = OpFNegate %f32 %inval\n"
214                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
215                 "             OpStore %outloc %neg\n"
216                 "             OpReturn\n"
217                 "             OpFunctionEnd\n";
218         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
219         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
220         spec.numWorkGroups = IVec3(numElements, 1, 1);
221
222         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNop appearing at different places", spec));
223
224         return group.release();
225 }
226
227 bool compareFUnord (const std::vector<BufferSp>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog& log)
228 {
229         if (outputAllocs.size() != 1)
230                 return false;
231
232         const BufferSp& expectedOutput                  = expectedOutputs[0];
233         const deInt32*  expectedOutputAsInt             = static_cast<const deInt32*>(expectedOutputs[0]->data());
234         const deInt32*  outputAsInt                             = static_cast<const deInt32*>(outputAllocs[0]->getHostPtr());
235         const float*    input1AsFloat                   = static_cast<const float*>(inputs[0]->data());
236         const float*    input2AsFloat                   = static_cast<const float*>(inputs[1]->data());
237         bool returnValue                                                = true;
238
239         for (size_t idx = 0; idx < expectedOutput->getNumBytes() / sizeof(deInt32); ++idx)
240         {
241                 if (outputAsInt[idx] != expectedOutputAsInt[idx])
242                 {
243                         log << TestLog::Message << "ERROR: Sub-case failed. inputs: " << input1AsFloat[idx] << "," << input2AsFloat[idx] << " output: " << outputAsInt[idx]<< " expected output: " << expectedOutputAsInt[idx] << TestLog::EndMessage;
244                         returnValue = false;
245                 }
246         }
247         return returnValue;
248 }
249
250 typedef VkBool32 (*compareFuncType) (float, float);
251
252 struct OpFUnordCase
253 {
254         const char*             name;
255         const char*             opCode;
256         compareFuncType compareFunc;
257
258                                         OpFUnordCase                    (const char* _name, const char* _opCode, compareFuncType _compareFunc)
259                                                 : name                          (_name)
260                                                 , opCode                        (_opCode)
261                                                 , compareFunc           (_compareFunc) {}
262 };
263
264 #define ADD_OPFUNORD_CASE(NAME, OPCODE, OPERATOR) \
265 do { \
266     struct compare_##NAME { static VkBool32 compare(float x, float y) { return (x OPERATOR y) ? VK_TRUE : VK_FALSE; } }; \
267     cases.push_back(OpFUnordCase(#NAME, OPCODE, compare_##NAME::compare)); \
268 } while (deGetFalse())
269
270 tcu::TestCaseGroup* createOpFUnordGroup (tcu::TestContext& testCtx)
271 {
272         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfunord", "Test the OpFUnord* opcodes"));
273         de::Random                                              rnd                             (deStringHash(group->getName()));
274         const int                                               numElements             = 100;
275         vector<OpFUnordCase>                    cases;
276
277         const StringTemplate                    shaderTemplate  (
278
279                 string(s_ShaderPreamble) +
280
281                 "OpSource GLSL 430\n"
282                 "OpName %main           \"main\"\n"
283                 "OpName %id             \"gl_GlobalInvocationID\"\n"
284
285                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
286
287                 "OpDecorate %buf BufferBlock\n"
288                 "OpDecorate %buf2 BufferBlock\n"
289                 "OpDecorate %indata1 DescriptorSet 0\n"
290                 "OpDecorate %indata1 Binding 0\n"
291                 "OpDecorate %indata2 DescriptorSet 0\n"
292                 "OpDecorate %indata2 Binding 1\n"
293                 "OpDecorate %outdata DescriptorSet 0\n"
294                 "OpDecorate %outdata Binding 2\n"
295                 "OpDecorate %f32arr ArrayStride 4\n"
296                 "OpDecorate %i32arr ArrayStride 4\n"
297                 "OpMemberDecorate %buf 0 Offset 0\n"
298                 "OpMemberDecorate %buf2 0 Offset 0\n"
299
300                 + string(s_CommonTypes) +
301
302                 "%buf        = OpTypeStruct %f32arr\n"
303                 "%bufptr     = OpTypePointer Uniform %buf\n"
304                 "%indata1    = OpVariable %bufptr Uniform\n"
305                 "%indata2    = OpVariable %bufptr Uniform\n"
306
307                 "%buf2       = OpTypeStruct %i32arr\n"
308                 "%buf2ptr    = OpTypePointer Uniform %buf2\n"
309                 "%outdata    = OpVariable %buf2ptr Uniform\n"
310
311                 "%id        = OpVariable %uvec3ptr Input\n"
312                 "%zero      = OpConstant %i32 0\n"
313                 "%consti1   = OpConstant %i32 1\n"
314                 "%constf1   = OpConstant %f32 1.0\n"
315
316                 "%main      = OpFunction %void None %voidf\n"
317                 "%label     = OpLabel\n"
318                 "%idval     = OpLoad %uvec3 %id\n"
319                 "%x         = OpCompositeExtract %u32 %idval 0\n"
320
321                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
322                 "%inval1    = OpLoad %f32 %inloc1\n"
323                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
324                 "%inval2    = OpLoad %f32 %inloc2\n"
325                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
326
327                 "%result    = ${OPCODE} %bool %inval1 %inval2\n"
328                 "%int_res   = OpSelect %i32 %result %consti1 %zero\n"
329                 "             OpStore %outloc %int_res\n"
330
331                 "             OpReturn\n"
332                 "             OpFunctionEnd\n");
333
334         ADD_OPFUNORD_CASE(equal, "OpFUnordEqual", ==);
335         ADD_OPFUNORD_CASE(less, "OpFUnordLessThan", <);
336         ADD_OPFUNORD_CASE(lessequal, "OpFUnordLessThanEqual", <=);
337         ADD_OPFUNORD_CASE(greater, "OpFUnordGreaterThan", >);
338         ADD_OPFUNORD_CASE(greaterequal, "OpFUnordGreaterThanEqual", >=);
339         ADD_OPFUNORD_CASE(notequal, "OpFUnordNotEqual", !=);
340
341         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
342         {
343                 map<string, string>                     specializations;
344                 ComputeShaderSpec                       spec;
345                 const float                                     NaN                             = std::numeric_limits<float>::quiet_NaN();
346                 vector<float>                           inputFloats1    (numElements, 0);
347                 vector<float>                           inputFloats2    (numElements, 0);
348                 vector<deInt32>                         expectedInts    (numElements, 0);
349
350                 specializations["OPCODE"]       = cases[caseNdx].opCode;
351                 spec.assembly                           = shaderTemplate.specialize(specializations);
352
353                 fillRandomScalars(rnd, 1.f, 100.f, &inputFloats1[0], numElements);
354                 for (size_t ndx = 0; ndx < numElements; ++ndx)
355                 {
356                         switch (ndx % 6)
357                         {
358                                 case 0:         inputFloats2[ndx] = inputFloats1[ndx] + 1.0f; break;
359                                 case 1:         inputFloats2[ndx] = inputFloats1[ndx] - 1.0f; break;
360                                 case 2:         inputFloats2[ndx] = inputFloats1[ndx]; break;
361                                 case 3:         inputFloats2[ndx] = NaN; break;
362                                 case 4:         inputFloats2[ndx] = inputFloats1[ndx];  inputFloats1[ndx] = NaN; break;
363                                 case 5:         inputFloats2[ndx] = NaN;                                inputFloats1[ndx] = NaN; break;
364                         }
365                         expectedInts[ndx] = tcu::Float32(inputFloats1[ndx]).isNaN() || tcu::Float32(inputFloats2[ndx]).isNaN() || cases[caseNdx].compareFunc(inputFloats1[ndx], inputFloats2[ndx]);
366                 }
367
368                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
369                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
370                 spec.outputs.push_back(BufferSp(new Int32Buffer(expectedInts)));
371                 spec.numWorkGroups = IVec3(numElements, 1, 1);
372                 spec.verifyIO = &compareFUnord;
373                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
374         }
375
376         return group.release();
377 }
378
379 struct OpAtomicCase
380 {
381         const char*             name;
382         const char*             assembly;
383         void                    (*calculateExpected)(deInt32&, deInt32);
384         deInt32                 numOutputElements;
385
386                                         OpAtomicCase                    (const char* _name, const char* _assembly, void (*_calculateExpected)(deInt32&, deInt32), deInt32 _numOutputElements)
387                                                 : name                          (_name)
388                                                 , assembly                      (_assembly)
389                                                 , calculateExpected     (_calculateExpected)
390                                                 , numOutputElements (_numOutputElements) {}
391 };
392
393 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx)
394 {
395         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opatomic", "Test the OpAtomic* opcodes"));
396         de::Random                                              rnd                             (deStringHash(group->getName()));
397         const int                                               numElements             = 1000000;
398         vector<OpAtomicCase>                    cases;
399
400         const StringTemplate                    shaderTemplate  (
401
402                 string(s_ShaderPreamble) +
403
404                 "OpSource GLSL 430\n"
405                 "OpName %main           \"main\"\n"
406                 "OpName %id             \"gl_GlobalInvocationID\"\n"
407
408                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
409
410                 "OpDecorate %buf BufferBlock\n"
411                 "OpDecorate %indata DescriptorSet 0\n"
412                 "OpDecorate %indata Binding 0\n"
413                 "OpDecorate %i32arr ArrayStride 4\n"
414                 "OpMemberDecorate %buf 0 Offset 0\n"
415
416                 "OpDecorate %sumbuf BufferBlock\n"
417                 "OpDecorate %sum DescriptorSet 0\n"
418                 "OpDecorate %sum Binding 1\n"
419                 "OpMemberDecorate %sumbuf 0 Coherent\n"
420                 "OpMemberDecorate %sumbuf 0 Offset 0\n"
421
422                 + string(s_CommonTypes) +
423
424                 "%buf       = OpTypeStruct %i32arr\n"
425                 "%bufptr    = OpTypePointer Uniform %buf\n"
426                 "%indata    = OpVariable %bufptr Uniform\n"
427
428                 "%sumbuf    = OpTypeStruct %i32arr\n"
429                 "%sumbufptr = OpTypePointer Uniform %sumbuf\n"
430                 "%sum       = OpVariable %sumbufptr Uniform\n"
431
432                 "%id        = OpVariable %uvec3ptr Input\n"
433                 "%minusone  = OpConstant %i32 -1\n"
434                 "%zero      = OpConstant %i32 0\n"
435                 "%one       = OpConstant %u32 1\n"
436                 "%two       = OpConstant %i32 2\n"
437
438                 "%main      = OpFunction %void None %voidf\n"
439                 "%label     = OpLabel\n"
440                 "%idval     = OpLoad %uvec3 %id\n"
441                 "%x         = OpCompositeExtract %u32 %idval 0\n"
442
443                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
444                 "%inval     = OpLoad %i32 %inloc\n"
445
446                 "%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
447                 "${INSTRUCTION}"
448
449                 "             OpReturn\n"
450                 "             OpFunctionEnd\n");
451
452         #define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, CALCULATE_EXPECTED, NUM_OUTPUT_ELEMENTS) \
453         do { \
454                 DE_STATIC_ASSERT(NUM_OUTPUT_ELEMENTS == 1 || NUM_OUTPUT_ELEMENTS == numElements); \
455                 struct calculateExpected_##NAME { static void calculateExpected(deInt32& expected, deInt32 input) CALCULATE_EXPECTED }; \
456                 cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, calculateExpected_##NAME::calculateExpected, NUM_OUTPUT_ELEMENTS)); \
457         } while (deGetFalse())
458         #define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, CALCULATE_EXPECTED) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, CALCULATE_EXPECTED, 1)
459         #define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, CALCULATE_EXPECTED) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, CALCULATE_EXPECTED, numElements)
460
461         ADD_OPATOMIC_CASE_1(iadd,       "%unused    = OpAtomicIAdd %i32 %outloc %one %zero %inval\n", { expected += input; } );
462         ADD_OPATOMIC_CASE_1(isub,       "%unused    = OpAtomicISub %i32 %outloc %one %zero %inval\n", { expected -= input; } );
463         ADD_OPATOMIC_CASE_1(iinc,       "%unused    = OpAtomicIIncrement %i32 %outloc %one %zero\n",  { ++expected; (void)input;} );
464         ADD_OPATOMIC_CASE_1(idec,       "%unused    = OpAtomicIDecrement %i32 %outloc %one %zero\n",  { --expected; (void)input;} );
465         ADD_OPATOMIC_CASE_N(load,       "%inval2    = OpAtomicLoad %i32 %inloc %zero %zero\n"
466                                                                 "             OpStore %outloc %inval2\n",  { expected = input;} );
467         ADD_OPATOMIC_CASE_N(store,      "             OpAtomicStore %outloc %zero %zero %inval\n",  { expected = input;} );
468         ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
469                                                                 "             OpStore %outloc %even\n"
470                                                                 "%unused    = OpAtomicCompareExchange %i32 %outloc %one %zero %zero %minusone %zero\n",  { expected = (input % 2) == 0 ? -1 : 1;} );
471
472         #undef ADD_OPATOMIC_CASE
473         #undef ADD_OPATOMIC_CASE_1
474         #undef ADD_OPATOMIC_CASE_N
475
476         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
477         {
478                 map<string, string>                     specializations;
479                 ComputeShaderSpec                       spec;
480                 vector<deInt32>                         inputInts               (numElements, 0);
481                 vector<deInt32>                         expected                (cases[caseNdx].numOutputElements, -1);
482
483                 specializations["INDEX"]                = (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
484                 specializations["INSTRUCTION"]  = cases[caseNdx].assembly;
485                 spec.assembly                                   = shaderTemplate.specialize(specializations);
486
487                 fillRandomScalars(rnd, 1, 100, &inputInts[0], numElements);
488                 for (size_t ndx = 0; ndx < numElements; ++ndx)
489                 {
490                         cases[caseNdx].calculateExpected((cases[caseNdx].numOutputElements == 1) ? expected[0] : expected[ndx], inputInts[ndx]);
491                 }
492
493                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
494                 spec.outputs.push_back(BufferSp(new Int32Buffer(expected)));
495                 spec.numWorkGroups = IVec3(numElements, 1, 1);
496                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
497         }
498
499         return group.release();
500 }
501
502 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
503 {
504         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
505         ComputeShaderSpec                               spec;
506         de::Random                                              rnd                             (deStringHash(group->getName()));
507         const int                                               numElements             = 100;
508         vector<float>                                   positiveFloats  (numElements, 0);
509         vector<float>                                   negativeFloats  (numElements, 0);
510
511         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
512
513         for (size_t ndx = 0; ndx < numElements; ++ndx)
514                 negativeFloats[ndx] = -positiveFloats[ndx];
515
516         spec.assembly =
517                 string(s_ShaderPreamble) +
518
519                 "%fname1 = OpString \"negateInputs.comp\"\n"
520                 "%fname2 = OpString \"negateInputs\"\n"
521
522                 "OpSource GLSL 430\n"
523                 "OpName %main           \"main\"\n"
524                 "OpName %id             \"gl_GlobalInvocationID\"\n"
525
526                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
527
528                 + string(s_InputOutputBufferTraits) +
529
530                 "OpLine %fname1 0 0\n" // At the earliest possible position
531
532                 + string(s_CommonTypes) + string(s_InputOutputBuffer) +
533
534                 "OpLine %fname1 0 1\n" // Multiple OpLines in sequence
535                 "OpLine %fname2 1 0\n" // Different filenames
536                 "OpLine %fname1 1000 100000\n"
537
538                 "%id        = OpVariable %uvec3ptr Input\n"
539                 "%zero      = OpConstant %i32 0\n"
540
541                 "OpLine %fname1 1 1\n" // Before a function
542
543                 "%main      = OpFunction %void None %voidf\n"
544                 "%label     = OpLabel\n"
545
546                 "OpLine %fname1 1 1\n" // In a function
547
548                 "%idval     = OpLoad %uvec3 %id\n"
549                 "%x         = OpCompositeExtract %u32 %idval 0\n"
550                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
551                 "%inval     = OpLoad %f32 %inloc\n"
552                 "%neg       = OpFNegate %f32 %inval\n"
553                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
554                 "             OpStore %outloc %neg\n"
555                 "             OpReturn\n"
556                 "             OpFunctionEnd\n";
557         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
558         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
559         spec.numWorkGroups = IVec3(numElements, 1, 1);
560
561         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
562
563         return group.release();
564 }
565
566 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
567 {
568         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
569         ComputeShaderSpec                               spec;
570         de::Random                                              rnd                             (deStringHash(group->getName()));
571         const int                                               numElements             = 100;
572         vector<float>                                   positiveFloats  (numElements, 0);
573         vector<float>                                   negativeFloats  (numElements, 0);
574
575         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
576
577         for (size_t ndx = 0; ndx < numElements; ++ndx)
578                 negativeFloats[ndx] = -positiveFloats[ndx];
579
580         spec.assembly =
581                 string(s_ShaderPreamble) +
582
583                 "%fname = OpString \"negateInputs.comp\"\n"
584
585                 "OpSource GLSL 430\n"
586                 "OpName %main           \"main\"\n"
587                 "OpName %id             \"gl_GlobalInvocationID\"\n"
588
589                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
590
591                 + string(s_InputOutputBufferTraits) +
592
593                 "OpNoLine\n" // At the earliest possible position, without preceding OpLine
594
595                 + string(s_CommonTypes) + string(s_InputOutputBuffer) +
596
597                 "OpLine %fname 0 1\n"
598                 "OpNoLine\n" // Immediately following a preceding OpLine
599
600                 "OpLine %fname 1000 1\n"
601
602                 "%id        = OpVariable %uvec3ptr Input\n"
603                 "%zero      = OpConstant %i32 0\n"
604
605                 "OpNoLine\n" // Contents after the previous OpLine
606
607                 "%main      = OpFunction %void None %voidf\n"
608                 "%label     = OpLabel\n"
609                 "%idval     = OpLoad %uvec3 %id\n"
610                 "%x         = OpCompositeExtract %u32 %idval 0\n"
611
612                 "OpNoLine\n" // Multiple OpNoLine
613                 "OpNoLine\n"
614                 "OpNoLine\n"
615
616                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
617                 "%inval     = OpLoad %f32 %inloc\n"
618                 "%neg       = OpFNegate %f32 %inval\n"
619                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
620                 "             OpStore %outloc %neg\n"
621                 "             OpReturn\n"
622                 "             OpFunctionEnd\n";
623         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
624         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
625         spec.numWorkGroups = IVec3(numElements, 1, 1);
626
627         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
628
629         return group.release();
630 }
631
632 // Compare instruction for the contraction compute case.
633 // Returns true if the output is what is expected from the test case.
634 bool compareNoContractCase(const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
635 {
636         if (outputAllocs.size() != 1)
637                 return false;
638
639         // We really just need this for size because we are not comparing the exact values.
640         const BufferSp& expectedOutput  = expectedOutputs[0];
641         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());;
642
643         for(size_t i = 0; i < expectedOutput->getNumBytes() / sizeof(float); ++i) {
644                 if (outputAsFloat[i] != 0.f &&
645                         outputAsFloat[i] != -ldexp(1, -24)) {
646                         return false;
647                 }
648         }
649
650         return true;
651 }
652
653 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
654 {
655         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
656         vector<CaseParameter>                   cases;
657         const int                                               numElements             = 100;
658         vector<float>                                   inputFloats1    (numElements, 0);
659         vector<float>                                   inputFloats2    (numElements, 0);
660         vector<float>                                   outputFloats    (numElements, 0);
661         const StringTemplate                    shaderTemplate  (
662                 string(s_ShaderPreamble) +
663
664                 "OpName %main           \"main\"\n"
665                 "OpName %id             \"gl_GlobalInvocationID\"\n"
666
667                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
668
669                 "${DECORATION}\n"
670
671                 "OpDecorate %buf BufferBlock\n"
672                 "OpDecorate %indata1 DescriptorSet 0\n"
673                 "OpDecorate %indata1 Binding 0\n"
674                 "OpDecorate %indata2 DescriptorSet 0\n"
675                 "OpDecorate %indata2 Binding 1\n"
676                 "OpDecorate %outdata DescriptorSet 0\n"
677                 "OpDecorate %outdata Binding 2\n"
678                 "OpDecorate %f32arr ArrayStride 4\n"
679                 "OpMemberDecorate %buf 0 Offset 0\n"
680
681                 + string(s_CommonTypes) +
682
683                 "%buf        = OpTypeStruct %f32arr\n"
684                 "%bufptr     = OpTypePointer Uniform %buf\n"
685                 "%indata1    = OpVariable %bufptr Uniform\n"
686                 "%indata2    = OpVariable %bufptr Uniform\n"
687                 "%outdata    = OpVariable %bufptr Uniform\n"
688
689                 "%id         = OpVariable %uvec3ptr Input\n"
690                 "%zero       = OpConstant %i32 0\n"
691                 "%c_f_m1     = OpConstant %f32 -1.\n"
692
693                 "%main       = OpFunction %void None %voidf\n"
694                 "%label      = OpLabel\n"
695                 "%idval      = OpLoad %uvec3 %id\n"
696                 "%x          = OpCompositeExtract %u32 %idval 0\n"
697                 "%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
698                 "%inval1     = OpLoad %f32 %inloc1\n"
699                 "%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
700                 "%inval2     = OpLoad %f32 %inloc2\n"
701                 "%mul        = OpFMul %f32 %inval1 %inval2\n"
702                 "%add        = OpFAdd %f32 %mul %c_f_m1\n"
703                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
704                 "              OpStore %outloc %add\n"
705                 "              OpReturn\n"
706                 "              OpFunctionEnd\n");
707
708         cases.push_back(CaseParameter("multiplication", "OpDecorate %mul NoContraction"));
709         cases.push_back(CaseParameter("addition",               "OpDecorate %add NoContraction"));
710         cases.push_back(CaseParameter("both",                   "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
711
712         for (size_t ndx = 0; ndx < numElements; ++ndx)
713         {
714                 inputFloats1[ndx]       = 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
715                 inputFloats2[ndx]       = 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
716                 // Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
717                 // conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
718                 // So the final result will be 0.f or 0x1p-24.
719                 // If the operation is combined into a precise fused multiply-add, then the result would be
720                 // 2^-46 (0xa8800000).
721                 outputFloats[ndx]       = 0.f;
722         }
723
724         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
725         {
726                 map<string, string>             specializations;
727                 ComputeShaderSpec               spec;
728
729                 specializations["DECORATION"] = cases[caseNdx].param;
730                 spec.assembly = shaderTemplate.specialize(specializations);
731                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
732                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
733                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
734                 spec.numWorkGroups = IVec3(numElements, 1, 1);
735                 // Check against the two possible answers based on rounding mode.
736                 spec.verifyIO = &compareNoContractCase;
737
738                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
739         }
740         return group.release();
741 }
742
743 bool compareFRem(const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
744 {
745         if (outputAllocs.size() != 1)
746                 return false;
747
748         const BufferSp& expectedOutput = expectedOutputs[0];
749         const float *expectedOutputAsFloat = static_cast<const float*>(expectedOutput->data());
750         const float* outputAsFloat = static_cast<const float*>(outputAllocs[0]->getHostPtr());;
751
752         for (size_t idx = 0; idx < expectedOutput->getNumBytes() / sizeof(float); ++idx)
753         {
754                 const float f0 = expectedOutputAsFloat[idx];
755                 const float f1 = outputAsFloat[idx];
756                 // \todo relative error needs to be fairly high because FRem may be implemented as
757                 // (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
758                 if (deFloatAbs((f1 - f0) / f0) > 0.02)
759                         return false;
760         }
761
762         return true;
763 }
764
765 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
766 {
767         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
768         ComputeShaderSpec                               spec;
769         de::Random                                              rnd                             (deStringHash(group->getName()));
770         const int                                               numElements             = 200;
771         vector<float>                                   inputFloats1    (numElements, 0);
772         vector<float>                                   inputFloats2    (numElements, 0);
773         vector<float>                                   outputFloats    (numElements, 0);
774
775         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
776         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
777
778         for (size_t ndx = 0; ndx < numElements; ++ndx)
779         {
780                 // Guard against divisors near zero.
781                 if (std::fabs(inputFloats2[ndx]) < 1e-3)
782                         inputFloats2[ndx] = 8.f;
783
784                 // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
785                 outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
786         }
787
788         spec.assembly =
789                 string(s_ShaderPreamble) +
790
791                 "OpName %main           \"main\"\n"
792                 "OpName %id             \"gl_GlobalInvocationID\"\n"
793
794                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
795
796                 "OpDecorate %buf BufferBlock\n"
797                 "OpDecorate %indata1 DescriptorSet 0\n"
798                 "OpDecorate %indata1 Binding 0\n"
799                 "OpDecorate %indata2 DescriptorSet 0\n"
800                 "OpDecorate %indata2 Binding 1\n"
801                 "OpDecorate %outdata DescriptorSet 0\n"
802                 "OpDecorate %outdata Binding 2\n"
803                 "OpDecorate %f32arr ArrayStride 4\n"
804                 "OpMemberDecorate %buf 0 Offset 0\n"
805
806                 + string(s_CommonTypes) +
807
808                 "%buf        = OpTypeStruct %f32arr\n"
809                 "%bufptr     = OpTypePointer Uniform %buf\n"
810                 "%indata1    = OpVariable %bufptr Uniform\n"
811                 "%indata2    = OpVariable %bufptr Uniform\n"
812                 "%outdata    = OpVariable %bufptr Uniform\n"
813
814                 "%id        = OpVariable %uvec3ptr Input\n"
815                 "%zero      = OpConstant %i32 0\n"
816
817                 "%main      = OpFunction %void None %voidf\n"
818                 "%label     = OpLabel\n"
819                 "%idval     = OpLoad %uvec3 %id\n"
820                 "%x         = OpCompositeExtract %u32 %idval 0\n"
821                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
822                 "%inval1    = OpLoad %f32 %inloc1\n"
823                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
824                 "%inval2    = OpLoad %f32 %inloc2\n"
825                 "%rem       = OpFRem %f32 %inval1 %inval2\n"
826                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
827                 "             OpStore %outloc %rem\n"
828                 "             OpReturn\n"
829                 "             OpFunctionEnd\n";
830
831         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
832         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
833         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
834         spec.numWorkGroups = IVec3(numElements, 1, 1);
835         spec.verifyIO = &compareFRem;
836
837         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
838
839         return group.release();
840 }
841
842 // Copy contents in the input buffer to the output buffer.
843 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
844 {
845         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
846         de::Random                                              rnd                             (deStringHash(group->getName()));
847         const int                                               numElements             = 100;
848
849         // The following case adds vec4(0., 0.5, 1.5, 2.5) to each of the elements in the input buffer and writes output to the output buffer.
850         ComputeShaderSpec                               spec1;
851         vector<Vec4>                                    inputFloats1    (numElements);
852         vector<Vec4>                                    outputFloats1   (numElements);
853
854         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
855
856         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
857         floorAll(inputFloats1);
858
859         for (size_t ndx = 0; ndx < numElements; ++ndx)
860                 outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
861
862         spec1.assembly =
863                 string(s_ShaderPreamble) +
864
865                 "OpName %main           \"main\"\n"
866                 "OpName %id             \"gl_GlobalInvocationID\"\n"
867
868                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
869                 "OpDecorate %vec4arr ArrayStride 16\n"
870
871                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) +
872
873                 "%vec4       = OpTypeVector %f32 4\n"
874                 "%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
875                 "%vec4ptr_f  = OpTypePointer Function %vec4\n"
876                 "%vec4arr    = OpTypeRuntimeArray %vec4\n"
877                 "%buf        = OpTypeStruct %vec4arr\n"
878                 "%bufptr     = OpTypePointer Uniform %buf\n"
879                 "%indata     = OpVariable %bufptr Uniform\n"
880                 "%outdata    = OpVariable %bufptr Uniform\n"
881
882                 "%id         = OpVariable %uvec3ptr Input\n"
883                 "%zero       = OpConstant %i32 0\n"
884                 "%c_f_0      = OpConstant %f32 0.\n"
885                 "%c_f_0_5    = OpConstant %f32 0.5\n"
886                 "%c_f_1_5    = OpConstant %f32 1.5\n"
887                 "%c_f_2_5    = OpConstant %f32 2.5\n"
888                 "%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
889
890                 "%main       = OpFunction %void None %voidf\n"
891                 "%label      = OpLabel\n"
892                 "%v_vec4     = OpVariable %vec4ptr_f Function\n"
893                 "%idval      = OpLoad %uvec3 %id\n"
894                 "%x          = OpCompositeExtract %u32 %idval 0\n"
895                 "%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
896                 "%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
897                 "              OpCopyMemory %v_vec4 %inloc\n"
898                 "%v_vec4_val = OpLoad %vec4 %v_vec4\n"
899                 "%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
900                 "              OpStore %outloc %add\n"
901                 "              OpReturn\n"
902                 "              OpFunctionEnd\n";
903
904         spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
905         spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
906         spec1.numWorkGroups = IVec3(numElements, 1, 1);
907
908         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
909
910         // The following case copies a float[100] variable from the input buffer to the output buffer.
911         ComputeShaderSpec                               spec2;
912         vector<float>                                   inputFloats2    (numElements);
913         vector<float>                                   outputFloats2   (numElements);
914
915         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
916
917         for (size_t ndx = 0; ndx < numElements; ++ndx)
918                 outputFloats2[ndx] = inputFloats2[ndx];
919
920         spec2.assembly =
921                 string(s_ShaderPreamble) +
922
923                 "OpName %main           \"main\"\n"
924                 "OpName %id             \"gl_GlobalInvocationID\"\n"
925
926                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
927                 "OpDecorate %f32arr100 ArrayStride 4\n"
928
929                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) +
930
931                 "%hundred        = OpConstant %u32 100\n"
932                 "%f32arr100      = OpTypeArray %f32 %hundred\n"
933                 "%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
934                 "%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
935                 "%buf            = OpTypeStruct %f32arr100\n"
936                 "%bufptr         = OpTypePointer Uniform %buf\n"
937                 "%indata         = OpVariable %bufptr Uniform\n"
938                 "%outdata        = OpVariable %bufptr Uniform\n"
939
940                 "%id             = OpVariable %uvec3ptr Input\n"
941                 "%zero           = OpConstant %i32 0\n"
942
943                 "%main           = OpFunction %void None %voidf\n"
944                 "%label          = OpLabel\n"
945                 "%var            = OpVariable %f32arr100ptr_f Function\n"
946                 "%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
947                 "%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
948                 "                  OpCopyMemory %var %inarr\n"
949                 "                  OpCopyMemory %outarr %var\n"
950                 "                  OpReturn\n"
951                 "                  OpFunctionEnd\n";
952
953         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
954         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
955         spec2.numWorkGroups = IVec3(1, 1, 1);
956
957         group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
958
959         // The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
960         ComputeShaderSpec                               spec3;
961         vector<float>                                   inputFloats3    (16);
962         vector<float>                                   outputFloats3   (16);
963
964         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
965
966         for (size_t ndx = 0; ndx < 16; ++ndx)
967                 outputFloats3[ndx] = inputFloats3[ndx];
968
969         spec3.assembly =
970                 string(s_ShaderPreamble) +
971
972                 "OpName %main           \"main\"\n"
973                 "OpName %id             \"gl_GlobalInvocationID\"\n"
974
975                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
976                 "OpMemberDecorate %buf 0 Offset 0\n"
977                 "OpMemberDecorate %buf 1 Offset 16\n"
978                 "OpMemberDecorate %buf 2 Offset 32\n"
979                 "OpMemberDecorate %buf 3 Offset 48\n"
980
981                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) +
982
983                 "%vec4      = OpTypeVector %f32 4\n"
984                 "%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
985                 "%bufptr    = OpTypePointer Uniform %buf\n"
986                 "%indata    = OpVariable %bufptr Uniform\n"
987                 "%outdata   = OpVariable %bufptr Uniform\n"
988                 "%vec4stptr = OpTypePointer Function %buf\n"
989
990                 "%id        = OpVariable %uvec3ptr Input\n"
991                 "%zero      = OpConstant %i32 0\n"
992
993                 "%main      = OpFunction %void None %voidf\n"
994                 "%label     = OpLabel\n"
995                 "%var       = OpVariable %vec4stptr Function\n"
996                 "             OpCopyMemory %var %indata\n"
997                 "             OpCopyMemory %outdata %var\n"
998                 "             OpReturn\n"
999                 "             OpFunctionEnd\n";
1000
1001         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1002         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
1003         spec3.numWorkGroups = IVec3(1, 1, 1);
1004
1005         group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
1006
1007         // The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
1008         ComputeShaderSpec                               spec4;
1009         vector<float>                                   inputFloats4    (numElements);
1010         vector<float>                                   outputFloats4   (numElements);
1011
1012         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
1013
1014         for (size_t ndx = 0; ndx < numElements; ++ndx)
1015                 outputFloats4[ndx] = -inputFloats4[ndx];
1016
1017         spec4.assembly =
1018                 string(s_ShaderPreamble) +
1019
1020                 "OpName %main           \"main\"\n"
1021                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1022
1023                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1024
1025                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
1026
1027                 "%f32ptr_f  = OpTypePointer Function %f32\n"
1028                 "%id        = OpVariable %uvec3ptr Input\n"
1029                 "%zero      = OpConstant %i32 0\n"
1030
1031                 "%main      = OpFunction %void None %voidf\n"
1032                 "%label     = OpLabel\n"
1033                 "%var       = OpVariable %f32ptr_f Function\n"
1034                 "%idval     = OpLoad %uvec3 %id\n"
1035                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1036                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
1037                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1038                 "             OpCopyMemory %var %inloc\n"
1039                 "%val       = OpLoad %f32 %var\n"
1040                 "%neg       = OpFNegate %f32 %val\n"
1041                 "             OpStore %outloc %neg\n"
1042                 "             OpReturn\n"
1043                 "             OpFunctionEnd\n";
1044
1045         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
1046         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
1047         spec4.numWorkGroups = IVec3(numElements, 1, 1);
1048
1049         group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
1050
1051         return group.release();
1052 }
1053
1054 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
1055 {
1056         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
1057         ComputeShaderSpec                               spec;
1058         de::Random                                              rnd                             (deStringHash(group->getName()));
1059         const int                                               numElements             = 100;
1060         vector<float>                                   inputFloats             (numElements, 0);
1061         vector<float>                                   outputFloats    (numElements, 0);
1062
1063         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
1064
1065         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
1066         floorAll(inputFloats);
1067
1068         for (size_t ndx = 0; ndx < numElements; ++ndx)
1069                 outputFloats[ndx] = inputFloats[ndx] + 7.5f;
1070
1071         spec.assembly =
1072                 string(s_ShaderPreamble) +
1073
1074                 "OpName %main           \"main\"\n"
1075                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1076
1077                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1078
1079                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) +
1080
1081                 "%fmat     = OpTypeMatrix %fvec3 3\n"
1082                 "%three    = OpConstant %u32 3\n"
1083                 "%farr     = OpTypeArray %f32 %three\n"
1084                 "%fst      = OpTypeStruct %f32 %f32\n"
1085
1086                 + string(s_InputOutputBuffer) +
1087
1088                 "%id            = OpVariable %uvec3ptr Input\n"
1089                 "%zero          = OpConstant %i32 0\n"
1090                 "%c_f           = OpConstant %f32 1.5\n"
1091                 "%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
1092                 "%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
1093                 "%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
1094                 "%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
1095
1096                 "%main          = OpFunction %void None %voidf\n"
1097                 "%label         = OpLabel\n"
1098                 "%c_f_copy      = OpCopyObject %f32   %c_f\n"
1099                 "%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
1100                 "%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
1101                 "%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
1102                 "%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
1103                 "%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
1104                 "%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
1105                 "%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
1106                 "%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
1107                 // Add up. 1.5 * 5 = 7.5.
1108                 "%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
1109                 "%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
1110                 "%add3          = OpFAdd %f32 %add2     %farr_elem\n"
1111                 "%add4          = OpFAdd %f32 %add3     %fst_elem\n"
1112
1113                 "%idval         = OpLoad %uvec3 %id\n"
1114                 "%x             = OpCompositeExtract %u32 %idval 0\n"
1115                 "%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
1116                 "%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
1117                 "%inval         = OpLoad %f32 %inloc\n"
1118                 "%add           = OpFAdd %f32 %add4 %inval\n"
1119                 "                 OpStore %outloc %add\n"
1120                 "                 OpReturn\n"
1121                 "                 OpFunctionEnd\n";
1122         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
1123         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1124         spec.numWorkGroups = IVec3(numElements, 1, 1);
1125
1126         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
1127
1128         return group.release();
1129 }
1130 // Assembly code used for testing OpUnreachable is based on GLSL source code:
1131 //
1132 // #version 430
1133 //
1134 // layout(std140, set = 0, binding = 0) readonly buffer Input {
1135 //   float elements[];
1136 // } input_data;
1137 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
1138 //   float elements[];
1139 // } output_data;
1140 //
1141 // void not_called_func() {
1142 //   // place OpUnreachable here
1143 // }
1144 //
1145 // uint modulo4(uint val) {
1146 //   switch (val % uint(4)) {
1147 //     case 0:  return 3;
1148 //     case 1:  return 2;
1149 //     case 2:  return 1;
1150 //     case 3:  return 0;
1151 //     default: return 100; // place OpUnreachable here
1152 //   }
1153 // }
1154 //
1155 // uint const5() {
1156 //   return 5;
1157 //   // place OpUnreachable here
1158 // }
1159 //
1160 // void main() {
1161 //   uint x = gl_GlobalInvocationID.x;
1162 //   if (const5() > modulo4(1000)) {
1163 //     output_data.elements[x] = -input_data.elements[x];
1164 //   } else {
1165 //     // place OpUnreachable here
1166 //     output_data.elements[x] = input_data.elements[x];
1167 //   }
1168 // }
1169
1170 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
1171 {
1172         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
1173         ComputeShaderSpec                               spec;
1174         de::Random                                              rnd                             (deStringHash(group->getName()));
1175         const int                                               numElements             = 100;
1176         vector<float>                                   positiveFloats  (numElements, 0);
1177         vector<float>                                   negativeFloats  (numElements, 0);
1178
1179         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
1180
1181         for (size_t ndx = 0; ndx < numElements; ++ndx)
1182                 negativeFloats[ndx] = -positiveFloats[ndx];
1183
1184         spec.assembly =
1185                 string(s_ShaderPreamble) +
1186
1187                 "OpSource GLSL 430\n"
1188                 "OpName %main            \"main\"\n"
1189                 "OpName %func_not_called_func \"not_called_func(\"\n"
1190                 "OpName %func_modulo4         \"modulo4(u1;\"\n"
1191                 "OpName %func_const5          \"const5(\"\n"
1192                 "OpName %id                   \"gl_GlobalInvocationID\"\n"
1193
1194                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1195
1196                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) +
1197
1198                 "%u32ptr    = OpTypePointer Function %u32\n"
1199                 "%uintfuint = OpTypeFunction %u32 %u32ptr\n"
1200                 "%unitf     = OpTypeFunction %u32\n"
1201
1202                 "%id        = OpVariable %uvec3ptr Input\n"
1203                 "%zero      = OpConstant %u32 0\n"
1204                 "%one       = OpConstant %u32 1\n"
1205                 "%two       = OpConstant %u32 2\n"
1206                 "%three     = OpConstant %u32 3\n"
1207                 "%four      = OpConstant %u32 4\n"
1208                 "%five      = OpConstant %u32 5\n"
1209                 "%hundred   = OpConstant %u32 100\n"
1210                 "%thousand  = OpConstant %u32 1000\n"
1211
1212                 + string(s_InputOutputBuffer) +
1213
1214                 // Main()
1215                 "%main   = OpFunction %void None %voidf\n"
1216                 "%main_entry  = OpLabel\n"
1217                 "%v_thousand  = OpVariable %u32ptr Function %thousand\n"
1218                 "%idval       = OpLoad %uvec3 %id\n"
1219                 "%x           = OpCompositeExtract %u32 %idval 0\n"
1220                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
1221                 "%inval       = OpLoad %f32 %inloc\n"
1222                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
1223                 "%ret_const5  = OpFunctionCall %u32 %func_const5\n"
1224                 "%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
1225                 "%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
1226                 "               OpSelectionMerge %if_end None\n"
1227                 "               OpBranchConditional %cmp_gt %if_true %if_false\n"
1228                 "%if_true     = OpLabel\n"
1229                 "%negate      = OpFNegate %f32 %inval\n"
1230                 "               OpStore %outloc %negate\n"
1231                 "               OpBranch %if_end\n"
1232                 "%if_false    = OpLabel\n"
1233                 "               OpUnreachable\n" // Unreachable else branch for if statement
1234                 "%if_end      = OpLabel\n"
1235                 "               OpReturn\n"
1236                 "               OpFunctionEnd\n"
1237
1238                 // not_called_function()
1239                 "%func_not_called_func  = OpFunction %void None %voidf\n"
1240                 "%not_called_func_entry = OpLabel\n"
1241                 "                         OpUnreachable\n" // Unreachable entry block in not called static function
1242                 "                         OpFunctionEnd\n"
1243
1244                 // modulo4()
1245                 "%func_modulo4  = OpFunction %u32 None %uintfuint\n"
1246                 "%valptr        = OpFunctionParameter %u32ptr\n"
1247                 "%modulo4_entry = OpLabel\n"
1248                 "%val           = OpLoad %u32 %valptr\n"
1249                 "%modulo        = OpUMod %u32 %val %four\n"
1250                 "                 OpSelectionMerge %switch_merge None\n"
1251                 "                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
1252                 "%case0         = OpLabel\n"
1253                 "                 OpReturnValue %three\n"
1254                 "%case1         = OpLabel\n"
1255                 "                 OpReturnValue %two\n"
1256                 "%case2         = OpLabel\n"
1257                 "                 OpReturnValue %one\n"
1258                 "%case3         = OpLabel\n"
1259                 "                 OpReturnValue %zero\n"
1260                 "%default       = OpLabel\n"
1261                 "                 OpUnreachable\n" // Unreachable default case for switch statement
1262                 "%switch_merge  = OpLabel\n"
1263                 "                 OpUnreachable\n" // Unreachable merge block for switch statement
1264                 "                 OpFunctionEnd\n"
1265
1266                 // const5()
1267                 "%func_const5  = OpFunction %u32 None %unitf\n"
1268                 "%const5_entry = OpLabel\n"
1269                 "                OpReturnValue %five\n"
1270                 "%unreachable  = OpLabel\n"
1271                 "                OpUnreachable\n" // Unreachable block in function
1272                 "                OpFunctionEnd\n";
1273         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
1274         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
1275         spec.numWorkGroups = IVec3(numElements, 1, 1);
1276
1277         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
1278
1279         return group.release();
1280 }
1281
1282 // Assembly code used for testing decoration group is based on GLSL source code:
1283 //
1284 // #version 430
1285 //
1286 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
1287 //   float elements[];
1288 // } input_data0;
1289 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
1290 //   float elements[];
1291 // } input_data1;
1292 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
1293 //   float elements[];
1294 // } input_data2;
1295 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
1296 //   float elements[];
1297 // } input_data3;
1298 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
1299 //   float elements[];
1300 // } input_data4;
1301 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
1302 //   float elements[];
1303 // } output_data;
1304 //
1305 // void main() {
1306 //   uint x = gl_GlobalInvocationID.x;
1307 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
1308 // }
1309 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
1310 {
1311         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
1312         ComputeShaderSpec                               spec;
1313         de::Random                                              rnd                             (deStringHash(group->getName()));
1314         const int                                               numElements             = 100;
1315         vector<float>                                   inputFloats0    (numElements, 0);
1316         vector<float>                                   inputFloats1    (numElements, 0);
1317         vector<float>                                   inputFloats2    (numElements, 0);
1318         vector<float>                                   inputFloats3    (numElements, 0);
1319         vector<float>                                   inputFloats4    (numElements, 0);
1320         vector<float>                                   outputFloats    (numElements, 0);
1321
1322         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
1323         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
1324         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
1325         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
1326         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
1327
1328         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
1329         floorAll(inputFloats0);
1330         floorAll(inputFloats1);
1331         floorAll(inputFloats2);
1332         floorAll(inputFloats3);
1333         floorAll(inputFloats4);
1334
1335         for (size_t ndx = 0; ndx < numElements; ++ndx)
1336                 outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
1337
1338         spec.assembly =
1339                 string(s_ShaderPreamble) +
1340
1341                 "OpSource GLSL 430\n"
1342                 "OpName %main \"main\"\n"
1343                 "OpName %id \"gl_GlobalInvocationID\"\n"
1344
1345                 // Not using group decoration on variable.
1346                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1347                 // Not using group decoration on type.
1348                 "OpDecorate %f32arr ArrayStride 4\n"
1349
1350                 "OpDecorate %groups BufferBlock\n"
1351                 "OpDecorate %groupm Offset 0\n"
1352                 "%groups = OpDecorationGroup\n"
1353                 "%groupm = OpDecorationGroup\n"
1354
1355                 // Group decoration on multiple structs.
1356                 "OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
1357                 // Group decoration on multiple struct members.
1358                 "OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
1359
1360                 "OpDecorate %group1 DescriptorSet 0\n"
1361                 "OpDecorate %group3 DescriptorSet 0\n"
1362                 "OpDecorate %group3 NonWritable\n"
1363                 "OpDecorate %group3 Restrict\n"
1364                 "%group0 = OpDecorationGroup\n"
1365                 "%group1 = OpDecorationGroup\n"
1366                 "%group3 = OpDecorationGroup\n"
1367
1368                 // Applying the same decoration group multiple times.
1369                 "OpGroupDecorate %group1 %outdata\n"
1370                 "OpGroupDecorate %group1 %outdata\n"
1371                 "OpGroupDecorate %group1 %outdata\n"
1372                 "OpDecorate %outdata DescriptorSet 0\n"
1373                 "OpDecorate %outdata Binding 5\n"
1374                 // Applying decoration group containing nothing.
1375                 "OpGroupDecorate %group0 %indata0\n"
1376                 "OpDecorate %indata0 DescriptorSet 0\n"
1377                 "OpDecorate %indata0 Binding 0\n"
1378                 // Applying decoration group containing one decoration.
1379                 "OpGroupDecorate %group1 %indata1\n"
1380                 "OpDecorate %indata1 Binding 1\n"
1381                 // Applying decoration group containing multiple decorations.
1382                 "OpGroupDecorate %group3 %indata2 %indata3\n"
1383                 "OpDecorate %indata2 Binding 2\n"
1384                 "OpDecorate %indata3 Binding 3\n"
1385                 // Applying multiple decoration groups (with overlapping).
1386                 "OpGroupDecorate %group0 %indata4\n"
1387                 "OpGroupDecorate %group1 %indata4\n"
1388                 "OpGroupDecorate %group3 %indata4\n"
1389                 "OpDecorate %indata4 Binding 4\n"
1390
1391                 + string(s_CommonTypes) +
1392
1393                 "%id   = OpVariable %uvec3ptr Input\n"
1394                 "%zero = OpConstant %i32 0\n"
1395
1396                 "%outbuf    = OpTypeStruct %f32arr\n"
1397                 "%outbufptr = OpTypePointer Uniform %outbuf\n"
1398                 "%outdata   = OpVariable %outbufptr Uniform\n"
1399                 "%inbuf0    = OpTypeStruct %f32arr\n"
1400                 "%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
1401                 "%indata0   = OpVariable %inbuf0ptr Uniform\n"
1402                 "%inbuf1    = OpTypeStruct %f32arr\n"
1403                 "%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
1404                 "%indata1   = OpVariable %inbuf1ptr Uniform\n"
1405                 "%inbuf2    = OpTypeStruct %f32arr\n"
1406                 "%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
1407                 "%indata2   = OpVariable %inbuf2ptr Uniform\n"
1408                 "%inbuf3    = OpTypeStruct %f32arr\n"
1409                 "%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
1410                 "%indata3   = OpVariable %inbuf3ptr Uniform\n"
1411                 "%inbuf4    = OpTypeStruct %f32arr\n"
1412                 "%inbufptr  = OpTypePointer Uniform %inbuf4\n"
1413                 "%indata4   = OpVariable %inbufptr Uniform\n"
1414
1415                 "%main   = OpFunction %void None %voidf\n"
1416                 "%label  = OpLabel\n"
1417                 "%idval  = OpLoad %uvec3 %id\n"
1418                 "%x      = OpCompositeExtract %u32 %idval 0\n"
1419                 "%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
1420                 "%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
1421                 "%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
1422                 "%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
1423                 "%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
1424                 "%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
1425                 "%inval0 = OpLoad %f32 %inloc0\n"
1426                 "%inval1 = OpLoad %f32 %inloc1\n"
1427                 "%inval2 = OpLoad %f32 %inloc2\n"
1428                 "%inval3 = OpLoad %f32 %inloc3\n"
1429                 "%inval4 = OpLoad %f32 %inloc4\n"
1430                 "%add0   = OpFAdd %f32 %inval0 %inval1\n"
1431                 "%add1   = OpFAdd %f32 %add0 %inval2\n"
1432                 "%add2   = OpFAdd %f32 %add1 %inval3\n"
1433                 "%add    = OpFAdd %f32 %add2 %inval4\n"
1434                 "          OpStore %outloc %add\n"
1435                 "          OpReturn\n"
1436                 "          OpFunctionEnd\n";
1437         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
1438         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1439         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1440         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1441         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
1442         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1443         spec.numWorkGroups = IVec3(numElements, 1, 1);
1444
1445         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
1446
1447         return group.release();
1448 }
1449
1450 struct SpecConstantTwoIntCase
1451 {
1452         const char*             caseName;
1453         const char*             scDefinition0;
1454         const char*             scDefinition1;
1455         const char*             scResultType;
1456         const char*             scOperation;
1457         deInt32                 scActualValue0;
1458         deInt32                 scActualValue1;
1459         const char*             resultOperation;
1460         vector<deInt32> expectedOutput;
1461
1462                                         SpecConstantTwoIntCase (const char* name,
1463                                                                                         const char* definition0,
1464                                                                                         const char* definition1,
1465                                                                                         const char* resultType,
1466                                                                                         const char* operation,
1467                                                                                         deInt32 value0,
1468                                                                                         deInt32 value1,
1469                                                                                         const char* resultOp,
1470                                                                                         const vector<deInt32>& output)
1471                                                 : caseName                      (name)
1472                                                 , scDefinition0         (definition0)
1473                                                 , scDefinition1         (definition1)
1474                                                 , scResultType          (resultType)
1475                                                 , scOperation           (operation)
1476                                                 , scActualValue0        (value0)
1477                                                 , scActualValue1        (value1)
1478                                                 , resultOperation       (resultOp)
1479                                                 , expectedOutput        (output) {}
1480 };
1481
1482 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
1483 {
1484         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
1485         vector<SpecConstantTwoIntCase>  cases;
1486         de::Random                                              rnd                             (deStringHash(group->getName()));
1487         const int                                               numElements             = 100;
1488         vector<deInt32>                                 inputInts               (numElements, 0);
1489         vector<deInt32>                                 outputInts1             (numElements, 0);
1490         vector<deInt32>                                 outputInts2             (numElements, 0);
1491         vector<deInt32>                                 outputInts3             (numElements, 0);
1492         vector<deInt32>                                 outputInts4             (numElements, 0);
1493         const StringTemplate                    shaderTemplate  (
1494                 string(s_ShaderPreamble) +
1495
1496                 "OpName %main           \"main\"\n"
1497                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1498
1499                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1500                 "OpDecorate %sc_0  SpecId 0\n"
1501                 "OpDecorate %sc_1  SpecId 1\n"
1502                 "OpDecorate %i32arr ArrayStride 4\n"
1503
1504                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) +
1505
1506                 "%buf     = OpTypeStruct %i32arr\n"
1507                 "%bufptr  = OpTypePointer Uniform %buf\n"
1508                 "%indata    = OpVariable %bufptr Uniform\n"
1509                 "%outdata   = OpVariable %bufptr Uniform\n"
1510
1511                 "%id        = OpVariable %uvec3ptr Input\n"
1512                 "%zero      = OpConstant %i32 0\n"
1513
1514                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
1515                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
1516                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
1517
1518                 "%main      = OpFunction %void None %voidf\n"
1519                 "%label     = OpLabel\n"
1520                 "%idval     = OpLoad %uvec3 %id\n"
1521                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1522                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
1523                 "%inval     = OpLoad %i32 %inloc\n"
1524                 "%final     = ${GEN_RESULT}\n"
1525                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1526                 "             OpStore %outloc %final\n"
1527                 "             OpReturn\n"
1528                 "             OpFunctionEnd\n");
1529
1530         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
1531
1532         for (size_t ndx = 0; ndx < numElements; ++ndx)
1533         {
1534                 outputInts1[ndx] = inputInts[ndx] + 42;
1535                 outputInts2[ndx] = inputInts[ndx];
1536                 outputInts3[ndx] = inputInts[ndx] - 11200;
1537                 outputInts4[ndx] = inputInts[ndx] + 1;
1538         }
1539
1540         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
1541         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
1542         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
1543
1544         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
1545         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
1546         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
1547         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
1548         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
1549         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
1550         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
1551         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
1552         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
1553         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
1554         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
1555         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
1556         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
1557         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
1558         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
1559         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
1560         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
1561         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
1562         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
1563         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
1564         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
1565         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
1566         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
1567         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
1568         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
1569         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
1570         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
1571         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
1572         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
1573         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
1574         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
1575         // OpSConvert, OpFConvert: these two instructions involve ints/floats of different bitwidths.
1576
1577         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
1578         {
1579                 map<string, string>             specializations;
1580                 ComputeShaderSpec               spec;
1581
1582                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
1583                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
1584                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
1585                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
1586                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
1587
1588                 spec.assembly = shaderTemplate.specialize(specializations);
1589                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
1590                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
1591                 spec.numWorkGroups = IVec3(numElements, 1, 1);
1592                 spec.specConstants.push_back(cases[caseNdx].scActualValue0);
1593                 spec.specConstants.push_back(cases[caseNdx].scActualValue1);
1594
1595                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec));
1596         }
1597
1598         ComputeShaderSpec                               spec;
1599
1600         spec.assembly =
1601                 string(s_ShaderPreamble) +
1602
1603                 "OpName %main           \"main\"\n"
1604                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1605
1606                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1607                 "OpDecorate %sc_0  SpecId 0\n"
1608                 "OpDecorate %sc_1  SpecId 1\n"
1609                 "OpDecorate %sc_2  SpecId 2\n"
1610                 "OpDecorate %i32arr ArrayStride 4\n"
1611
1612                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) +
1613
1614                 "%ivec3     = OpTypeVector %i32 3\n"
1615                 "%buf     = OpTypeStruct %i32arr\n"
1616                 "%bufptr  = OpTypePointer Uniform %buf\n"
1617                 "%indata    = OpVariable %bufptr Uniform\n"
1618                 "%outdata   = OpVariable %bufptr Uniform\n"
1619
1620                 "%id        = OpVariable %uvec3ptr Input\n"
1621                 "%zero      = OpConstant %i32 0\n"
1622                 "%ivec3_0   = OpConstantComposite %ivec3 %zero %zero %zero\n"
1623
1624                 "%sc_0        = OpSpecConstant %i32 0\n"
1625                 "%sc_1        = OpSpecConstant %i32 0\n"
1626                 "%sc_2        = OpSpecConstant %i32 0\n"
1627                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0   0\n"     // (sc_0, 0, 0)
1628                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0   1\n"     // (0, sc_1, 0)
1629                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0   2\n"     // (0, 0, sc_2)
1630                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %sc_vec3_1 1 0 4\n" // (0,    sc_0, sc_1)
1631                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2 5 1 2\n" // (sc_2, sc_0, sc_1)
1632                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012            0\n"     // sc_2
1633                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012            1\n"     // sc_0
1634                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012            2\n"     // sc_1
1635                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"        // (sc_2 - sc_0)
1636                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"        // (sc_2 - sc_0) * sc_1
1637
1638                 "%main      = OpFunction %void None %voidf\n"
1639                 "%label     = OpLabel\n"
1640                 "%idval     = OpLoad %uvec3 %id\n"
1641                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1642                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
1643                 "%inval     = OpLoad %i32 %inloc\n"
1644                 "%final     = OpIAdd %i32 %inval %sc_final\n"
1645                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1646                 "             OpStore %outloc %final\n"
1647                 "             OpReturn\n"
1648                 "             OpFunctionEnd\n";
1649         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
1650         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
1651         spec.numWorkGroups = IVec3(numElements, 1, 1);
1652         spec.specConstants.push_back(123);
1653         spec.specConstants.push_back(56);
1654         spec.specConstants.push_back(-77);
1655
1656         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
1657
1658         return group.release();
1659 }
1660
1661 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
1662 {
1663         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
1664         ComputeShaderSpec                               spec1;
1665         ComputeShaderSpec                               spec2;
1666         ComputeShaderSpec                               spec3;
1667         de::Random                                              rnd                             (deStringHash(group->getName()));
1668         const int                                               numElements             = 100;
1669         vector<float>                                   inputFloats             (numElements, 0);
1670         vector<float>                                   outputFloats1   (numElements, 0);
1671         vector<float>                                   outputFloats2   (numElements, 0);
1672         vector<float>                                   outputFloats3   (numElements, 0);
1673
1674         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
1675
1676         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
1677         floorAll(inputFloats);
1678
1679         for (size_t ndx = 0; ndx < numElements; ++ndx)
1680         {
1681                 switch (ndx % 3)
1682                 {
1683                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
1684                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
1685                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
1686                         default:        break;
1687                 }
1688                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
1689                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
1690         }
1691
1692         spec1.assembly =
1693                 string(s_ShaderPreamble) +
1694
1695                 "OpSource GLSL 430\n"
1696                 "OpName %main \"main\"\n"
1697                 "OpName %id \"gl_GlobalInvocationID\"\n"
1698
1699                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1700
1701                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
1702
1703                 "%id = OpVariable %uvec3ptr Input\n"
1704                 "%zero       = OpConstant %i32 0\n"
1705                 "%three      = OpConstant %u32 3\n"
1706                 "%constf5p5  = OpConstant %f32 5.5\n"
1707                 "%constf20p5 = OpConstant %f32 20.5\n"
1708                 "%constf1p75 = OpConstant %f32 1.75\n"
1709                 "%constf8p5  = OpConstant %f32 8.5\n"
1710                 "%constf6p5  = OpConstant %f32 6.5\n"
1711
1712                 "%main     = OpFunction %void None %voidf\n"
1713                 "%entry    = OpLabel\n"
1714                 "%idval    = OpLoad %uvec3 %id\n"
1715                 "%x        = OpCompositeExtract %u32 %idval 0\n"
1716                 "%selector = OpUMod %u32 %x %three\n"
1717                 "            OpSelectionMerge %phi None\n"
1718                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
1719
1720                 // Case 1 before OpPhi.
1721                 "%case1    = OpLabel\n"
1722                 "            OpBranch %phi\n"
1723
1724                 "%default  = OpLabel\n"
1725                 "            OpUnreachable\n"
1726
1727                 "%phi      = OpLabel\n"
1728                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
1729                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
1730                 "%inval    = OpLoad %f32 %inloc\n"
1731                 "%add      = OpFAdd %f32 %inval %operand\n"
1732                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
1733                 "            OpStore %outloc %add\n"
1734                 "            OpReturn\n"
1735
1736                 // Case 0 after OpPhi.
1737                 "%case0    = OpLabel\n"
1738                 "            OpBranch %phi\n"
1739
1740
1741                 // Case 2 after OpPhi.
1742                 "%case2    = OpLabel\n"
1743                 "            OpBranch %phi\n"
1744
1745                 "            OpFunctionEnd\n";
1746         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
1747         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
1748         spec1.numWorkGroups = IVec3(numElements, 1, 1);
1749
1750         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
1751
1752         spec2.assembly =
1753                 string(s_ShaderPreamble) +
1754
1755                 "OpName %main \"main\"\n"
1756                 "OpName %id \"gl_GlobalInvocationID\"\n"
1757
1758                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1759
1760                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
1761
1762                 "%id         = OpVariable %uvec3ptr Input\n"
1763                 "%zero       = OpConstant %i32 0\n"
1764                 "%one        = OpConstant %i32 1\n"
1765                 "%three      = OpConstant %i32 3\n"
1766                 "%constf6p5  = OpConstant %f32 6.5\n"
1767
1768                 "%main       = OpFunction %void None %voidf\n"
1769                 "%entry      = OpLabel\n"
1770                 "%idval      = OpLoad %uvec3 %id\n"
1771                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1772                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
1773                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
1774                 "%inval      = OpLoad %f32 %inloc\n"
1775                 "              OpBranch %phi\n"
1776
1777                 "%phi        = OpLabel\n"
1778                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
1779                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
1780                 "%step_next  = OpIAdd %i32 %step %one\n"
1781                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
1782                 "%still_loop = OpSLessThan %bool %step %three\n"
1783                 "              OpLoopMerge %exit %phi None\n"
1784                 "              OpBranchConditional %still_loop %phi %exit\n"
1785
1786                 "%exit       = OpLabel\n"
1787                 "              OpStore %outloc %accum\n"
1788                 "              OpReturn\n"
1789                 "              OpFunctionEnd\n";
1790         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
1791         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
1792         spec2.numWorkGroups = IVec3(numElements, 1, 1);
1793
1794         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
1795
1796         spec3.assembly =
1797                 string(s_ShaderPreamble) +
1798
1799                 "OpName %main \"main\"\n"
1800                 "OpName %id \"gl_GlobalInvocationID\"\n"
1801
1802                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1803
1804                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
1805
1806                 "%f32ptr_f   = OpTypePointer Function %f32\n"
1807                 "%id         = OpVariable %uvec3ptr Input\n"
1808                 "%true       = OpConstantTrue %bool\n"
1809                 "%false      = OpConstantFalse %bool\n"
1810                 "%zero       = OpConstant %i32 0\n"
1811                 "%constf8p5  = OpConstant %f32 8.5\n"
1812
1813                 "%main       = OpFunction %void None %voidf\n"
1814                 "%entry      = OpLabel\n"
1815                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
1816                 "%idval      = OpLoad %uvec3 %id\n"
1817                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1818                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
1819                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
1820                 "%a_init     = OpLoad %f32 %inloc\n"
1821                 "%b_init     = OpLoad %f32 %b\n"
1822                 "              OpBranch %phi\n"
1823
1824                 "%phi        = OpLabel\n"
1825                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
1826                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
1827                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
1828                 "              OpLoopMerge %exit %phi None\n"
1829                 "              OpBranchConditional %still_loop %phi %exit\n"
1830
1831                 "%exit       = OpLabel\n"
1832                 "%sub        = OpFSub %f32 %a_next %b_next\n"
1833                 "              OpStore %outloc %sub\n"
1834                 "              OpReturn\n"
1835                 "              OpFunctionEnd\n";
1836         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
1837         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
1838         spec3.numWorkGroups = IVec3(numElements, 1, 1);
1839
1840         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
1841
1842         return group.release();
1843 }
1844
1845 // Assembly code used for testing block order is based on GLSL source code:
1846 //
1847 // #version 430
1848 //
1849 // layout(std140, set = 0, binding = 0) readonly buffer Input {
1850 //   float elements[];
1851 // } input_data;
1852 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
1853 //   float elements[];
1854 // } output_data;
1855 //
1856 // void main() {
1857 //   uint x = gl_GlobalInvocationID.x;
1858 //   output_data.elements[x] = input_data.elements[x];
1859 //   if (x > uint(50)) {
1860 //     switch (x % uint(3)) {
1861 //       case 0: output_data.elements[x] += 1.5f; break;
1862 //       case 1: output_data.elements[x] += 42.f; break;
1863 //       case 2: output_data.elements[x] -= 27.f; break;
1864 //       default: break;
1865 //     }
1866 //   } else {
1867 //     output_data.elements[x] = -input_data.elements[x];
1868 //   }
1869 // }
1870 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
1871 {
1872         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
1873         ComputeShaderSpec                               spec;
1874         de::Random                                              rnd                             (deStringHash(group->getName()));
1875         const int                                               numElements             = 100;
1876         vector<float>                                   inputFloats             (numElements, 0);
1877         vector<float>                                   outputFloats    (numElements, 0);
1878
1879         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
1880
1881         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
1882         floorAll(inputFloats);
1883
1884         for (size_t ndx = 0; ndx <= 50; ++ndx)
1885                 outputFloats[ndx] = -inputFloats[ndx];
1886
1887         for (size_t ndx = 51; ndx < numElements; ++ndx)
1888         {
1889                 switch (ndx % 3)
1890                 {
1891                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
1892                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
1893                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
1894                         default:        break;
1895                 }
1896         }
1897
1898         spec.assembly =
1899                 string(s_ShaderPreamble) +
1900
1901                 "OpSource GLSL 430\n"
1902                 "OpName %main \"main\"\n"
1903                 "OpName %id \"gl_GlobalInvocationID\"\n"
1904
1905                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1906
1907                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) +
1908
1909                 "%u32ptr       = OpTypePointer Function %u32\n"
1910                 "%u32ptr_input = OpTypePointer Input %u32\n"
1911
1912                 + string(s_InputOutputBuffer) +
1913
1914                 "%id        = OpVariable %uvec3ptr Input\n"
1915                 "%zero      = OpConstant %i32 0\n"
1916                 "%const3    = OpConstant %u32 3\n"
1917                 "%const50   = OpConstant %u32 50\n"
1918                 "%constf1p5 = OpConstant %f32 1.5\n"
1919                 "%constf27  = OpConstant %f32 27.0\n"
1920                 "%constf42  = OpConstant %f32 42.0\n"
1921
1922                 "%main = OpFunction %void None %voidf\n"
1923
1924                 // entry block.
1925                 "%entry    = OpLabel\n"
1926
1927                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
1928                 "%xvar     = OpVariable %u32ptr Function\n"
1929                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
1930                 "%x        = OpLoad %u32 %xptr\n"
1931                 "            OpStore %xvar %x\n"
1932
1933                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
1934                 "            OpSelectionMerge %if_merge None\n"
1935                 "            OpBranchConditional %cmp %if_true %if_false\n"
1936
1937                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
1938                 "%if_false = OpLabel\n"
1939                 "%x_f      = OpLoad %u32 %xvar\n"
1940                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
1941                 "%inval_f  = OpLoad %f32 %inloc_f\n"
1942                 "%negate   = OpFNegate %f32 %inval_f\n"
1943                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
1944                 "            OpStore %outloc_f %negate\n"
1945                 "            OpBranch %if_merge\n"
1946
1947                 // Merge block for if-statement: placed in the middle of true and false branch.
1948                 "%if_merge = OpLabel\n"
1949                 "            OpReturn\n"
1950
1951                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
1952                 "%if_true  = OpLabel\n"
1953                 "%xval_t   = OpLoad %u32 %xvar\n"
1954                 "%mod      = OpUMod %u32 %xval_t %const3\n"
1955                 "            OpSelectionMerge %switch_merge None\n"
1956                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
1957
1958                 // Merge block for switch-statement: placed before the case
1959                 // bodies.  But it must follow OpSwitch which dominates it.
1960                 "%switch_merge = OpLabel\n"
1961                 "                OpBranch %if_merge\n"
1962
1963                 // Case 1 for switch-statement: placed before case 0.
1964                 // It must follow the OpSwitch that dominates it.
1965                 "%case1    = OpLabel\n"
1966                 "%x_1      = OpLoad %u32 %xvar\n"
1967                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
1968                 "%inval_1  = OpLoad %f32 %inloc_1\n"
1969                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
1970                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
1971                 "            OpStore %outloc_1 %addf42\n"
1972                 "            OpBranch %switch_merge\n"
1973
1974                 // Case 2 for switch-statement.
1975                 "%case2    = OpLabel\n"
1976                 "%x_2      = OpLoad %u32 %xvar\n"
1977                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
1978                 "%inval_2  = OpLoad %f32 %inloc_2\n"
1979                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
1980                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
1981                 "            OpStore %outloc_2 %subf27\n"
1982                 "            OpBranch %switch_merge\n"
1983
1984                 // Default case for switch-statement: placed in the middle of normal cases.
1985                 "%default = OpLabel\n"
1986                 "           OpBranch %switch_merge\n"
1987
1988                 // Case 0 for switch-statement: out of order.
1989                 "%case0    = OpLabel\n"
1990                 "%x_0      = OpLoad %u32 %xvar\n"
1991                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
1992                 "%inval_0  = OpLoad %f32 %inloc_0\n"
1993                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
1994                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
1995                 "            OpStore %outloc_0 %addf1p5\n"
1996                 "            OpBranch %switch_merge\n"
1997
1998                 "            OpFunctionEnd\n";
1999         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2000         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2001         spec.numWorkGroups = IVec3(numElements, 1, 1);
2002
2003         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
2004
2005         return group.release();
2006 }
2007
2008 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
2009 {
2010         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
2011         ComputeShaderSpec                               spec1;
2012         ComputeShaderSpec                               spec2;
2013         de::Random                                              rnd                             (deStringHash(group->getName()));
2014         const int                                               numElements             = 100;
2015         vector<float>                                   inputFloats             (numElements, 0);
2016         vector<float>                                   outputFloats1   (numElements, 0);
2017         vector<float>                                   outputFloats2   (numElements, 0);
2018         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
2019
2020         for (size_t ndx = 0; ndx < numElements; ++ndx)
2021         {
2022                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
2023                 outputFloats2[ndx] = -inputFloats[ndx];
2024         }
2025
2026         const string assembly(
2027                 "OpCapability Shader\n"
2028                 "OpCapability ClipDistance\n"
2029                 "OpMemoryModel Logical GLSL450\n"
2030                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
2031                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
2032                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
2033                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
2034                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
2035                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
2036
2037                 "OpName %comp_main1              \"entrypoint1\"\n"
2038                 "OpName %comp_main2              \"entrypoint2\"\n"
2039                 "OpName %vert_main               \"entrypoint2\"\n"
2040                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
2041                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
2042                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
2043                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
2044                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
2045                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
2046                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
2047
2048                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
2049                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
2050                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
2051                 "OpDecorate %vert_builtin_st         Block\n"
2052                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
2053                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
2054                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
2055
2056                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
2057
2058                 "%zero       = OpConstant %i32 0\n"
2059                 "%one        = OpConstant %u32 1\n"
2060                 "%c_f32_1    = OpConstant %f32 1\n"
2061
2062                 "%i32inputptr         = OpTypePointer Input %i32\n"
2063                 "%vec4                = OpTypeVector %f32 4\n"
2064                 "%vec4ptr             = OpTypePointer Output %vec4\n"
2065                 "%f32arr1             = OpTypeArray %f32 %one\n"
2066                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
2067                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
2068                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
2069
2070                 "%id         = OpVariable %uvec3ptr Input\n"
2071                 "%vertexIndex = OpVariable %i32inputptr Input\n"
2072                 "%instanceIndex = OpVariable %i32inputptr Input\n"
2073                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
2074
2075                 // gl_Position = vec4(1.);
2076                 "%vert_main  = OpFunction %void None %voidf\n"
2077                 "%vert_entry = OpLabel\n"
2078                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
2079                 "              OpStore %position %c_vec4_1\n"
2080                 "              OpReturn\n"
2081                 "              OpFunctionEnd\n"
2082
2083                 // Double inputs.
2084                 "%comp_main1  = OpFunction %void None %voidf\n"
2085                 "%comp1_entry = OpLabel\n"
2086                 "%idval1      = OpLoad %uvec3 %id\n"
2087                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
2088                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
2089                 "%inval1      = OpLoad %f32 %inloc1\n"
2090                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
2091                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
2092                 "               OpStore %outloc1 %add\n"
2093                 "               OpReturn\n"
2094                 "               OpFunctionEnd\n"
2095
2096                 // Negate inputs.
2097                 "%comp_main2  = OpFunction %void None %voidf\n"
2098                 "%comp2_entry = OpLabel\n"
2099                 "%idval2      = OpLoad %uvec3 %id\n"
2100                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
2101                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
2102                 "%inval2      = OpLoad %f32 %inloc2\n"
2103                 "%neg         = OpFNegate %f32 %inval2\n"
2104                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
2105                 "               OpStore %outloc2 %neg\n"
2106                 "               OpReturn\n"
2107                 "               OpFunctionEnd\n");
2108
2109         spec1.assembly = assembly;
2110         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2111         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
2112         spec1.numWorkGroups = IVec3(numElements, 1, 1);
2113         spec1.entryPoint = "entrypoint1";
2114
2115         spec2.assembly = assembly;
2116         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2117         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2118         spec2.numWorkGroups = IVec3(numElements, 1, 1);
2119         spec2.entryPoint = "entrypoint2";
2120
2121         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
2122         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
2123
2124         return group.release();
2125 }
2126
2127 inline std::string makeLongUTF8String (size_t num4ByteChars)
2128 {
2129         // An example of a longest valid UTF-8 character.  Be explicit about the
2130         // character type because Microsoft compilers can otherwise interpret the
2131         // character string as being over wide (16-bit) characters. Ideally, we
2132         // would just use a C++11 UTF-8 string literal, but we want to support older
2133         // Microsoft compilers.
2134         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
2135         std::string longString;
2136         longString.reserve(num4ByteChars * 4);
2137         for (size_t count = 0; count < num4ByteChars; count++)
2138         {
2139                 longString += earthAfrica;
2140         }
2141         return longString;
2142 }
2143
2144 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
2145 {
2146         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
2147         vector<CaseParameter>                   cases;
2148         de::Random                                              rnd                             (deStringHash(group->getName()));
2149         const int                                               numElements             = 100;
2150         vector<float>                                   positiveFloats  (numElements, 0);
2151         vector<float>                                   negativeFloats  (numElements, 0);
2152         const StringTemplate                    shaderTemplate  (
2153                 "OpCapability Shader\n"
2154                 "OpMemoryModel Logical GLSL450\n"
2155
2156                 "OpEntryPoint GLCompute %main \"main\" %id\n"
2157                 "OpExecutionMode %main LocalSize 1 1 1\n"
2158
2159                 "${SOURCE}\n"
2160
2161                 "OpName %main           \"main\"\n"
2162                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2163
2164                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2165
2166                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
2167
2168                 "%id        = OpVariable %uvec3ptr Input\n"
2169                 "%zero      = OpConstant %i32 0\n"
2170
2171                 "%main      = OpFunction %void None %voidf\n"
2172                 "%label     = OpLabel\n"
2173                 "%idval     = OpLoad %uvec3 %id\n"
2174                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2175                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2176                 "%inval     = OpLoad %f32 %inloc\n"
2177                 "%neg       = OpFNegate %f32 %inval\n"
2178                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2179                 "             OpStore %outloc %neg\n"
2180                 "             OpReturn\n"
2181                 "             OpFunctionEnd\n");
2182
2183         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
2184         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
2185         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
2186                                                                                                                                                         "OpSource GLSL 430 %fname"));
2187         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
2188                                                                                                                                                         "OpSource GLSL 430 %fname"));
2189         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
2190                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
2191         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
2192                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
2193         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
2194                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
2195         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
2196                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
2197         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
2198                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
2199                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
2200         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
2201                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
2202                                                                                                                                                         "OpSourceContinued \"\""));
2203         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
2204                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
2205                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
2206         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
2207                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
2208                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
2209         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
2210                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
2211                                                                                                                                                         "OpSourceContinued \"void\"\n"
2212                                                                                                                                                         "OpSourceContinued \"main()\"\n"
2213                                                                                                                                                         "OpSourceContinued \"{}\""));
2214         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
2215                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
2216                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
2217
2218         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2219
2220         for (size_t ndx = 0; ndx < numElements; ++ndx)
2221                 negativeFloats[ndx] = -positiveFloats[ndx];
2222
2223         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2224         {
2225                 map<string, string>             specializations;
2226                 ComputeShaderSpec               spec;
2227
2228                 specializations["SOURCE"] = cases[caseNdx].param;
2229                 spec.assembly = shaderTemplate.specialize(specializations);
2230                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2231                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2232                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2233
2234                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
2235         }
2236
2237         return group.release();
2238 }
2239
2240 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
2241 {
2242         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
2243         vector<CaseParameter>                   cases;
2244         de::Random                                              rnd                             (deStringHash(group->getName()));
2245         const int                                               numElements             = 100;
2246         vector<float>                                   inputFloats             (numElements, 0);
2247         vector<float>                                   outputFloats    (numElements, 0);
2248         const StringTemplate                    shaderTemplate  (
2249                 string(s_ShaderPreamble) +
2250
2251                 "OpSourceExtension \"${EXTENSION}\"\n"
2252
2253                 "OpName %main           \"main\"\n"
2254                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2255
2256                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2257
2258                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
2259
2260                 "%id        = OpVariable %uvec3ptr Input\n"
2261                 "%zero      = OpConstant %i32 0\n"
2262
2263                 "%main      = OpFunction %void None %voidf\n"
2264                 "%label     = OpLabel\n"
2265                 "%idval     = OpLoad %uvec3 %id\n"
2266                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2267                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2268                 "%inval     = OpLoad %f32 %inloc\n"
2269                 "%neg       = OpFNegate %f32 %inval\n"
2270                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2271                 "             OpStore %outloc %neg\n"
2272                 "             OpReturn\n"
2273                 "             OpFunctionEnd\n");
2274
2275         cases.push_back(CaseParameter("empty_extension",        ""));
2276         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
2277         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
2278         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
2279         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
2280
2281         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2282
2283         for (size_t ndx = 0; ndx < numElements; ++ndx)
2284                 outputFloats[ndx] = -inputFloats[ndx];
2285
2286         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2287         {
2288                 map<string, string>             specializations;
2289                 ComputeShaderSpec               spec;
2290
2291                 specializations["EXTENSION"] = cases[caseNdx].param;
2292                 spec.assembly = shaderTemplate.specialize(specializations);
2293                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2294                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2295                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2296
2297                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
2298         }
2299
2300         return group.release();
2301 }
2302
2303 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
2304 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
2305 {
2306         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
2307         vector<CaseParameter>                   cases;
2308         de::Random                                              rnd                             (deStringHash(group->getName()));
2309         const int                                               numElements             = 100;
2310         vector<float>                                   positiveFloats  (numElements, 0);
2311         vector<float>                                   negativeFloats  (numElements, 0);
2312         const StringTemplate                    shaderTemplate  (
2313                 string(s_ShaderPreamble) +
2314
2315                 "OpSource GLSL 430\n"
2316                 "OpName %main           \"main\"\n"
2317                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2318
2319                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2320
2321                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
2322
2323                 "${TYPE}\n"
2324                 "%null      = OpConstantNull %type\n"
2325
2326                 "%id        = OpVariable %uvec3ptr Input\n"
2327                 "%zero      = OpConstant %i32 0\n"
2328
2329                 "%main      = OpFunction %void None %voidf\n"
2330                 "%label     = OpLabel\n"
2331                 "%idval     = OpLoad %uvec3 %id\n"
2332                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2333                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2334                 "%inval     = OpLoad %f32 %inloc\n"
2335                 "%neg       = OpFNegate %f32 %inval\n"
2336                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2337                 "             OpStore %outloc %neg\n"
2338                 "             OpReturn\n"
2339                 "             OpFunctionEnd\n");
2340
2341         cases.push_back(CaseParameter("bool",                   "%type = OpTypeBool"));
2342         cases.push_back(CaseParameter("sint32",                 "%type = OpTypeInt 32 1"));
2343         cases.push_back(CaseParameter("uint32",                 "%type = OpTypeInt 32 0"));
2344         cases.push_back(CaseParameter("float32",                "%type = OpTypeFloat 32"));
2345         cases.push_back(CaseParameter("vec4float32",    "%type = OpTypeVector %f32 4"));
2346         cases.push_back(CaseParameter("vec3bool",               "%type = OpTypeVector %bool 3"));
2347         cases.push_back(CaseParameter("vec2uint32",             "%type = OpTypeVector %u32 2"));
2348         cases.push_back(CaseParameter("matrix",                 "%type = OpTypeMatrix %fvec3 3"));
2349         cases.push_back(CaseParameter("array",                  "%100 = OpConstant %u32 100\n"
2350                                                                                                         "%type = OpTypeArray %i32 %100"));
2351         cases.push_back(CaseParameter("struct",                 "%type = OpTypeStruct %f32 %i32 %u32"));
2352         cases.push_back(CaseParameter("pointer",                "%type = OpTypePointer Function %i32"));
2353
2354         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2355
2356         for (size_t ndx = 0; ndx < numElements; ++ndx)
2357                 negativeFloats[ndx] = -positiveFloats[ndx];
2358
2359         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2360         {
2361                 map<string, string>             specializations;
2362                 ComputeShaderSpec               spec;
2363
2364                 specializations["TYPE"] = cases[caseNdx].param;
2365                 spec.assembly = shaderTemplate.specialize(specializations);
2366                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2367                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2368                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2369
2370                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
2371         }
2372
2373         return group.release();
2374 }
2375
2376 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
2377 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
2378 {
2379         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
2380         vector<CaseParameter>                   cases;
2381         de::Random                                              rnd                             (deStringHash(group->getName()));
2382         const int                                               numElements             = 100;
2383         vector<float>                                   positiveFloats  (numElements, 0);
2384         vector<float>                                   negativeFloats  (numElements, 0);
2385         const StringTemplate                    shaderTemplate  (
2386                 string(s_ShaderPreamble) +
2387
2388                 "OpSource GLSL 430\n"
2389                 "OpName %main           \"main\"\n"
2390                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2391
2392                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2393
2394                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
2395
2396                 "%id        = OpVariable %uvec3ptr Input\n"
2397                 "%zero      = OpConstant %i32 0\n"
2398
2399                 "${CONSTANT}\n"
2400
2401                 "%main      = OpFunction %void None %voidf\n"
2402                 "%label     = OpLabel\n"
2403                 "%idval     = OpLoad %uvec3 %id\n"
2404                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2405                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2406                 "%inval     = OpLoad %f32 %inloc\n"
2407                 "%neg       = OpFNegate %f32 %inval\n"
2408                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2409                 "             OpStore %outloc %neg\n"
2410                 "             OpReturn\n"
2411                 "             OpFunctionEnd\n");
2412
2413         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
2414                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
2415         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
2416                                                                                                         "%ten = OpConstant %f32 10.\n"
2417                                                                                                         "%fzero = OpConstant %f32 0.\n"
2418                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
2419                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
2420         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
2421                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
2422                                                                                                         "%fzero = OpConstant %f32 0.\n"
2423                                                                                                         "%one = OpConstant %f32 1.\n"
2424                                                                                                         "%point5 = OpConstant %f32 0.5\n"
2425                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
2426                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
2427                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
2428         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
2429                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
2430                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
2431                                                                                                         "%point5 = OpConstant %f32 0.5\n"
2432                                                                                                         "%one = OpConstant %u32 1\n"
2433                                                                                                         "%ten = OpConstant %i32 10\n"
2434                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
2435                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
2436                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
2437
2438         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2439
2440         for (size_t ndx = 0; ndx < numElements; ++ndx)
2441                 negativeFloats[ndx] = -positiveFloats[ndx];
2442
2443         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2444         {
2445                 map<string, string>             specializations;
2446                 ComputeShaderSpec               spec;
2447
2448                 specializations["CONSTANT"] = cases[caseNdx].param;
2449                 spec.assembly = shaderTemplate.specialize(specializations);
2450                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2451                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2452                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2453
2454                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
2455         }
2456
2457         return group.release();
2458 }
2459
2460 // Creates a floating point number with the given exponent, and significand
2461 // bits set. It can only create normalized numbers. Only the least significant
2462 // 24 bits of the significand will be examined. The final bit of the
2463 // significand will also be ignored. This allows alignment to be written
2464 // similarly to C99 hex-floats.
2465 // For example if you wanted to write 0x1.7f34p-12 you would call
2466 // constructNormalizedFloat(-12, 0x7f3400)
2467 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
2468 {
2469         float f = 1.0f;
2470
2471         for (deInt32 idx = 0; idx < 23; ++idx)
2472         {
2473                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
2474                 significand <<= 1;
2475         }
2476
2477         return std::ldexp(f, exponent);
2478 }
2479
2480 // Compare instruction for the OpQuantizeF16 compute exact case.
2481 // Returns true if the output is what is expected from the test case.
2482 bool compareOpQuantizeF16ComputeExactCase (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
2483 {
2484         if (outputAllocs.size() != 1)
2485                 return false;
2486
2487         // We really just need this for size because we cannot compare Nans.
2488         const BufferSp& expectedOutput  = expectedOutputs[0];
2489         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());;
2490
2491         if (expectedOutput->getNumBytes() != 4*sizeof(float)) {
2492                 return false;
2493         }
2494
2495         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
2496                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
2497                 return false;
2498         }
2499         outputAsFloat++;
2500
2501         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
2502                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
2503                 return false;
2504         }
2505         outputAsFloat++;
2506
2507         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
2508                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
2509                 return false;
2510         }
2511         outputAsFloat++;
2512
2513         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
2514                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
2515                 return false;
2516         }
2517
2518         return true;
2519 }
2520
2521 // Checks that every output from a test-case is a float NaN.
2522 bool compareNan (const std::vector<BufferSp>&, const vector<AllocationSp>& outputAllocs, const std::vector<BufferSp>& expectedOutputs, TestLog&)
2523 {
2524         if (outputAllocs.size() != 1)
2525                 return false;
2526
2527         // We really just need this for size because we cannot compare Nans.
2528         const BufferSp& expectedOutput          = expectedOutputs[0];
2529         const float* output_as_float            = static_cast<const float*>(outputAllocs[0]->getHostPtr());;
2530
2531         for (size_t idx = 0; idx < expectedOutput->getNumBytes() / sizeof(float); ++idx)
2532         {
2533                 if (!deFloatIsNaN(output_as_float[idx]))
2534                 {
2535                         return false;
2536                 }
2537         }
2538
2539         return true;
2540 }
2541
2542 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
2543 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
2544 {
2545         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
2546
2547         const std::string shader (
2548                 string(s_ShaderPreamble) +
2549
2550                 "OpSource GLSL 430\n"
2551                 "OpName %main           \"main\"\n"
2552                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2553
2554                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2555
2556                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
2557
2558                 "%id        = OpVariable %uvec3ptr Input\n"
2559                 "%zero      = OpConstant %i32 0\n"
2560
2561                 "%main      = OpFunction %void None %voidf\n"
2562                 "%label     = OpLabel\n"
2563                 "%idval     = OpLoad %uvec3 %id\n"
2564                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2565                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2566                 "%inval     = OpLoad %f32 %inloc\n"
2567                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
2568                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2569                 "             OpStore %outloc %quant\n"
2570                 "             OpReturn\n"
2571                 "             OpFunctionEnd\n");
2572
2573         {
2574                 ComputeShaderSpec       spec;
2575                 const deUint32          numElements             = 100;
2576                 vector<float>           infinities;
2577                 vector<float>           results;
2578
2579                 infinities.reserve(numElements);
2580                 results.reserve(numElements);
2581
2582                 for (size_t idx = 0; idx < numElements; ++idx)
2583                 {
2584                         switch(idx % 4)
2585                         {
2586                                 case 0:
2587                                         infinities.push_back(std::numeric_limits<float>::infinity());
2588                                         results.push_back(std::numeric_limits<float>::infinity());
2589                                         break;
2590                                 case 1:
2591                                         infinities.push_back(-std::numeric_limits<float>::infinity());
2592                                         results.push_back(-std::numeric_limits<float>::infinity());
2593                                         break;
2594                                 case 2:
2595                                         infinities.push_back(std::ldexp(1.0f, 16));
2596                                         results.push_back(std::numeric_limits<float>::infinity());
2597                                         break;
2598                                 case 3:
2599                                         infinities.push_back(std::ldexp(-1.0f, 32));
2600                                         results.push_back(-std::numeric_limits<float>::infinity());
2601                                         break;
2602                         }
2603                 }
2604
2605                 spec.assembly = shader;
2606                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
2607                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
2608                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2609
2610                 group->addChild(new SpvAsmComputeShaderCase(
2611                         testCtx, "infinities", "Check that infinities propagated and created", spec));
2612         }
2613
2614         {
2615                 ComputeShaderSpec       spec;
2616                 vector<float>           nans;
2617                 const deUint32          numElements             = 100;
2618
2619                 nans.reserve(numElements);
2620
2621                 for (size_t idx = 0; idx < numElements; ++idx)
2622                 {
2623                         if (idx % 2 == 0)
2624                         {
2625                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
2626                         }
2627                         else
2628                         {
2629                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
2630                         }
2631                 }
2632
2633                 spec.assembly = shader;
2634                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
2635                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
2636                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2637                 spec.verifyIO = &compareNan;
2638
2639                 group->addChild(new SpvAsmComputeShaderCase(
2640                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
2641         }
2642
2643         {
2644                 ComputeShaderSpec       spec;
2645                 vector<float>           small;
2646                 vector<float>           zeros;
2647                 const deUint32          numElements             = 100;
2648
2649                 small.reserve(numElements);
2650                 zeros.reserve(numElements);
2651
2652                 for (size_t idx = 0; idx < numElements; ++idx)
2653                 {
2654                         switch(idx % 6)
2655                         {
2656                                 case 0:
2657                                         small.push_back(0.f);
2658                                         zeros.push_back(0.f);
2659                                         break;
2660                                 case 1:
2661                                         small.push_back(-0.f);
2662                                         zeros.push_back(-0.f);
2663                                         break;
2664                                 case 2:
2665                                         small.push_back(std::ldexp(1.0f, -16));
2666                                         zeros.push_back(0.f);
2667                                         break;
2668                                 case 3:
2669                                         small.push_back(std::ldexp(-1.0f, -32));
2670                                         zeros.push_back(-0.f);
2671                                         break;
2672                                 case 4:
2673                                         small.push_back(std::ldexp(1.0f, -127));
2674                                         zeros.push_back(0.f);
2675                                         break;
2676                                 case 5:
2677                                         small.push_back(-std::ldexp(1.0f, -128));
2678                                         zeros.push_back(-0.f);
2679                                         break;
2680                         }
2681                 }
2682
2683                 spec.assembly = shader;
2684                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
2685                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
2686                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2687
2688                 group->addChild(new SpvAsmComputeShaderCase(
2689                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
2690         }
2691
2692         {
2693                 ComputeShaderSpec       spec;
2694                 vector<float>           exact;
2695                 const deUint32          numElements             = 200;
2696
2697                 exact.reserve(numElements);
2698
2699                 for (size_t idx = 0; idx < numElements; ++idx)
2700                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
2701
2702                 spec.assembly = shader;
2703                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
2704                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
2705                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2706
2707                 group->addChild(new SpvAsmComputeShaderCase(
2708                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
2709         }
2710
2711         {
2712                 ComputeShaderSpec       spec;
2713                 vector<float>           inputs;
2714                 const deUint32          numElements             = 4;
2715
2716                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
2717                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
2718                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
2719                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
2720
2721                 spec.assembly = shader;
2722                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
2723                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
2724                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
2725                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2726
2727                 group->addChild(new SpvAsmComputeShaderCase(
2728                         testCtx, "rounded", "Check that are rounded when needed", spec));
2729         }
2730
2731         return group.release();
2732 }
2733
2734 // Performs a bitwise copy of source to the destination type Dest.
2735 template <typename Dest, typename Src>
2736 Dest bitwiseCast(Src source)
2737 {
2738   Dest dest;
2739   DE_STATIC_ASSERT(sizeof(source) == sizeof(dest));
2740   deMemcpy(&dest, &source, sizeof(dest));
2741   return dest;
2742 }
2743
2744 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
2745 {
2746         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
2747
2748         const std::string shader (
2749                 string(s_ShaderPreamble) +
2750
2751                 "OpName %main           \"main\"\n"
2752                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2753
2754                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2755
2756                 "OpDecorate %sc_0  SpecId 0\n"
2757                 "OpDecorate %sc_1  SpecId 1\n"
2758                 "OpDecorate %sc_2  SpecId 2\n"
2759                 "OpDecorate %sc_3  SpecId 3\n"
2760                 "OpDecorate %sc_4  SpecId 4\n"
2761                 "OpDecorate %sc_5  SpecId 5\n"
2762
2763                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
2764
2765                 "%id        = OpVariable %uvec3ptr Input\n"
2766                 "%zero      = OpConstant %i32 0\n"
2767                 "%c_u32_6   = OpConstant %u32 6\n"
2768
2769                 "%sc_0      = OpSpecConstant %f32 0.\n"
2770                 "%sc_1      = OpSpecConstant %f32 0.\n"
2771                 "%sc_2      = OpSpecConstant %f32 0.\n"
2772                 "%sc_3      = OpSpecConstant %f32 0.\n"
2773                 "%sc_4      = OpSpecConstant %f32 0.\n"
2774                 "%sc_5      = OpSpecConstant %f32 0.\n"
2775
2776                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
2777                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
2778                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
2779                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
2780                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
2781                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
2782
2783                 "%main      = OpFunction %void None %voidf\n"
2784                 "%label     = OpLabel\n"
2785                 "%idval     = OpLoad %uvec3 %id\n"
2786                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2787                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2788                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
2789                 "            OpSelectionMerge %exit None\n"
2790                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
2791
2792                 "%case0     = OpLabel\n"
2793                 "             OpStore %outloc %sc_0_quant\n"
2794                 "             OpBranch %exit\n"
2795
2796                 "%case1     = OpLabel\n"
2797                 "             OpStore %outloc %sc_1_quant\n"
2798                 "             OpBranch %exit\n"
2799
2800                 "%case2     = OpLabel\n"
2801                 "             OpStore %outloc %sc_2_quant\n"
2802                 "             OpBranch %exit\n"
2803
2804                 "%case3     = OpLabel\n"
2805                 "             OpStore %outloc %sc_3_quant\n"
2806                 "             OpBranch %exit\n"
2807
2808                 "%case4     = OpLabel\n"
2809                 "             OpStore %outloc %sc_4_quant\n"
2810                 "             OpBranch %exit\n"
2811
2812                 "%case5     = OpLabel\n"
2813                 "             OpStore %outloc %sc_5_quant\n"
2814                 "             OpBranch %exit\n"
2815
2816                 "%exit      = OpLabel\n"
2817                 "             OpReturn\n"
2818
2819                 "             OpFunctionEnd\n");
2820
2821         {
2822                 ComputeShaderSpec       spec;
2823                 const deUint8           numCases        = 4;
2824                 vector<float>           inputs          (numCases, 0.f);
2825                 vector<float>           outputs;
2826
2827                 spec.assembly           = shader;
2828                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
2829
2830                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
2831                 spec.specConstants.push_back(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
2832                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
2833                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
2834
2835                 outputs.push_back(std::numeric_limits<float>::infinity());
2836                 outputs.push_back(-std::numeric_limits<float>::infinity());
2837                 outputs.push_back(std::numeric_limits<float>::infinity());
2838                 outputs.push_back(-std::numeric_limits<float>::infinity());
2839
2840                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
2841                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
2842
2843                 group->addChild(new SpvAsmComputeShaderCase(
2844                         testCtx, "infinities", "Check that infinities propagated and created", spec));
2845         }
2846
2847         {
2848                 ComputeShaderSpec       spec;
2849                 const deUint8           numCases        = 2;
2850                 vector<float>           inputs          (numCases, 0.f);
2851                 vector<float>           outputs;
2852
2853                 spec.assembly           = shader;
2854                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
2855                 spec.verifyIO           = &compareNan;
2856
2857                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
2858                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
2859
2860                 for (deUint8 idx = 0; idx < numCases; ++idx)
2861                         spec.specConstants.push_back(bitwiseCast<deUint32>(outputs[idx]));
2862
2863                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
2864                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
2865
2866                 group->addChild(new SpvAsmComputeShaderCase(
2867                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
2868         }
2869
2870         {
2871                 ComputeShaderSpec       spec;
2872                 const deUint8           numCases        = 6;
2873                 vector<float>           inputs          (numCases, 0.f);
2874                 vector<float>           outputs;
2875
2876                 spec.assembly           = shader;
2877                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
2878
2879                 spec.specConstants.push_back(bitwiseCast<deUint32>(0.f));
2880                 spec.specConstants.push_back(bitwiseCast<deUint32>(-0.f));
2881                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
2882                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
2883                 spec.specConstants.push_back(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
2884                 spec.specConstants.push_back(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
2885
2886                 outputs.push_back(0.f);
2887                 outputs.push_back(-0.f);
2888                 outputs.push_back(0.f);
2889                 outputs.push_back(-0.f);
2890                 outputs.push_back(0.f);
2891                 outputs.push_back(-0.f);
2892
2893                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
2894                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
2895
2896                 group->addChild(new SpvAsmComputeShaderCase(
2897                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
2898         }
2899
2900         {
2901                 ComputeShaderSpec       spec;
2902                 const deUint8           numCases        = 6;
2903                 vector<float>           inputs          (numCases, 0.f);
2904                 vector<float>           outputs;
2905
2906                 spec.assembly           = shader;
2907                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
2908
2909                 for (deUint8 idx = 0; idx < 6; ++idx)
2910                 {
2911                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
2912                         spec.specConstants.push_back(bitwiseCast<deUint32>(f));
2913                         outputs.push_back(f);
2914                 }
2915
2916                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
2917                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
2918
2919                 group->addChild(new SpvAsmComputeShaderCase(
2920                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
2921         }
2922
2923         {
2924                 ComputeShaderSpec       spec;
2925                 const deUint8           numCases        = 4;
2926                 vector<float>           inputs          (numCases, 0.f);
2927                 vector<float>           outputs;
2928
2929                 spec.assembly           = shader;
2930                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
2931                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
2932
2933                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
2934                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
2935                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
2936                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
2937
2938                 for (deUint8 idx = 0; idx < numCases; ++idx)
2939                         spec.specConstants.push_back(bitwiseCast<deUint32>(outputs[idx]));
2940
2941                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
2942                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
2943
2944                 group->addChild(new SpvAsmComputeShaderCase(
2945                         testCtx, "rounded", "Check that are rounded when needed", spec));
2946         }
2947
2948         return group.release();
2949 }
2950
2951 // Checks that constant null/composite values can be used in computation.
2952 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
2953 {
2954         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
2955         ComputeShaderSpec                               spec;
2956         de::Random                                              rnd                             (deStringHash(group->getName()));
2957         const int                                               numElements             = 100;
2958         vector<float>                                   positiveFloats  (numElements, 0);
2959         vector<float>                                   negativeFloats  (numElements, 0);
2960
2961         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2962
2963         for (size_t ndx = 0; ndx < numElements; ++ndx)
2964                 negativeFloats[ndx] = -positiveFloats[ndx];
2965
2966         spec.assembly =
2967                 "OpCapability Shader\n"
2968                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
2969                 "OpMemoryModel Logical GLSL450\n"
2970                 "OpEntryPoint GLCompute %main \"main\" %id\n"
2971                 "OpExecutionMode %main LocalSize 1 1 1\n"
2972
2973                 "OpSource GLSL 430\n"
2974                 "OpName %main           \"main\"\n"
2975                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2976
2977                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2978
2979                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) +
2980
2981                 "%fmat      = OpTypeMatrix %fvec3 3\n"
2982                 "%ten       = OpConstant %u32 10\n"
2983                 "%f32arr10  = OpTypeArray %f32 %ten\n"
2984                 "%fst       = OpTypeStruct %f32 %f32\n"
2985
2986                 + string(s_InputOutputBuffer) +
2987
2988                 "%id        = OpVariable %uvec3ptr Input\n"
2989                 "%zero      = OpConstant %i32 0\n"
2990
2991                 // Create a bunch of null values
2992                 "%unull     = OpConstantNull %u32\n"
2993                 "%fnull     = OpConstantNull %f32\n"
2994                 "%vnull     = OpConstantNull %fvec3\n"
2995                 "%mnull     = OpConstantNull %fmat\n"
2996                 "%anull     = OpConstantNull %f32arr10\n"
2997                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
2998
2999                 "%main      = OpFunction %void None %voidf\n"
3000                 "%label     = OpLabel\n"
3001                 "%idval     = OpLoad %uvec3 %id\n"
3002                 "%x         = OpCompositeExtract %u32 %idval 0\n"
3003                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
3004                 "%inval     = OpLoad %f32 %inloc\n"
3005                 "%neg       = OpFNegate %f32 %inval\n"
3006
3007                 // Get the abs() of (a certain element of) those null values
3008                 "%unull_cov = OpConvertUToF %f32 %unull\n"
3009                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
3010                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
3011                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
3012                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
3013                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
3014                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
3015                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
3016                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
3017                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
3018                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
3019
3020                 // Add them all
3021                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
3022                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
3023                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
3024                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
3025                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
3026                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
3027
3028                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
3029                 "             OpStore %outloc %final\n" // write to output
3030                 "             OpReturn\n"
3031                 "             OpFunctionEnd\n";
3032         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
3033         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
3034         spec.numWorkGroups = IVec3(numElements, 1, 1);
3035
3036         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
3037
3038         return group.release();
3039 }
3040
3041 // Assembly code used for testing loop control is based on GLSL source code:
3042 // #version 430
3043 //
3044 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3045 //   float elements[];
3046 // } input_data;
3047 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3048 //   float elements[];
3049 // } output_data;
3050 //
3051 // void main() {
3052 //   uint x = gl_GlobalInvocationID.x;
3053 //   output_data.elements[x] = input_data.elements[x];
3054 //   for (uint i = 0; i < 4; ++i)
3055 //     output_data.elements[x] += 1.f;
3056 // }
3057 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
3058 {
3059         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
3060         vector<CaseParameter>                   cases;
3061         de::Random                                              rnd                             (deStringHash(group->getName()));
3062         const int                                               numElements             = 100;
3063         vector<float>                                   inputFloats             (numElements, 0);
3064         vector<float>                                   outputFloats    (numElements, 0);
3065         const StringTemplate                    shaderTemplate  (
3066                 string(s_ShaderPreamble) +
3067
3068                 "OpSource GLSL 430\n"
3069                 "OpName %main \"main\"\n"
3070                 "OpName %id \"gl_GlobalInvocationID\"\n"
3071
3072                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3073
3074                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
3075
3076                 "%u32ptr      = OpTypePointer Function %u32\n"
3077
3078                 "%id          = OpVariable %uvec3ptr Input\n"
3079                 "%zero        = OpConstant %i32 0\n"
3080                 "%uzero       = OpConstant %u32 0\n"
3081                 "%one         = OpConstant %i32 1\n"
3082                 "%constf1     = OpConstant %f32 1.0\n"
3083                 "%four        = OpConstant %u32 4\n"
3084
3085                 "%main        = OpFunction %void None %voidf\n"
3086                 "%entry       = OpLabel\n"
3087                 "%i           = OpVariable %u32ptr Function\n"
3088                 "               OpStore %i %uzero\n"
3089
3090                 "%idval       = OpLoad %uvec3 %id\n"
3091                 "%x           = OpCompositeExtract %u32 %idval 0\n"
3092                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
3093                 "%inval       = OpLoad %f32 %inloc\n"
3094                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
3095                 "               OpStore %outloc %inval\n"
3096                 "               OpBranch %loop_entry\n"
3097
3098                 "%loop_entry  = OpLabel\n"
3099                 "%i_val       = OpLoad %u32 %i\n"
3100                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
3101                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
3102                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
3103                 "%loop_body   = OpLabel\n"
3104                 "%outval      = OpLoad %f32 %outloc\n"
3105                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
3106                 "               OpStore %outloc %addf1\n"
3107                 "%new_i       = OpIAdd %u32 %i_val %one\n"
3108                 "               OpStore %i %new_i\n"
3109                 "               OpBranch %loop_entry\n"
3110                 "%loop_merge  = OpLabel\n"
3111                 "               OpReturn\n"
3112                 "               OpFunctionEnd\n");
3113
3114         cases.push_back(CaseParameter("none",                           "None"));
3115         cases.push_back(CaseParameter("unroll",                         "Unroll"));
3116         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
3117         cases.push_back(CaseParameter("unroll_dont_unroll",     "Unroll|DontUnroll"));
3118
3119         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3120
3121         for (size_t ndx = 0; ndx < numElements; ++ndx)
3122                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
3123
3124         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
3125         {
3126                 map<string, string>             specializations;
3127                 ComputeShaderSpec               spec;
3128
3129                 specializations["CONTROL"] = cases[caseNdx].param;
3130                 spec.assembly = shaderTemplate.specialize(specializations);
3131                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3132                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3133                 spec.numWorkGroups = IVec3(numElements, 1, 1);
3134
3135                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
3136         }
3137
3138         return group.release();
3139 }
3140
3141 // Assembly code used for testing selection control is based on GLSL source code:
3142 // #version 430
3143 //
3144 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3145 //   float elements[];
3146 // } input_data;
3147 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3148 //   float elements[];
3149 // } output_data;
3150 //
3151 // void main() {
3152 //   uint x = gl_GlobalInvocationID.x;
3153 //   float val = input_data.elements[x];
3154 //   if (val > 10.f)
3155 //     output_data.elements[x] = val + 1.f;
3156 //   else
3157 //     output_data.elements[x] = val - 1.f;
3158 // }
3159 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
3160 {
3161         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
3162         vector<CaseParameter>                   cases;
3163         de::Random                                              rnd                             (deStringHash(group->getName()));
3164         const int                                               numElements             = 100;
3165         vector<float>                                   inputFloats             (numElements, 0);
3166         vector<float>                                   outputFloats    (numElements, 0);
3167         const StringTemplate                    shaderTemplate  (
3168                 string(s_ShaderPreamble) +
3169
3170                 "OpSource GLSL 430\n"
3171                 "OpName %main \"main\"\n"
3172                 "OpName %id \"gl_GlobalInvocationID\"\n"
3173
3174                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3175
3176                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
3177
3178                 "%id       = OpVariable %uvec3ptr Input\n"
3179                 "%zero     = OpConstant %i32 0\n"
3180                 "%constf1  = OpConstant %f32 1.0\n"
3181                 "%constf10 = OpConstant %f32 10.0\n"
3182
3183                 "%main     = OpFunction %void None %voidf\n"
3184                 "%entry    = OpLabel\n"
3185                 "%idval    = OpLoad %uvec3 %id\n"
3186                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3187                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3188                 "%inval    = OpLoad %f32 %inloc\n"
3189                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3190                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
3191
3192                 "            OpSelectionMerge %if_end ${CONTROL}\n"
3193                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
3194                 "%if_true  = OpLabel\n"
3195                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
3196                 "            OpStore %outloc %addf1\n"
3197                 "            OpBranch %if_end\n"
3198                 "%if_false = OpLabel\n"
3199                 "%subf1    = OpFSub %f32 %inval %constf1\n"
3200                 "            OpStore %outloc %subf1\n"
3201                 "            OpBranch %if_end\n"
3202                 "%if_end   = OpLabel\n"
3203                 "            OpReturn\n"
3204                 "            OpFunctionEnd\n");
3205
3206         cases.push_back(CaseParameter("none",                                   "None"));
3207         cases.push_back(CaseParameter("flatten",                                "Flatten"));
3208         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
3209         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
3210
3211         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3212
3213         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3214         floorAll(inputFloats);
3215
3216         for (size_t ndx = 0; ndx < numElements; ++ndx)
3217                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
3218
3219         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
3220         {
3221                 map<string, string>             specializations;
3222                 ComputeShaderSpec               spec;
3223
3224                 specializations["CONTROL"] = cases[caseNdx].param;
3225                 spec.assembly = shaderTemplate.specialize(specializations);
3226                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3227                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3228                 spec.numWorkGroups = IVec3(numElements, 1, 1);
3229
3230                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
3231         }
3232
3233         return group.release();
3234 }
3235
3236 // Assembly code used for testing function control is based on GLSL source code:
3237 //
3238 // #version 430
3239 //
3240 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3241 //   float elements[];
3242 // } input_data;
3243 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3244 //   float elements[];
3245 // } output_data;
3246 //
3247 // float const10() { return 10.f; }
3248 //
3249 // void main() {
3250 //   uint x = gl_GlobalInvocationID.x;
3251 //   output_data.elements[x] = input_data.elements[x] + const10();
3252 // }
3253 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
3254 {
3255         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
3256         vector<CaseParameter>                   cases;
3257         de::Random                                              rnd                             (deStringHash(group->getName()));
3258         const int                                               numElements             = 100;
3259         vector<float>                                   inputFloats             (numElements, 0);
3260         vector<float>                                   outputFloats    (numElements, 0);
3261         const StringTemplate                    shaderTemplate  (
3262                 string(s_ShaderPreamble) +
3263
3264                 "OpSource GLSL 430\n"
3265                 "OpName %main \"main\"\n"
3266                 "OpName %func_const10 \"const10(\"\n"
3267                 "OpName %id \"gl_GlobalInvocationID\"\n"
3268
3269                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3270
3271                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
3272
3273                 "%f32f = OpTypeFunction %f32\n"
3274                 "%id = OpVariable %uvec3ptr Input\n"
3275                 "%zero = OpConstant %i32 0\n"
3276                 "%constf10 = OpConstant %f32 10.0\n"
3277
3278                 "%main         = OpFunction %void None %voidf\n"
3279                 "%entry        = OpLabel\n"
3280                 "%idval        = OpLoad %uvec3 %id\n"
3281                 "%x            = OpCompositeExtract %u32 %idval 0\n"
3282                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
3283                 "%inval        = OpLoad %f32 %inloc\n"
3284                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
3285                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
3286                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
3287                 "                OpStore %outloc %fadd\n"
3288                 "                OpReturn\n"
3289                 "                OpFunctionEnd\n"
3290
3291                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
3292                 "%label        = OpLabel\n"
3293                 "                OpReturnValue %constf10\n"
3294                 "                OpFunctionEnd\n");
3295
3296         cases.push_back(CaseParameter("none",                                           "None"));
3297         cases.push_back(CaseParameter("inline",                                         "Inline"));
3298         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
3299         cases.push_back(CaseParameter("pure",                                           "Pure"));
3300         cases.push_back(CaseParameter("const",                                          "Const"));
3301         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
3302         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
3303         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
3304         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
3305
3306         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3307
3308         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3309         floorAll(inputFloats);
3310
3311         for (size_t ndx = 0; ndx < numElements; ++ndx)
3312                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
3313
3314         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
3315         {
3316                 map<string, string>             specializations;
3317                 ComputeShaderSpec               spec;
3318
3319                 specializations["CONTROL"] = cases[caseNdx].param;
3320                 spec.assembly = shaderTemplate.specialize(specializations);
3321                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3322                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3323                 spec.numWorkGroups = IVec3(numElements, 1, 1);
3324
3325                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
3326         }
3327
3328         return group.release();
3329 }
3330
3331 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
3332 {
3333         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
3334         vector<CaseParameter>                   cases;
3335         de::Random                                              rnd                             (deStringHash(group->getName()));
3336         const int                                               numElements             = 100;
3337         vector<float>                                   inputFloats             (numElements, 0);
3338         vector<float>                                   outputFloats    (numElements, 0);
3339         const StringTemplate                    shaderTemplate  (
3340                 string(s_ShaderPreamble) +
3341
3342                 "OpSource GLSL 430\n"
3343                 "OpName %main           \"main\"\n"
3344                 "OpName %id             \"gl_GlobalInvocationID\"\n"
3345
3346                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3347
3348                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
3349
3350                 "%f32ptr_f  = OpTypePointer Function %f32\n"
3351
3352                 "%id        = OpVariable %uvec3ptr Input\n"
3353                 "%zero      = OpConstant %i32 0\n"
3354                 "%four      = OpConstant %i32 4\n"
3355
3356                 "%main      = OpFunction %void None %voidf\n"
3357                 "%label     = OpLabel\n"
3358                 "%copy      = OpVariable %f32ptr_f Function\n"
3359                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
3360                 "%x         = OpCompositeExtract %u32 %idval 0\n"
3361                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
3362                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
3363                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
3364                 "%val1      = OpLoad %f32 %copy\n"
3365                 "%val2      = OpLoad %f32 %inloc\n"
3366                 "%add       = OpFAdd %f32 %val1 %val2\n"
3367                 "             OpStore %outloc %add ${ACCESS}\n"
3368                 "             OpReturn\n"
3369                 "             OpFunctionEnd\n");
3370
3371         cases.push_back(CaseParameter("null",                                   ""));
3372         cases.push_back(CaseParameter("none",                                   "None"));
3373         cases.push_back(CaseParameter("volatile",                               "Volatile"));
3374         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
3375         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
3376         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
3377         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
3378
3379         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3380
3381         for (size_t ndx = 0; ndx < numElements; ++ndx)
3382                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
3383
3384         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
3385         {
3386                 map<string, string>             specializations;
3387                 ComputeShaderSpec               spec;
3388
3389                 specializations["ACCESS"] = cases[caseNdx].param;
3390                 spec.assembly = shaderTemplate.specialize(specializations);
3391                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3392                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3393                 spec.numWorkGroups = IVec3(numElements, 1, 1);
3394
3395                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
3396         }
3397
3398         return group.release();
3399 }
3400
3401 // Checks that we can get undefined values for various types, without exercising a computation with it.
3402 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
3403 {
3404         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
3405         vector<CaseParameter>                   cases;
3406         de::Random                                              rnd                             (deStringHash(group->getName()));
3407         const int                                               numElements             = 100;
3408         vector<float>                                   positiveFloats  (numElements, 0);
3409         vector<float>                                   negativeFloats  (numElements, 0);
3410         const StringTemplate                    shaderTemplate  (
3411                 string(s_ShaderPreamble) +
3412
3413                 "OpSource GLSL 430\n"
3414                 "OpName %main           \"main\"\n"
3415                 "OpName %id             \"gl_GlobalInvocationID\"\n"
3416
3417                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3418
3419                 + string(s_InputOutputBufferTraits) + string(s_CommonTypes) + string(s_InputOutputBuffer) +
3420
3421                 "${TYPE}\n"
3422
3423                 "%id        = OpVariable %uvec3ptr Input\n"
3424                 "%zero      = OpConstant %i32 0\n"
3425
3426                 "%main      = OpFunction %void None %voidf\n"
3427                 "%label     = OpLabel\n"
3428
3429                 "%undef     = OpUndef %type\n"
3430
3431                 "%idval     = OpLoad %uvec3 %id\n"
3432                 "%x         = OpCompositeExtract %u32 %idval 0\n"
3433
3434                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
3435                 "%inval     = OpLoad %f32 %inloc\n"
3436                 "%neg       = OpFNegate %f32 %inval\n"
3437                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
3438                 "             OpStore %outloc %neg\n"
3439                 "             OpReturn\n"
3440                 "             OpFunctionEnd\n");
3441
3442         cases.push_back(CaseParameter("bool",                   "%type = OpTypeBool"));
3443         cases.push_back(CaseParameter("sint32",                 "%type = OpTypeInt 32 1"));
3444         cases.push_back(CaseParameter("uint32",                 "%type = OpTypeInt 32 0"));
3445         cases.push_back(CaseParameter("float32",                "%type = OpTypeFloat 32"));
3446         cases.push_back(CaseParameter("vec4float32",    "%type = OpTypeVector %f32 4"));
3447         cases.push_back(CaseParameter("vec2uint32",             "%type = OpTypeVector %u32 2"));
3448         cases.push_back(CaseParameter("matrix",                 "%type = OpTypeMatrix %fvec3 3"));
3449         cases.push_back(CaseParameter("image",                  "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown"));
3450         cases.push_back(CaseParameter("sampler",                "%type = OpTypeSampler"));
3451         cases.push_back(CaseParameter("sampledimage",   "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
3452                                                                                                         "%type = OpTypeSampledImage %img"));
3453         cases.push_back(CaseParameter("array",                  "%100 = OpConstant %u32 100\n"
3454                                                                                                         "%type = OpTypeArray %i32 %100"));
3455         cases.push_back(CaseParameter("runtimearray",   "%type = OpTypeRuntimeArray %f32"));
3456         cases.push_back(CaseParameter("struct",                 "%type = OpTypeStruct %f32 %i32 %u32"));
3457         cases.push_back(CaseParameter("pointer",                "%type = OpTypePointer Function %i32"));
3458
3459         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
3460
3461         for (size_t ndx = 0; ndx < numElements; ++ndx)
3462                 negativeFloats[ndx] = -positiveFloats[ndx];
3463
3464         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
3465         {
3466                 map<string, string>             specializations;
3467                 ComputeShaderSpec               spec;
3468
3469                 specializations["TYPE"] = cases[caseNdx].param;
3470                 spec.assembly = shaderTemplate.specialize(specializations);
3471                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
3472                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
3473                 spec.numWorkGroups = IVec3(numElements, 1, 1);
3474
3475                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
3476         }
3477
3478                 return group.release();
3479 }
3480 typedef std::pair<std::string, VkShaderStageFlagBits>   EntryToStage;
3481 typedef map<string, vector<EntryToStage> >                              ModuleMap;
3482 typedef map<VkShaderStageFlagBits, vector<deInt32> >    StageToSpecConstantMap;
3483
3484 // Context for a specific test instantiation. For example, an instantiation
3485 // may test colors yellow/magenta/cyan/mauve in a tesselation shader
3486 // with an entry point named 'main_to_the_main'
3487 struct InstanceContext
3488 {
3489         // Map of modules to what entry_points we care to use from those modules.
3490         ModuleMap                               moduleMap;
3491         RGBA                                    inputColors[4];
3492         RGBA                                    outputColors[4];
3493         // Concrete SPIR-V code to test via boilerplate specialization.
3494         map<string, string>             testCodeFragments;
3495         StageToSpecConstantMap  specConstants;
3496         bool                                    hasTessellation;
3497         VkShaderStageFlagBits   requiredStages;
3498
3499         InstanceContext (const RGBA (&inputs)[4], const RGBA (&outputs)[4], const map<string, string>& testCodeFragments_, const StageToSpecConstantMap& specConstants_)
3500                 : testCodeFragments             (testCodeFragments_)
3501                 , specConstants                 (specConstants_)
3502                 , hasTessellation               (false)
3503                 , requiredStages                (static_cast<VkShaderStageFlagBits>(0))
3504         {
3505                 inputColors[0]          = inputs[0];
3506                 inputColors[1]          = inputs[1];
3507                 inputColors[2]          = inputs[2];
3508                 inputColors[3]          = inputs[3];
3509
3510                 outputColors[0]         = outputs[0];
3511                 outputColors[1]         = outputs[1];
3512                 outputColors[2]         = outputs[2];
3513                 outputColors[3]         = outputs[3];
3514         }
3515
3516         InstanceContext (const InstanceContext& other)
3517                 : moduleMap                     (other.moduleMap)
3518                 , testCodeFragments     (other.testCodeFragments)
3519                 , specConstants         (other.specConstants)
3520                 , hasTessellation       (other.hasTessellation)
3521                 , requiredStages    (other.requiredStages)
3522         {
3523                 inputColors[0]          = other.inputColors[0];
3524                 inputColors[1]          = other.inputColors[1];
3525                 inputColors[2]          = other.inputColors[2];
3526                 inputColors[3]          = other.inputColors[3];
3527
3528                 outputColors[0]         = other.outputColors[0];
3529                 outputColors[1]         = other.outputColors[1];
3530                 outputColors[2]         = other.outputColors[2];
3531                 outputColors[3]         = other.outputColors[3];
3532         }
3533 };
3534
3535 // A description of a shader to be used for a single stage of the graphics pipeline.
3536 struct ShaderElement
3537 {
3538         // The module that contains this shader entrypoint.
3539         string                                  moduleName;
3540
3541         // The name of the entrypoint.
3542         string                                  entryName;
3543
3544         // Which shader stage this entry point represents.
3545         VkShaderStageFlagBits   stage;
3546
3547         ShaderElement (const string& moduleName_, const string& entryPoint_, VkShaderStageFlagBits shaderStage_)
3548                 : moduleName(moduleName_)
3549                 , entryName(entryPoint_)
3550                 , stage(shaderStage_)
3551         {
3552         }
3553 };
3554
3555 void getDefaultColors (RGBA (&colors)[4])
3556 {
3557         colors[0] = RGBA::white();
3558         colors[1] = RGBA::red();
3559         colors[2] = RGBA::green();
3560         colors[3] = RGBA::blue();
3561 }
3562
3563 void getHalfColorsFullAlpha (RGBA (&colors)[4])
3564 {
3565         colors[0] = RGBA(127, 127, 127, 255);
3566         colors[1] = RGBA(127, 0,   0,   255);
3567         colors[2] = RGBA(0,       127, 0,       255);
3568         colors[3] = RGBA(0,       0,   127, 255);
3569 }
3570
3571 void getInvertedDefaultColors (RGBA (&colors)[4])
3572 {
3573         colors[0] = RGBA(0,             0,              0,              255);
3574         colors[1] = RGBA(0,             255,    255,    255);
3575         colors[2] = RGBA(255,   0,              255,    255);
3576         colors[3] = RGBA(255,   255,    0,              255);
3577 }
3578
3579 // Turns a statically sized array of ShaderElements into an instance-context
3580 // by setting up the mapping of modules to their contained shaders and stages.
3581 // The inputs and expected outputs are given by inputColors and outputColors
3582 template<size_t N>
3583 InstanceContext createInstanceContext (const ShaderElement (&elements)[N], const RGBA (&inputColors)[4], const RGBA (&outputColors)[4], const map<string, string>& testCodeFragments, const StageToSpecConstantMap& specConstants)
3584 {
3585         InstanceContext ctx (inputColors, outputColors, testCodeFragments, specConstants);
3586         for (size_t i = 0; i < N; ++i)
3587         {
3588                 ctx.moduleMap[elements[i].moduleName].push_back(std::make_pair(elements[i].entryName, elements[i].stage));
3589                 ctx.requiredStages = static_cast<VkShaderStageFlagBits>(ctx.requiredStages | elements[i].stage);
3590         }
3591         return ctx;
3592 }
3593
3594 template<size_t N>
3595 inline InstanceContext createInstanceContext (const ShaderElement (&elements)[N], RGBA (&inputColors)[4], const RGBA (&outputColors)[4], const map<string, string>& testCodeFragments)
3596 {
3597         return createInstanceContext(elements, inputColors, outputColors, testCodeFragments, StageToSpecConstantMap());
3598 }
3599
3600 // The same as createInstanceContext above, but with default colors.
3601 template<size_t N>
3602 InstanceContext createInstanceContext (const ShaderElement (&elements)[N], const map<string, string>& testCodeFragments)
3603 {
3604         RGBA defaultColors[4];
3605         getDefaultColors(defaultColors);
3606         return createInstanceContext(elements, defaultColors, defaultColors, testCodeFragments);
3607 }
3608
3609 // For the current InstanceContext, constructs the required modules and shader stage create infos.
3610 void createPipelineShaderStages (const DeviceInterface& vk, const VkDevice vkDevice, InstanceContext& instance, Context& context, vector<ModuleHandleSp>& modules, vector<VkPipelineShaderStageCreateInfo>& createInfos)
3611 {
3612         for (ModuleMap::const_iterator moduleNdx = instance.moduleMap.begin(); moduleNdx != instance.moduleMap.end(); ++moduleNdx)
3613         {
3614                 const ModuleHandleSp mod(new Unique<VkShaderModule>(createShaderModule(vk, vkDevice, context.getBinaryCollection().get(moduleNdx->first), 0)));
3615                 modules.push_back(ModuleHandleSp(mod));
3616                 for (vector<EntryToStage>::const_iterator shaderNdx = moduleNdx->second.begin(); shaderNdx != moduleNdx->second.end(); ++shaderNdx)
3617                 {
3618                         const EntryToStage&                                             stage                   = *shaderNdx;
3619                         const VkPipelineShaderStageCreateInfo   shaderParam             =
3620                         {
3621                                 VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,    //      VkStructureType                 sType;
3622                                 DE_NULL,                                                                                                //      const void*                             pNext;
3623                                 (VkPipelineShaderStageCreateFlags)0,
3624                                 stage.second,                                                                                   //      VkShaderStageFlagBits   stage;
3625                                 **modules.back(),                                                                               //      VkShaderModule                  module;
3626                                 stage.first.c_str(),                                                                    //      const char*                             pName;
3627                                 (const VkSpecializationInfo*)DE_NULL,
3628                         };
3629                         createInfos.push_back(shaderParam);
3630                 }
3631         }
3632 }
3633
3634 #define SPIRV_ASSEMBLY_TYPES                                                                                                                                    \
3635         "%void = OpTypeVoid\n"                                                                                                                                          \
3636         "%bool = OpTypeBool\n"                                                                                                                                          \
3637                                                                                                                                                                                                 \
3638         "%i32 = OpTypeInt 32 1\n"                                                                                                                                       \
3639         "%u32 = OpTypeInt 32 0\n"                                                                                                                                       \
3640                                                                                                                                                                                                 \
3641         "%f32 = OpTypeFloat 32\n"                                                                                                                                       \
3642         "%v3f32 = OpTypeVector %f32 3\n"                                                                                                                        \
3643         "%v4f32 = OpTypeVector %f32 4\n"                                                                                                                        \
3644         "%v4bool = OpTypeVector %bool 4\n"                                                                                                                      \
3645                                                                                                                                                                                                 \
3646         "%v4f32_function = OpTypeFunction %v4f32 %v4f32\n"                                                                                      \
3647         "%fun = OpTypeFunction %void\n"                                                                                                                         \
3648                                                                                                                                                                                                 \
3649         "%ip_f32 = OpTypePointer Input %f32\n"                                                                                                          \
3650         "%ip_i32 = OpTypePointer Input %i32\n"                                                                                                          \
3651         "%ip_v3f32 = OpTypePointer Input %v3f32\n"                                                                                                      \
3652         "%ip_v4f32 = OpTypePointer Input %v4f32\n"                                                                                                      \
3653                                                                                                                                                                                                 \
3654         "%op_f32 = OpTypePointer Output %f32\n"                                                                                                         \
3655         "%op_v4f32 = OpTypePointer Output %v4f32\n"                                                                                                     \
3656                                                                                                                                                                                                 \
3657         "%fp_f32   = OpTypePointer Function %f32\n"                                                                                                     \
3658         "%fp_i32   = OpTypePointer Function %i32\n"                                                                                                     \
3659         "%fp_v4f32 = OpTypePointer Function %v4f32\n"
3660
3661 #define SPIRV_ASSEMBLY_CONSTANTS                                                                                                                                \
3662         "%c_f32_1 = OpConstant %f32 1.0\n"                                                                                                                      \
3663         "%c_f32_0 = OpConstant %f32 0.0\n"                                                                                                                      \
3664         "%c_f32_0_5 = OpConstant %f32 0.5\n"                                                                                                            \
3665         "%c_f32_n1  = OpConstant %f32 -1.\n"                                                                                                            \
3666         "%c_f32_7 = OpConstant %f32 7.0\n"                                                                                                                      \
3667         "%c_f32_8 = OpConstant %f32 8.0\n"                                                                                                                      \
3668         "%c_i32_0 = OpConstant %i32 0\n"                                                                                                                        \
3669         "%c_i32_1 = OpConstant %i32 1\n"                                                                                                                        \
3670         "%c_i32_2 = OpConstant %i32 2\n"                                                                                                                        \
3671         "%c_i32_3 = OpConstant %i32 3\n"                                                                                                                        \
3672         "%c_i32_4 = OpConstant %i32 4\n"                                                                                                                        \
3673         "%c_u32_0 = OpConstant %u32 0\n"                                                                                                                        \
3674         "%c_u32_1 = OpConstant %u32 1\n"                                                                                                                        \
3675         "%c_u32_2 = OpConstant %u32 2\n"                                                                                                                        \
3676         "%c_u32_3 = OpConstant %u32 3\n"                                                                                                                        \
3677         "%c_u32_32 = OpConstant %u32 32\n"                                                                                                                      \
3678         "%c_u32_4 = OpConstant %u32 4\n"                                                                                                                        \
3679         "%c_u32_31_bits = OpConstant %u32 0x7FFFFFFF\n"                                                                                         \
3680         "%c_v4f32_1_1_1_1 = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"           \
3681         "%c_v4f32_1_0_0_1 = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_1\n"           \
3682         "%c_v4f32_0_5_0_5_0_5_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5\n"
3683
3684 #define SPIRV_ASSEMBLY_ARRAYS                                                                                                                                   \
3685         "%a1f32 = OpTypeArray %f32 %c_u32_1\n"                                                                                                          \
3686         "%a2f32 = OpTypeArray %f32 %c_u32_2\n"                                                                                                          \
3687         "%a3v4f32 = OpTypeArray %v4f32 %c_u32_3\n"                                                                                                      \
3688         "%a4f32 = OpTypeArray %f32 %c_u32_4\n"                                                                                                          \
3689         "%a32v4f32 = OpTypeArray %v4f32 %c_u32_32\n"                                                                                            \
3690         "%ip_a3v4f32 = OpTypePointer Input %a3v4f32\n"                                                                                          \
3691         "%ip_a32v4f32 = OpTypePointer Input %a32v4f32\n"                                                                                        \
3692         "%op_a2f32 = OpTypePointer Output %a2f32\n"                                                                                                     \
3693         "%op_a3v4f32 = OpTypePointer Output %a3v4f32\n"                                                                                         \
3694         "%op_a4f32 = OpTypePointer Output %a4f32\n"
3695
3696 // Creates vertex-shader assembly by specializing a boilerplate StringTemplate
3697 // on fragments, which must (at least) map "testfun" to an OpFunction definition
3698 // for %test_code that takes and returns a %v4f32.  Boilerplate IDs are prefixed
3699 // with "BP_" to avoid collisions with fragments.
3700 //
3701 // It corresponds roughly to this GLSL:
3702 //;
3703 // layout(location = 0) in vec4 position;
3704 // layout(location = 1) in vec4 color;
3705 // layout(location = 1) out highp vec4 vtxColor;
3706 // void main (void) { gl_Position = position; vtxColor = test_func(color); }
3707 string makeVertexShaderAssembly(const map<string, string>& fragments)
3708 {
3709 // \todo [2015-11-23 awoloszyn] Remove OpName once these have stabalized
3710         static const char vertexShaderBoilerplate[] =
3711                 "OpCapability Shader\n"
3712                 "OpCapability ClipDistance\n"
3713                 "OpCapability CullDistance\n"
3714                 "OpMemoryModel Logical GLSL450\n"
3715                 "OpEntryPoint Vertex %main \"main\" %BP_stream %BP_position %BP_vtx_color %BP_color %BP_gl_VertexIndex %BP_gl_InstanceIndex\n"
3716                 "${debug:opt}\n"
3717                 "OpName %main \"main\"\n"
3718                 "OpName %BP_gl_PerVertex \"gl_PerVertex\"\n"
3719                 "OpMemberName %BP_gl_PerVertex 0 \"gl_Position\"\n"
3720                 "OpMemberName %BP_gl_PerVertex 1 \"gl_PointSize\"\n"
3721                 "OpMemberName %BP_gl_PerVertex 2 \"gl_ClipDistance\"\n"
3722                 "OpMemberName %BP_gl_PerVertex 3 \"gl_CullDistance\"\n"
3723                 "OpName %test_code \"testfun(vf4;\"\n"
3724                 "OpName %BP_stream \"\"\n"
3725                 "OpName %BP_position \"position\"\n"
3726                 "OpName %BP_vtx_color \"vtxColor\"\n"
3727                 "OpName %BP_color \"color\"\n"
3728                 "OpName %BP_gl_VertexIndex \"gl_VertexIndex\"\n"
3729                 "OpName %BP_gl_InstanceIndex \"gl_InstanceIndex\"\n"
3730                 "OpMemberDecorate %BP_gl_PerVertex 0 BuiltIn Position\n"
3731                 "OpMemberDecorate %BP_gl_PerVertex 1 BuiltIn PointSize\n"
3732                 "OpMemberDecorate %BP_gl_PerVertex 2 BuiltIn ClipDistance\n"
3733                 "OpMemberDecorate %BP_gl_PerVertex 3 BuiltIn CullDistance\n"
3734                 "OpDecorate %BP_gl_PerVertex Block\n"
3735                 "OpDecorate %BP_position Location 0\n"
3736                 "OpDecorate %BP_vtx_color Location 1\n"
3737                 "OpDecorate %BP_color Location 1\n"
3738                 "OpDecorate %BP_gl_VertexIndex BuiltIn VertexIndex\n"
3739                 "OpDecorate %BP_gl_InstanceIndex BuiltIn InstanceIndex\n"
3740                 "${decoration:opt}\n"
3741                 SPIRV_ASSEMBLY_TYPES
3742                 SPIRV_ASSEMBLY_CONSTANTS
3743                 SPIRV_ASSEMBLY_ARRAYS
3744                 "%BP_gl_PerVertex = OpTypeStruct %v4f32 %f32 %a1f32 %a1f32\n"
3745                 "%BP_op_gl_PerVertex = OpTypePointer Output %BP_gl_PerVertex\n"
3746                 "%BP_stream = OpVariable %BP_op_gl_PerVertex Output\n"
3747                 "%BP_position = OpVariable %ip_v4f32 Input\n"
3748                 "%BP_vtx_color = OpVariable %op_v4f32 Output\n"
3749                 "%BP_color = OpVariable %ip_v4f32 Input\n"
3750                 "%BP_gl_VertexIndex = OpVariable %ip_i32 Input\n"
3751                 "%BP_gl_InstanceIndex = OpVariable %ip_i32 Input\n"
3752                 "${pre_main:opt}\n"
3753                 "%main = OpFunction %void None %fun\n"
3754                 "%BP_label = OpLabel\n"
3755                 "%BP_pos = OpLoad %v4f32 %BP_position\n"
3756                 "%BP_gl_pos = OpAccessChain %op_v4f32 %BP_stream %c_i32_0\n"
3757                 "OpStore %BP_gl_pos %BP_pos\n"
3758                 "%BP_col = OpLoad %v4f32 %BP_color\n"
3759                 "%BP_col_transformed = OpFunctionCall %v4f32 %test_code %BP_col\n"
3760                 "OpStore %BP_vtx_color %BP_col_transformed\n"
3761                 "OpReturn\n"
3762                 "OpFunctionEnd\n"
3763                 "${testfun}\n";
3764         return tcu::StringTemplate(vertexShaderBoilerplate).specialize(fragments);
3765 }
3766
3767 // Creates tess-control-shader assembly by specializing a boilerplate
3768 // StringTemplate on fragments, which must (at least) map "testfun" to an
3769 // OpFunction definition for %test_code that takes and returns a %v4f32.
3770 // Boilerplate IDs are prefixed with "BP_" to avoid collisions with fragments.
3771 //
3772 // It roughly corresponds to the following GLSL.
3773 //
3774 // #version 450
3775 // layout(vertices = 3) out;
3776 // layout(location = 1) in vec4 in_color[];
3777 // layout(location = 1) out vec4 out_color[];
3778 //
3779 // void main() {
3780 //   out_color[gl_InvocationID] = testfun(in_color[gl_InvocationID]);
3781 //   gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
3782 //   if (gl_InvocationID == 0) {
3783 //     gl_TessLevelOuter[0] = 1.0;
3784 //     gl_TessLevelOuter[1] = 1.0;
3785 //     gl_TessLevelOuter[2] = 1.0;
3786 //     gl_TessLevelInner[0] = 1.0;
3787 //   }
3788 // }
3789 string makeTessControlShaderAssembly (const map<string, string>& fragments)
3790 {
3791         static const char tessControlShaderBoilerplate[] =
3792                 "OpCapability Tessellation\n"
3793                 "OpCapability ClipDistance\n"
3794                 "OpCapability CullDistance\n"
3795                 "OpMemoryModel Logical GLSL450\n"
3796                 "OpEntryPoint TessellationControl %BP_main \"main\" %BP_out_color %BP_gl_InvocationID %BP_in_color %BP_gl_out %BP_gl_in %BP_gl_TessLevelOuter %BP_gl_TessLevelInner\n"
3797                 "OpExecutionMode %BP_main OutputVertices 3\n"
3798                 "${debug:opt}\n"
3799                 "OpName %BP_main \"main\"\n"
3800                 "OpName %test_code \"testfun(vf4;\"\n"
3801                 "OpName %BP_out_color \"out_color\"\n"
3802                 "OpName %BP_gl_InvocationID \"gl_InvocationID\"\n"
3803                 "OpName %BP_in_color \"in_color\"\n"
3804                 "OpName %BP_gl_PerVertex \"gl_PerVertex\"\n"
3805                 "OpMemberName %BP_gl_PerVertex 0 \"gl_Position\"\n"
3806                 "OpMemberName %BP_gl_PerVertex 1 \"gl_PointSize\"\n"
3807                 "OpMemberName %BP_gl_PerVertex 2 \"gl_ClipDistance\"\n"
3808                 "OpMemberName %BP_gl_PerVertex 3 \"gl_CullDistance\"\n"
3809                 "OpName %BP_gl_out \"gl_out\"\n"
3810                 "OpName %BP_gl_PVOut \"gl_PerVertex\"\n"
3811                 "OpMemberName %BP_gl_PVOut 0 \"gl_Position\"\n"
3812                 "OpMemberName %BP_gl_PVOut 1 \"gl_PointSize\"\n"
3813                 "OpMemberName %BP_gl_PVOut 2 \"gl_ClipDistance\"\n"
3814                 "OpMemberName %BP_gl_PVOut 3 \"gl_CullDistance\"\n"
3815                 "OpName %BP_gl_in \"gl_in\"\n"
3816                 "OpName %BP_gl_TessLevelOuter \"gl_TessLevelOuter\"\n"
3817                 "OpName %BP_gl_TessLevelInner \"gl_TessLevelInner\"\n"
3818                 "OpDecorate %BP_out_color Location 1\n"
3819                 "OpDecorate %BP_gl_InvocationID BuiltIn InvocationId\n"
3820                 "OpDecorate %BP_in_color Location 1\n"
3821                 "OpMemberDecorate %BP_gl_PerVertex 0 BuiltIn Position\n"
3822                 "OpMemberDecorate %BP_gl_PerVertex 1 BuiltIn PointSize\n"
3823                 "OpMemberDecorate %BP_gl_PerVertex 2 BuiltIn ClipDistance\n"
3824                 "OpMemberDecorate %BP_gl_PerVertex 3 BuiltIn CullDistance\n"
3825                 "OpDecorate %BP_gl_PerVertex Block\n"
3826                 "OpMemberDecorate %BP_gl_PVOut 0 BuiltIn Position\n"
3827                 "OpMemberDecorate %BP_gl_PVOut 1 BuiltIn PointSize\n"
3828                 "OpMemberDecorate %BP_gl_PVOut 2 BuiltIn ClipDistance\n"
3829                 "OpMemberDecorate %BP_gl_PVOut 3 BuiltIn CullDistance\n"
3830                 "OpDecorate %BP_gl_PVOut Block\n"
3831                 "OpDecorate %BP_gl_TessLevelOuter Patch\n"
3832                 "OpDecorate %BP_gl_TessLevelOuter BuiltIn TessLevelOuter\n"
3833                 "OpDecorate %BP_gl_TessLevelInner Patch\n"
3834                 "OpDecorate %BP_gl_TessLevelInner BuiltIn TessLevelInner\n"
3835                 "${decoration:opt}\n"
3836                 SPIRV_ASSEMBLY_TYPES
3837                 SPIRV_ASSEMBLY_CONSTANTS
3838                 SPIRV_ASSEMBLY_ARRAYS
3839                 "%BP_out_color = OpVariable %op_a3v4f32 Output\n"
3840                 "%BP_gl_InvocationID = OpVariable %ip_i32 Input\n"
3841                 "%BP_in_color = OpVariable %ip_a32v4f32 Input\n"
3842                 "%BP_gl_PerVertex = OpTypeStruct %v4f32 %f32 %a1f32 %a1f32\n"
3843                 "%BP_a3_gl_PerVertex = OpTypeArray %BP_gl_PerVertex %c_u32_3\n"
3844                 "%BP_op_a3_gl_PerVertex = OpTypePointer Output %BP_a3_gl_PerVertex\n"
3845                 "%BP_gl_out = OpVariable %BP_op_a3_gl_PerVertex Output\n"
3846                 "%BP_gl_PVOut = OpTypeStruct %v4f32 %f32 %a1f32 %a1f32\n"
3847                 "%BP_a32_gl_PVOut = OpTypeArray %BP_gl_PVOut %c_u32_32\n"
3848                 "%BP_ip_a32_gl_PVOut = OpTypePointer Input %BP_a32_gl_PVOut\n"
3849                 "%BP_gl_in = OpVariable %BP_ip_a32_gl_PVOut Input\n"
3850                 "%BP_gl_TessLevelOuter = OpVariable %op_a4f32 Output\n"
3851                 "%BP_gl_TessLevelInner = OpVariable %op_a2f32 Output\n"
3852                 "${pre_main:opt}\n"
3853
3854                 "%BP_main = OpFunction %void None %fun\n"
3855                 "%BP_label = OpLabel\n"
3856
3857                 "%BP_gl_Invoc = OpLoad %i32 %BP_gl_InvocationID\n"
3858
3859                 "%BP_in_col_loc = OpAccessChain %ip_v4f32 %BP_in_color %BP_gl_Invoc\n"
3860                 "%BP_out_col_loc = OpAccessChain %op_v4f32 %BP_out_color %BP_gl_Invoc\n"
3861                 "%BP_in_col_val = OpLoad %v4f32 %BP_in_col_loc\n"
3862                 "%BP_clr_transformed = OpFunctionCall %v4f32 %test_code %BP_in_col_val\n"
3863                 "OpStore %BP_out_col_loc %BP_clr_transformed\n"
3864
3865                 "%BP_in_pos_loc = OpAccessChain %ip_v4f32 %BP_gl_in %BP_gl_Invoc %c_i32_0\n"
3866                 "%BP_out_pos_loc = OpAccessChain %op_v4f32 %BP_gl_out %BP_gl_Invoc %c_i32_0\n"
3867                 "%BP_in_pos_val = OpLoad %v4f32 %BP_in_pos_loc\n"
3868                 "OpStore %BP_out_pos_loc %BP_in_pos_val\n"
3869
3870                 "%BP_cmp = OpIEqual %bool %BP_gl_Invoc %c_i32_0\n"
3871                 "OpSelectionMerge %BP_merge_label None\n"
3872                 "OpBranchConditional %BP_cmp %BP_if_label %BP_merge_label\n"
3873                 "%BP_if_label = OpLabel\n"
3874                 "%BP_gl_TessLevelOuterPos_0 = OpAccessChain %op_f32 %BP_gl_TessLevelOuter %c_i32_0\n"
3875                 "%BP_gl_TessLevelOuterPos_1 = OpAccessChain %op_f32 %BP_gl_TessLevelOuter %c_i32_1\n"
3876                 "%BP_gl_TessLevelOuterPos_2 = OpAccessChain %op_f32 %BP_gl_TessLevelOuter %c_i32_2\n"
3877                 "%BP_gl_TessLevelInnerPos_0 = OpAccessChain %op_f32 %BP_gl_TessLevelInner %c_i32_0\n"
3878                 "OpStore %BP_gl_TessLevelOuterPos_0 %c_f32_1\n"
3879                 "OpStore %BP_gl_TessLevelOuterPos_1 %c_f32_1\n"
3880                 "OpStore %BP_gl_TessLevelOuterPos_2 %c_f32_1\n"
3881                 "OpStore %BP_gl_TessLevelInnerPos_0 %c_f32_1\n"
3882                 "OpBranch %BP_merge_label\n"
3883                 "%BP_merge_label = OpLabel\n"
3884                 "OpReturn\n"
3885                 "OpFunctionEnd\n"
3886                 "${testfun}\n";
3887         return tcu::StringTemplate(tessControlShaderBoilerplate).specialize(fragments);
3888 }
3889
3890 // Creates tess-evaluation-shader assembly by specializing a boilerplate
3891 // StringTemplate on fragments, which must (at least) map "testfun" to an
3892 // OpFunction definition for %test_code that takes and returns a %v4f32.
3893 // Boilerplate IDs are prefixed with "BP_" to avoid collisions with fragments.
3894 //
3895 // It roughly corresponds to the following glsl.
3896 //
3897 // #version 450
3898 //
3899 // layout(triangles, equal_spacing, ccw) in;
3900 // layout(location = 1) in vec4 in_color[];
3901 // layout(location = 1) out vec4 out_color;
3902 //
3903 // #define interpolate(val)
3904 //   vec4(gl_TessCoord.x) * val[0] + vec4(gl_TessCoord.y) * val[1] +
3905 //          vec4(gl_TessCoord.z) * val[2]
3906 //
3907 // void main() {
3908 //   gl_Position = vec4(gl_TessCoord.x) * gl_in[0].gl_Position +
3909 //                  vec4(gl_TessCoord.y) * gl_in[1].gl_Position +
3910 //                  vec4(gl_TessCoord.z) * gl_in[2].gl_Position;
3911 //   out_color = testfun(interpolate(in_color));
3912 // }
3913 string makeTessEvalShaderAssembly(const map<string, string>& fragments)
3914 {
3915         static const char tessEvalBoilerplate[] =
3916                 "OpCapability Tessellation\n"
3917                 "OpCapability ClipDistance\n"
3918                 "OpCapability CullDistance\n"
3919                 "OpMemoryModel Logical GLSL450\n"
3920                 "OpEntryPoint TessellationEvaluation %BP_main \"main\" %BP_stream %BP_gl_TessCoord %BP_gl_in %BP_out_color %BP_in_color\n"
3921                 "OpExecutionMode %BP_main Triangles\n"
3922                 "OpExecutionMode %BP_main SpacingEqual\n"
3923                 "OpExecutionMode %BP_main VertexOrderCcw\n"
3924                 "${debug:opt}\n"
3925                 "OpName %BP_main \"main\"\n"
3926                 "OpName %test_code \"testfun(vf4;\"\n"
3927                 "OpName %BP_gl_PerVertexOut \"gl_PerVertex\"\n"
3928                 "OpMemberName %BP_gl_PerVertexOut 0 \"gl_Position\"\n"
3929                 "OpMemberName %BP_gl_PerVertexOut 1 \"gl_PointSize\"\n"
3930                 "OpMemberName %BP_gl_PerVertexOut 2 \"gl_ClipDistance\"\n"
3931                 "OpMemberName %BP_gl_PerVertexOut 3 \"gl_CullDistance\"\n"
3932                 "OpName %BP_stream \"\"\n"
3933                 "OpName %BP_gl_TessCoord \"gl_TessCoord\"\n"
3934                 "OpName %BP_gl_PerVertexIn \"gl_PerVertex\"\n"
3935                 "OpMemberName %BP_gl_PerVertexIn 0 \"gl_Position\"\n"
3936                 "OpMemberName %BP_gl_PerVertexIn 1 \"gl_PointSize\"\n"
3937                 "OpMemberName %BP_gl_PerVertexIn 2 \"gl_ClipDistance\"\n"
3938                 "OpMemberName %BP_gl_PerVertexIn 3 \"gl_CullDistance\"\n"
3939                 "OpName %BP_gl_in \"gl_in\"\n"
3940                 "OpName %BP_out_color \"out_color\"\n"
3941                 "OpName %BP_in_color \"in_color\"\n"
3942                 "OpMemberDecorate %BP_gl_PerVertexOut 0 BuiltIn Position\n"
3943                 "OpMemberDecorate %BP_gl_PerVertexOut 1 BuiltIn PointSize\n"
3944                 "OpMemberDecorate %BP_gl_PerVertexOut 2 BuiltIn ClipDistance\n"
3945                 "OpMemberDecorate %BP_gl_PerVertexOut 3 BuiltIn CullDistance\n"
3946                 "OpDecorate %BP_gl_PerVertexOut Block\n"
3947                 "OpDecorate %BP_gl_TessCoord BuiltIn TessCoord\n"
3948                 "OpMemberDecorate %BP_gl_PerVertexIn 0 BuiltIn Position\n"
3949                 "OpMemberDecorate %BP_gl_PerVertexIn 1 BuiltIn PointSize\n"
3950                 "OpMemberDecorate %BP_gl_PerVertexIn 2 BuiltIn ClipDistance\n"
3951                 "OpMemberDecorate %BP_gl_PerVertexIn 3 BuiltIn CullDistance\n"
3952                 "OpDecorate %BP_gl_PerVertexIn Block\n"
3953                 "OpDecorate %BP_out_color Location 1\n"
3954                 "OpDecorate %BP_in_color Location 1\n"
3955                 "${decoration:opt}\n"
3956                 SPIRV_ASSEMBLY_TYPES
3957                 SPIRV_ASSEMBLY_CONSTANTS
3958                 SPIRV_ASSEMBLY_ARRAYS
3959                 "%BP_gl_PerVertexOut = OpTypeStruct %v4f32 %f32 %a1f32 %a1f32\n"
3960                 "%BP_op_gl_PerVertexOut = OpTypePointer Output %BP_gl_PerVertexOut\n"
3961                 "%BP_stream = OpVariable %BP_op_gl_PerVertexOut Output\n"
3962                 "%BP_gl_TessCoord = OpVariable %ip_v3f32 Input\n"
3963                 "%BP_gl_PerVertexIn = OpTypeStruct %v4f32 %f32 %a1f32 %a1f32\n"
3964                 "%BP_a32_gl_PerVertexIn = OpTypeArray %BP_gl_PerVertexIn %c_u32_32\n"
3965                 "%BP_ip_a32_gl_PerVertexIn = OpTypePointer Input %BP_a32_gl_PerVertexIn\n"
3966                 "%BP_gl_in = OpVariable %BP_ip_a32_gl_PerVertexIn Input\n"
3967                 "%BP_out_color = OpVariable %op_v4f32 Output\n"
3968                 "%BP_in_color = OpVariable %ip_a32v4f32 Input\n"
3969                 "${pre_main:opt}\n"
3970                 "%BP_main = OpFunction %void None %fun\n"
3971                 "%BP_label = OpLabel\n"
3972                 "%BP_gl_TC_0 = OpAccessChain %ip_f32 %BP_gl_TessCoord %c_u32_0\n"
3973                 "%BP_gl_TC_1 = OpAccessChain %ip_f32 %BP_gl_TessCoord %c_u32_1\n"
3974                 "%BP_gl_TC_2 = OpAccessChain %ip_f32 %BP_gl_TessCoord %c_u32_2\n"
3975                 "%BP_gl_in_gl_Pos_0 = OpAccessChain %ip_v4f32 %BP_gl_in %c_i32_0 %c_i32_0\n"
3976                 "%BP_gl_in_gl_Pos_1 = OpAccessChain %ip_v4f32 %BP_gl_in %c_i32_1 %c_i32_0\n"
3977                 "%BP_gl_in_gl_Pos_2 = OpAccessChain %ip_v4f32 %BP_gl_in %c_i32_2 %c_i32_0\n"
3978
3979                 "%BP_gl_OPos = OpAccessChain %op_v4f32 %BP_stream %c_i32_0\n"
3980                 "%BP_in_color_0 = OpAccessChain %ip_v4f32 %BP_in_color %c_i32_0\n"
3981                 "%BP_in_color_1 = OpAccessChain %ip_v4f32 %BP_in_color %c_i32_1\n"
3982                 "%BP_in_color_2 = OpAccessChain %ip_v4f32 %BP_in_color %c_i32_2\n"
3983
3984                 "%BP_TC_W_0 = OpLoad %f32 %BP_gl_TC_0\n"
3985                 "%BP_TC_W_1 = OpLoad %f32 %BP_gl_TC_1\n"
3986                 "%BP_TC_W_2 = OpLoad %f32 %BP_gl_TC_2\n"
3987                 "%BP_v4f32_TC_0 = OpCompositeConstruct %v4f32 %BP_TC_W_0 %BP_TC_W_0 %BP_TC_W_0 %BP_TC_W_0\n"
3988                 "%BP_v4f32_TC_1 = OpCompositeConstruct %v4f32 %BP_TC_W_1 %BP_TC_W_1 %BP_TC_W_1 %BP_TC_W_1\n"
3989                 "%BP_v4f32_TC_2 = OpCompositeConstruct %v4f32 %BP_TC_W_2 %BP_TC_W_2 %BP_TC_W_2 %BP_TC_W_2\n"
3990
3991                 "%BP_gl_IP_0 = OpLoad %v4f32 %BP_gl_in_gl_Pos_0\n"
3992                 "%BP_gl_IP_1 = OpLoad %v4f32 %BP_gl_in_gl_Pos_1\n"
3993                 "%BP_gl_IP_2 = OpLoad %v4f32 %BP_gl_in_gl_Pos_2\n"
3994
3995                 "%BP_IP_W_0 = OpFMul %v4f32 %BP_v4f32_TC_0 %BP_gl_IP_0\n"
3996                 "%BP_IP_W_1 = OpFMul %v4f32 %BP_v4f32_TC_1 %BP_gl_IP_1\n"
3997                 "%BP_IP_W_2 = OpFMul %v4f32 %BP_v4f32_TC_2 %BP_gl_IP_2\n"
3998
3999                 "%BP_pos_sum_0 = OpFAdd %v4f32 %BP_IP_W_0 %BP_IP_W_1\n"
4000                 "%BP_pos_sum_1 = OpFAdd %v4f32 %BP_pos_sum_0 %BP_IP_W_2\n"
4001
4002                 "OpStore %BP_gl_OPos %BP_pos_sum_1\n"
4003
4004                 "%BP_IC_0 = OpLoad %v4f32 %BP_in_color_0\n"
4005                 "%BP_IC_1 = OpLoad %v4f32 %BP_in_color_1\n"
4006                 "%BP_IC_2 = OpLoad %v4f32 %BP_in_color_2\n"
4007
4008                 "%BP_IC_W_0 = OpFMul %v4f32 %BP_v4f32_TC_0 %BP_IC_0\n"
4009                 "%BP_IC_W_1 = OpFMul %v4f32 %BP_v4f32_TC_1 %BP_IC_1\n"
4010                 "%BP_IC_W_2 = OpFMul %v4f32 %BP_v4f32_TC_2 %BP_IC_2\n"
4011
4012                 "%BP_col_sum_0 = OpFAdd %v4f32 %BP_IC_W_0 %BP_IC_W_1\n"
4013                 "%BP_col_sum_1 = OpFAdd %v4f32 %BP_col_sum_0 %BP_IC_W_2\n"
4014
4015                 "%BP_clr_transformed = OpFunctionCall %v4f32 %test_code %BP_col_sum_1\n"
4016
4017                 "OpStore %BP_out_color %BP_clr_transformed\n"
4018                 "OpReturn\n"
4019                 "OpFunctionEnd\n"
4020                 "${testfun}\n";
4021         return tcu::StringTemplate(tessEvalBoilerplate).specialize(fragments);
4022 }
4023
4024 // Creates geometry-shader assembly by specializing a boilerplate StringTemplate
4025 // on fragments, which must (at least) map "testfun" to an OpFunction definition
4026 // for %test_code that takes and returns a %v4f32.  Boilerplate IDs are prefixed
4027 // with "BP_" to avoid collisions with fragments.
4028 //
4029 // Derived from this GLSL:
4030 //
4031 // #version 450
4032 // layout(triangles) in;
4033 // layout(triangle_strip, max_vertices = 3) out;
4034 //
4035 // layout(location = 1) in vec4 in_color[];
4036 // layout(location = 1) out vec4 out_color;
4037 //
4038 // void main() {
4039 //   gl_Position = gl_in[0].gl_Position;
4040 //   out_color = test_fun(in_color[0]);
4041 //   EmitVertex();
4042 //   gl_Position = gl_in[1].gl_Position;
4043 //   out_color = test_fun(in_color[1]);
4044 //   EmitVertex();
4045 //   gl_Position = gl_in[2].gl_Position;
4046 //   out_color = test_fun(in_color[2]);
4047 //   EmitVertex();
4048 //   EndPrimitive();
4049 // }
4050 string makeGeometryShaderAssembly(const map<string, string>& fragments)
4051 {
4052         static const char geometryShaderBoilerplate[] =
4053                 "OpCapability Geometry\n"
4054                 "OpCapability ClipDistance\n"
4055                 "OpCapability CullDistance\n"
4056                 "OpMemoryModel Logical GLSL450\n"
4057                 "OpEntryPoint Geometry %BP_main \"main\" %BP_out_gl_position %BP_gl_in %BP_out_color %BP_in_color\n"
4058                 "OpExecutionMode %BP_main Triangles\n"
4059                 "OpExecutionMode %BP_main OutputTriangleStrip\n"
4060                 "OpExecutionMode %BP_main OutputVertices 3\n"
4061                 "${debug:opt}\n"
4062                 "OpName %BP_main \"main\"\n"
4063                 "OpName %BP_per_vertex_in \"gl_PerVertex\"\n"
4064                 "OpMemberName %BP_per_vertex_in 0 \"gl_Position\"\n"
4065                 "OpMemberName %BP_per_vertex_in 1 \"gl_PointSize\"\n"
4066                 "OpMemberName %BP_per_vertex_in 2 \"gl_ClipDistance\"\n"
4067                 "OpMemberName %BP_per_vertex_in 3 \"gl_CullDistance\"\n"
4068                 "OpName %BP_gl_in \"gl_in\"\n"
4069                 "OpName %BP_out_color \"out_color\"\n"
4070                 "OpName %BP_in_color \"in_color\"\n"
4071                 "OpName %test_code \"testfun(vf4;\"\n"
4072                 "OpDecorate %BP_out_gl_position BuiltIn Position\n"
4073                 "OpMemberDecorate %BP_per_vertex_in 0 BuiltIn Position\n"
4074                 "OpMemberDecorate %BP_per_vertex_in 1 BuiltIn PointSize\n"
4075                 "OpMemberDecorate %BP_per_vertex_in 2 BuiltIn ClipDistance\n"
4076                 "OpMemberDecorate %BP_per_vertex_in 3 BuiltIn CullDistance\n"
4077                 "OpDecorate %BP_per_vertex_in Block\n"
4078                 "OpDecorate %BP_out_color Location 1\n"
4079                 "OpDecorate %BP_in_color Location 1\n"
4080                 "${decoration:opt}\n"
4081                 SPIRV_ASSEMBLY_TYPES
4082                 SPIRV_ASSEMBLY_CONSTANTS
4083                 SPIRV_ASSEMBLY_ARRAYS
4084                 "%BP_per_vertex_in = OpTypeStruct %v4f32 %f32 %a1f32 %a1f32\n"
4085                 "%BP_a3_per_vertex_in = OpTypeArray %BP_per_vertex_in %c_u32_3\n"
4086                 "%BP_ip_a3_per_vertex_in = OpTypePointer Input %BP_a3_per_vertex_in\n"
4087
4088                 "%BP_gl_in = OpVariable %BP_ip_a3_per_vertex_in Input\n"
4089                 "%BP_out_color = OpVariable %op_v4f32 Output\n"
4090                 "%BP_in_color = OpVariable %ip_a3v4f32 Input\n"
4091                 "%BP_out_gl_position = OpVariable %op_v4f32 Output\n"
4092                 "${pre_main:opt}\n"
4093
4094                 "%BP_main = OpFunction %void None %fun\n"
4095                 "%BP_label = OpLabel\n"
4096                 "%BP_gl_in_0_gl_position = OpAccessChain %ip_v4f32 %BP_gl_in %c_i32_0 %c_i32_0\n"
4097                 "%BP_gl_in_1_gl_position = OpAccessChain %ip_v4f32 %BP_gl_in %c_i32_1 %c_i32_0\n"
4098                 "%BP_gl_in_2_gl_position = OpAccessChain %ip_v4f32 %BP_gl_in %c_i32_2 %c_i32_0\n"
4099
4100                 "%BP_in_position_0 = OpLoad %v4f32 %BP_gl_in_0_gl_position\n"
4101                 "%BP_in_position_1 = OpLoad %v4f32 %BP_gl_in_1_gl_position\n"
4102                 "%BP_in_position_2 = OpLoad %v4f32 %BP_gl_in_2_gl_position \n"
4103
4104                 "%BP_in_color_0_ptr = OpAccessChain %ip_v4f32 %BP_in_color %c_i32_0\n"
4105                 "%BP_in_color_1_ptr = OpAccessChain %ip_v4f32 %BP_in_color %c_i32_1\n"
4106                 "%BP_in_color_2_ptr = OpAccessChain %ip_v4f32 %BP_in_color %c_i32_2\n"
4107
4108                 "%BP_in_color_0 = OpLoad %v4f32 %BP_in_color_0_ptr\n"
4109                 "%BP_in_color_1 = OpLoad %v4f32 %BP_in_color_1_ptr\n"
4110                 "%BP_in_color_2 = OpLoad %v4f32 %BP_in_color_2_ptr\n"
4111
4112                 "%BP_transformed_in_color_0 = OpFunctionCall %v4f32 %test_code %BP_in_color_0\n"
4113                 "%BP_transformed_in_color_1 = OpFunctionCall %v4f32 %test_code %BP_in_color_1\n"
4114                 "%BP_transformed_in_color_2 = OpFunctionCall %v4f32 %test_code %BP_in_color_2\n"
4115
4116
4117                 "OpStore %BP_out_gl_position %BP_in_position_0\n"
4118                 "OpStore %BP_out_color %BP_transformed_in_color_0\n"
4119                 "OpEmitVertex\n"
4120
4121                 "OpStore %BP_out_gl_position %BP_in_position_1\n"
4122                 "OpStore %BP_out_color %BP_transformed_in_color_1\n"
4123                 "OpEmitVertex\n"
4124
4125                 "OpStore %BP_out_gl_position %BP_in_position_2\n"
4126                 "OpStore %BP_out_color %BP_transformed_in_color_2\n"
4127                 "OpEmitVertex\n"
4128
4129                 "OpEndPrimitive\n"
4130                 "OpReturn\n"
4131                 "OpFunctionEnd\n"
4132                 "${testfun}\n";
4133         return tcu::StringTemplate(geometryShaderBoilerplate).specialize(fragments);
4134 }
4135
4136 // Creates fragment-shader assembly by specializing a boilerplate StringTemplate
4137 // on fragments, which must (at least) map "testfun" to an OpFunction definition
4138 // for %test_code that takes and returns a %v4f32.  Boilerplate IDs are prefixed
4139 // with "BP_" to avoid collisions with fragments.
4140 //
4141 // Derived from this GLSL:
4142 //
4143 // layout(location = 1) in highp vec4 vtxColor;
4144 // layout(location = 0) out highp vec4 fragColor;
4145 // highp vec4 testfun(highp vec4 x) { return x; }
4146 // void main(void) { fragColor = testfun(vtxColor); }
4147 //
4148 // with modifications including passing vtxColor by value and ripping out
4149 // testfun() definition.
4150 string makeFragmentShaderAssembly(const map<string, string>& fragments)
4151 {
4152         static const char fragmentShaderBoilerplate[] =
4153                 "OpCapability Shader\n"
4154                 "OpMemoryModel Logical GLSL450\n"
4155                 "OpEntryPoint Fragment %BP_main \"main\" %BP_vtxColor %BP_fragColor\n"
4156                 "OpExecutionMode %BP_main OriginUpperLeft\n"
4157                 "${debug:opt}\n"
4158                 "OpName %BP_main \"main\"\n"
4159                 "OpName %BP_fragColor \"fragColor\"\n"
4160                 "OpName %BP_vtxColor \"vtxColor\"\n"
4161                 "OpName %test_code \"testfun(vf4;\"\n"
4162                 "OpDecorate %BP_fragColor Location 0\n"
4163                 "OpDecorate %BP_vtxColor Location 1\n"
4164                 "${decoration:opt}\n"
4165                 SPIRV_ASSEMBLY_TYPES
4166                 SPIRV_ASSEMBLY_CONSTANTS
4167                 SPIRV_ASSEMBLY_ARRAYS
4168                 "%BP_fragColor = OpVariable %op_v4f32 Output\n"
4169                 "%BP_vtxColor = OpVariable %ip_v4f32 Input\n"
4170                 "${pre_main:opt}\n"
4171                 "%BP_main = OpFunction %void None %fun\n"
4172                 "%BP_label_main = OpLabel\n"
4173                 "%BP_tmp1 = OpLoad %v4f32 %BP_vtxColor\n"
4174                 "%BP_tmp2 = OpFunctionCall %v4f32 %test_code %BP_tmp1\n"
4175                 "OpStore %BP_fragColor %BP_tmp2\n"
4176                 "OpReturn\n"
4177                 "OpFunctionEnd\n"
4178                 "${testfun}\n";
4179         return tcu::StringTemplate(fragmentShaderBoilerplate).specialize(fragments);
4180 }
4181
4182 // Creates fragments that specialize into a simple pass-through shader (of any kind).
4183 map<string, string> passthruFragments(void)
4184 {
4185         map<string, string> fragments;
4186         fragments["testfun"] =
4187                 // A %test_code function that returns its argument unchanged.
4188                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
4189                 "%param1 = OpFunctionParameter %v4f32\n"
4190                 "%label_testfun = OpLabel\n"
4191                 "OpReturnValue %param1\n"
4192                 "OpFunctionEnd\n";
4193         return fragments;
4194 }
4195
4196 // Adds shader assembly text to dst.spirvAsmSources for all shader kinds.
4197 // Vertex shader gets custom code from context, the rest are pass-through.
4198 void addShaderCodeCustomVertex(vk::SourceCollections& dst, InstanceContext context)
4199 {
4200         map<string, string> passthru = passthruFragments();
4201         dst.spirvAsmSources.add("vert") << makeVertexShaderAssembly(context.testCodeFragments);
4202         dst.spirvAsmSources.add("frag") << makeFragmentShaderAssembly(passthru);
4203 }
4204
4205 // Adds shader assembly text to dst.spirvAsmSources for all shader kinds.
4206 // Tessellation control shader gets custom code from context, the rest are
4207 // pass-through.
4208 void addShaderCodeCustomTessControl(vk::SourceCollections& dst, InstanceContext context)
4209 {
4210         map<string, string> passthru = passthruFragments();
4211         dst.spirvAsmSources.add("vert") << makeVertexShaderAssembly(passthru);
4212         dst.spirvAsmSources.add("tessc") << makeTessControlShaderAssembly(context.testCodeFragments);
4213         dst.spirvAsmSources.add("tesse") << makeTessEvalShaderAssembly(passthru);
4214         dst.spirvAsmSources.add("frag") << makeFragmentShaderAssembly(passthru);
4215 }
4216
4217 // Adds shader assembly text to dst.spirvAsmSources for all shader kinds.
4218 // Tessellation evaluation shader gets custom code from context, the rest are
4219 // pass-through.
4220 void addShaderCodeCustomTessEval(vk::SourceCollections& dst, InstanceContext context)
4221 {
4222         map<string, string> passthru = passthruFragments();
4223         dst.spirvAsmSources.add("vert") << makeVertexShaderAssembly(passthru);
4224         dst.spirvAsmSources.add("tessc") << makeTessControlShaderAssembly(passthru);
4225         dst.spirvAsmSources.add("tesse") << makeTessEvalShaderAssembly(context.testCodeFragments);
4226         dst.spirvAsmSources.add("frag") << makeFragmentShaderAssembly(passthru);
4227 }
4228
4229 // Adds shader assembly text to dst.spirvAsmSources for all shader kinds.
4230 // Geometry shader gets custom code from context, the rest are pass-through.
4231 void addShaderCodeCustomGeometry(vk::SourceCollections& dst, InstanceContext context)
4232 {
4233         map<string, string> passthru = passthruFragments();
4234         dst.spirvAsmSources.add("vert") << makeVertexShaderAssembly(passthru);
4235         dst.spirvAsmSources.add("geom") << makeGeometryShaderAssembly(context.testCodeFragments);
4236         dst.spirvAsmSources.add("frag") << makeFragmentShaderAssembly(passthru);
4237 }
4238
4239 // Adds shader assembly text to dst.spirvAsmSources for all shader kinds.
4240 // Fragment shader gets custom code from context, the rest are pass-through.
4241 void addShaderCodeCustomFragment(vk::SourceCollections& dst, InstanceContext context)
4242 {
4243         map<string, string> passthru = passthruFragments();
4244         dst.spirvAsmSources.add("vert") << makeVertexShaderAssembly(passthru);
4245         dst.spirvAsmSources.add("frag") << makeFragmentShaderAssembly(context.testCodeFragments);
4246 }
4247
4248 void createCombinedModule(vk::SourceCollections& dst, InstanceContext)
4249 {
4250         // \todo [2015-12-07 awoloszyn] Make tessellation / geometry conditional
4251         // \todo [2015-12-07 awoloszyn] Remove OpName and OpMemberName at some point
4252         dst.spirvAsmSources.add("module") <<
4253                 "OpCapability Shader\n"
4254                 "OpCapability ClipDistance\n"
4255                 "OpCapability CullDistance\n"
4256                 "OpCapability Geometry\n"
4257                 "OpCapability Tessellation\n"
4258                 "OpMemoryModel Logical GLSL450\n"
4259
4260                 "OpEntryPoint Vertex %vert_main \"main\" %vert_Position %vert_vtxColor %vert_color %vert_vtxPosition %vert_vertex_id %vert_instance_id\n"
4261                 "OpEntryPoint Geometry %geom_main \"main\" %geom_out_gl_position %geom_gl_in %geom_out_color %geom_in_color\n"
4262                 "OpEntryPoint TessellationControl %tessc_main \"main\" %tessc_out_color %tessc_gl_InvocationID %tessc_in_color %tessc_out_position %tessc_in_position %tessc_gl_TessLevelOuter %tessc_gl_TessLevelInner\n"
4263                 "OpEntryPoint TessellationEvaluation %tesse_main \"main\" %tesse_stream %tesse_gl_tessCoord %tesse_in_position %tesse_out_color %tesse_in_color \n"
4264                 "OpEntryPoint Fragment %frag_main \"main\" %frag_vtxColor %frag_fragColor\n"
4265
4266                 "OpExecutionMode %geom_main Triangles\n"
4267                 "OpExecutionMode %geom_main OutputTriangleStrip\n"
4268                 "OpExecutionMode %geom_main OutputVertices 3\n"
4269
4270                 "OpExecutionMode %tessc_main OutputVertices 3\n"
4271
4272                 "OpExecutionMode %tesse_main Triangles\n"
4273                 "OpExecutionMode %tesse_main SpacingEqual\n"
4274                 "OpExecutionMode %tesse_main VertexOrderCcw\n"
4275
4276                 "OpExecutionMode %frag_main OriginUpperLeft\n"
4277
4278                 "OpName %vert_main \"main\"\n"
4279                 "OpName %vert_vtxPosition \"vtxPosition\"\n"
4280                 "OpName %vert_Position \"position\"\n"
4281                 "OpName %vert_vtxColor \"vtxColor\"\n"
4282                 "OpName %vert_color \"color\"\n"
4283                 "OpName %vert_vertex_id \"gl_VertexIndex\"\n"
4284                 "OpName %vert_instance_id \"gl_InstanceIndex\"\n"
4285                 "OpName %geom_main \"main\"\n"
4286                 "OpName %geom_per_vertex_in \"gl_PerVertex\"\n"
4287                 "OpMemberName %geom_per_vertex_in 0 \"gl_Position\"\n"
4288                 "OpMemberName %geom_per_vertex_in 1 \"gl_PointSize\"\n"
4289                 "OpMemberName %geom_per_vertex_in 2 \"gl_ClipDistance\"\n"
4290                 "OpMemberName %geom_per_vertex_in 3 \"gl_CullDistance\"\n"
4291                 "OpName %geom_gl_in \"gl_in\"\n"
4292                 "OpName %geom_out_color \"out_color\"\n"
4293                 "OpName %geom_in_color \"in_color\"\n"
4294                 "OpName %tessc_main \"main\"\n"
4295                 "OpName %tessc_out_color \"out_color\"\n"
4296                 "OpName %tessc_gl_InvocationID \"gl_InvocationID\"\n"
4297                 "OpName %tessc_in_color \"in_color\"\n"
4298                 "OpName %tessc_out_position \"out_position\"\n"
4299                 "OpName %tessc_in_position \"in_position\"\n"
4300                 "OpName %tessc_gl_TessLevelOuter \"gl_TessLevelOuter\"\n"
4301                 "OpName %tessc_gl_TessLevelInner \"gl_TessLevelInner\"\n"
4302                 "OpName %tesse_main \"main\"\n"
4303                 "OpName %tesse_per_vertex_out \"gl_PerVertex\"\n"
4304                 "OpMemberName %tesse_per_vertex_out 0 \"gl_Position\"\n"
4305                 "OpMemberName %tesse_per_vertex_out 1 \"gl_PointSize\"\n"
4306                 "OpMemberName %tesse_per_vertex_out 2 \"gl_ClipDistance\"\n"
4307                 "OpMemberName %tesse_per_vertex_out 3 \"gl_CullDistance\"\n"
4308                 "OpName %tesse_stream \"\"\n"
4309                 "OpName %tesse_gl_tessCoord \"gl_TessCoord\"\n"
4310                 "OpName %tesse_in_position \"in_position\"\n"
4311                 "OpName %tesse_out_color \"out_color\"\n"
4312                 "OpName %tesse_in_color \"in_color\"\n"
4313                 "OpName %frag_main \"main\"\n"
4314                 "OpName %frag_fragColor \"fragColor\"\n"
4315                 "OpName %frag_vtxColor \"vtxColor\"\n"
4316
4317                 "; Vertex decorations\n"
4318                 "OpDecorate %vert_vtxPosition Location 2\n"
4319                 "OpDecorate %vert_Position Location 0\n"
4320                 "OpDecorate %vert_vtxColor Location 1\n"
4321                 "OpDecorate %vert_color Location 1\n"
4322                 "OpDecorate %vert_vertex_id BuiltIn VertexIndex\n"
4323                 "OpDecorate %vert_instance_id BuiltIn InstanceIndex\n"
4324
4325                 "; Geometry decorations\n"
4326                 "OpDecorate %geom_out_gl_position BuiltIn Position\n"
4327                 "OpMemberDecorate %geom_per_vertex_in 0 BuiltIn Position\n"
4328                 "OpMemberDecorate %geom_per_vertex_in 1 BuiltIn PointSize\n"
4329                 "OpMemberDecorate %geom_per_vertex_in 2 BuiltIn ClipDistance\n"
4330                 "OpMemberDecorate %geom_per_vertex_in 3 BuiltIn CullDistance\n"
4331                 "OpDecorate %geom_per_vertex_in Block\n"
4332                 "OpDecorate %geom_out_color Location 1\n"
4333                 "OpDecorate %geom_in_color Location 1\n"
4334
4335                 "; Tessellation Control decorations\n"
4336                 "OpDecorate %tessc_out_color Location 1\n"
4337                 "OpDecorate %tessc_gl_InvocationID BuiltIn InvocationId\n"
4338                 "OpDecorate %tessc_in_color Location 1\n"
4339                 "OpDecorate %tessc_out_position Location 2\n"
4340                 "OpDecorate %tessc_in_position Location 2\n"
4341                 "OpDecorate %tessc_gl_TessLevelOuter Patch\n"
4342                 "OpDecorate %tessc_gl_TessLevelOuter BuiltIn TessLevelOuter\n"
4343                 "OpDecorate %tessc_gl_TessLevelInner Patch\n"
4344                 "OpDecorate %tessc_gl_TessLevelInner BuiltIn TessLevelInner\n"
4345
4346                 "; Tessellation Evaluation decorations\n"
4347                 "OpMemberDecorate %tesse_per_vertex_out 0 BuiltIn Position\n"
4348                 "OpMemberDecorate %tesse_per_vertex_out 1 BuiltIn PointSize\n"
4349                 "OpMemberDecorate %tesse_per_vertex_out 2 BuiltIn ClipDistance\n"
4350                 "OpMemberDecorate %tesse_per_vertex_out 3 BuiltIn CullDistance\n"
4351                 "OpDecorate %tesse_per_vertex_out Block\n"
4352                 "OpDecorate %tesse_gl_tessCoord BuiltIn TessCoord\n"
4353                 "OpDecorate %tesse_in_position Location 2\n"
4354                 "OpDecorate %tesse_out_color Location 1\n"
4355                 "OpDecorate %tesse_in_color Location 1\n"
4356
4357                 "; Fragment decorations\n"
4358                 "OpDecorate %frag_fragColor Location 0\n"
4359                 "OpDecorate %frag_vtxColor Location 1\n"
4360
4361                 SPIRV_ASSEMBLY_TYPES
4362                 SPIRV_ASSEMBLY_CONSTANTS
4363                 SPIRV_ASSEMBLY_ARRAYS
4364
4365                 "; Vertex Variables\n"
4366                 "%vert_vtxPosition = OpVariable %op_v4f32 Output\n"
4367                 "%vert_Position = OpVariable %ip_v4f32 Input\n"
4368                 "%vert_vtxColor = OpVariable %op_v4f32 Output\n"
4369                 "%vert_color = OpVariable %ip_v4f32 Input\n"
4370                 "%vert_vertex_id = OpVariable %ip_i32 Input\n"
4371                 "%vert_instance_id = OpVariable %ip_i32 Input\n"
4372
4373                 "; Geometry Variables\n"
4374                 "%geom_per_vertex_in = OpTypeStruct %v4f32 %f32 %a1f32 %a1f32\n"
4375                 "%geom_a3_per_vertex_in = OpTypeArray %geom_per_vertex_in %c_u32_3\n"
4376                 "%geom_ip_a3_per_vertex_in = OpTypePointer Input %geom_a3_per_vertex_in\n"
4377                 "%geom_gl_in = OpVariable %geom_ip_a3_per_vertex_in Input\n"
4378                 "%geom_out_color = OpVariable %op_v4f32 Output\n"
4379                 "%geom_in_color = OpVariable %ip_a3v4f32 Input\n"
4380                 "%geom_out_gl_position = OpVariable %op_v4f32 Output\n"
4381
4382                 "; Tessellation Control Variables\n"
4383                 "%tessc_out_color = OpVariable %op_a3v4f32 Output\n"
4384                 "%tessc_gl_InvocationID = OpVariable %ip_i32 Input\n"
4385                 "%tessc_in_color = OpVariable %ip_a32v4f32 Input\n"
4386                 "%tessc_out_position = OpVariable %op_a3v4f32 Output\n"
4387                 "%tessc_in_position = OpVariable %ip_a32v4f32 Input\n"
4388                 "%tessc_gl_TessLevelOuter = OpVariable %op_a4f32 Output\n"
4389                 "%tessc_gl_TessLevelInner = OpVariable %op_a2f32 Output\n"
4390
4391                 "; Tessellation Evaluation Decorations\n"
4392                 "%tesse_per_vertex_out = OpTypeStruct %v4f32 %f32 %a1f32 %a1f32\n"
4393                 "%tesse_op_per_vertex_out = OpTypePointer Output %tesse_per_vertex_out\n"
4394                 "%tesse_stream = OpVariable %tesse_op_per_vertex_out Output\n"
4395                 "%tesse_gl_tessCoord = OpVariable %ip_v3f32 Input\n"
4396                 "%tesse_in_position = OpVariable %ip_a32v4f32 Input\n"
4397                 "%tesse_out_color = OpVariable %op_v4f32 Output\n"
4398                 "%tesse_in_color = OpVariable %ip_a32v4f32 Input\n"
4399
4400                 "; Fragment Variables\n"
4401                 "%frag_fragColor = OpVariable %op_v4f32 Output\n"
4402                 "%frag_vtxColor = OpVariable %ip_v4f32 Input\n"
4403
4404                 "; Vertex Entry\n"
4405                 "%vert_main = OpFunction %void None %fun\n"
4406                 "%vert_label = OpLabel\n"
4407                 "%vert_tmp_position = OpLoad %v4f32 %vert_Position\n"
4408                 "OpStore %vert_vtxPosition %vert_tmp_position\n"
4409                 "%vert_tmp_color = OpLoad %v4f32 %vert_color\n"
4410                 "OpStore %vert_vtxColor %vert_tmp_color\n"
4411                 "OpReturn\n"
4412                 "OpFunctionEnd\n"
4413
4414                 "; Geometry Entry\n"
4415                 "%geom_main = OpFunction %void None %fun\n"
4416                 "%geom_label = OpLabel\n"
4417                 "%geom_gl_in_0_gl_position = OpAccessChain %ip_v4f32 %geom_gl_in %c_i32_0 %c_i32_0\n"
4418                 "%geom_gl_in_1_gl_position = OpAccessChain %ip_v4f32 %geom_gl_in %c_i32_1 %c_i32_0\n"
4419                 "%geom_gl_in_2_gl_position = OpAccessChain %ip_v4f32 %geom_gl_in %c_i32_2 %c_i32_0\n"
4420                 "%geom_in_position_0 = OpLoad %v4f32 %geom_gl_in_0_gl_position\n"
4421                 "%geom_in_position_1 = OpLoad %v4f32 %geom_gl_in_1_gl_position\n"
4422                 "%geom_in_position_2 = OpLoad %v4f32 %geom_gl_in_2_gl_position \n"
4423                 "%geom_in_color_0_ptr = OpAccessChain %ip_v4f32 %geom_in_color %c_i32_0\n"
4424                 "%geom_in_color_1_ptr = OpAccessChain %ip_v4f32 %geom_in_color %c_i32_1\n"
4425                 "%geom_in_color_2_ptr = OpAccessChain %ip_v4f32 %geom_in_color %c_i32_2\n"
4426                 "%geom_in_color_0 = OpLoad %v4f32 %geom_in_color_0_ptr\n"
4427                 "%geom_in_color_1 = OpLoad %v4f32 %geom_in_color_1_ptr\n"
4428                 "%geom_in_color_2 = OpLoad %v4f32 %geom_in_color_2_ptr\n"
4429                 "OpStore %geom_out_gl_position %geom_in_position_0\n"
4430                 "OpStore %geom_out_color %geom_in_color_0\n"
4431                 "OpEmitVertex\n"
4432                 "OpStore %geom_out_gl_position %geom_in_position_1\n"
4433                 "OpStore %geom_out_color %geom_in_color_1\n"
4434                 "OpEmitVertex\n"
4435                 "OpStore %geom_out_gl_position %geom_in_position_2\n"
4436                 "OpStore %geom_out_color %geom_in_color_2\n"
4437                 "OpEmitVertex\n"
4438                 "OpEndPrimitive\n"
4439                 "OpReturn\n"
4440                 "OpFunctionEnd\n"
4441
4442                 "; Tessellation Control Entry\n"
4443                 "%tessc_main = OpFunction %void None %fun\n"
4444                 "%tessc_label = OpLabel\n"
4445                 "%tessc_invocation_id = OpLoad %i32 %tessc_gl_InvocationID\n"
4446                 "%tessc_in_color_ptr = OpAccessChain %ip_v4f32 %tessc_in_color %tessc_invocation_id\n"
4447                 "%tessc_in_position_ptr = OpAccessChain %ip_v4f32 %tessc_in_position %tessc_invocation_id\n"
4448                 "%tessc_in_color_val = OpLoad %v4f32 %tessc_in_color_ptr\n"
4449                 "%tessc_in_position_val = OpLoad %v4f32 %tessc_in_position_ptr\n"
4450                 "%tessc_out_color_ptr = OpAccessChain %op_v4f32 %tessc_out_color %tessc_invocation_id\n"
4451                 "%tessc_out_position_ptr = OpAccessChain %op_v4f32 %tessc_out_position %tessc_invocation_id\n"
4452                 "OpStore %tessc_out_color_ptr %tessc_in_color_val\n"
4453                 "OpStore %tessc_out_position_ptr %tessc_in_position_val\n"
4454                 "%tessc_is_first_invocation = OpIEqual %bool %tessc_invocation_id %c_i32_0\n"
4455                 "OpSelectionMerge %tessc_merge_label None\n"
4456                 "OpBranchConditional %tessc_is_first_invocation %tessc_first_invocation %tessc_merge_label\n"
4457                 "%tessc_first_invocation = OpLabel\n"
4458                 "%tessc_tess_outer_0 = OpAccessChain %op_f32 %tessc_gl_TessLevelOuter %c_i32_0\n"
4459                 "%tessc_tess_outer_1 = OpAccessChain %op_f32 %tessc_gl_TessLevelOuter %c_i32_1\n"
4460                 "%tessc_tess_outer_2 = OpAccessChain %op_f32 %tessc_gl_TessLevelOuter %c_i32_2\n"
4461                 "%tessc_tess_inner = OpAccessChain %op_f32 %tessc_gl_TessLevelInner %c_i32_0\n"
4462                 "OpStore %tessc_tess_outer_0 %c_f32_1\n"
4463                 "OpStore %tessc_tess_outer_1 %c_f32_1\n"
4464                 "OpStore %tessc_tess_outer_2 %c_f32_1\n"
4465                 "OpStore %tessc_tess_inner %c_f32_1\n"
4466                 "OpBranch %tessc_merge_label\n"
4467                 "%tessc_merge_label = OpLabel\n"
4468                 "OpReturn\n"
4469                 "OpFunctionEnd\n"
4470
4471                 "; Tessellation Evaluation Entry\n"
4472                 "%tesse_main = OpFunction %void None %fun\n"
4473                 "%tesse_label = OpLabel\n"
4474                 "%tesse_tc_0_ptr = OpAccessChain %ip_f32 %tesse_gl_tessCoord %c_u32_0\n"
4475                 "%tesse_tc_1_ptr = OpAccessChain %ip_f32 %tesse_gl_tessCoord %c_u32_1\n"
4476                 "%tesse_tc_2_ptr = OpAccessChain %ip_f32 %tesse_gl_tessCoord %c_u32_2\n"
4477                 "%tesse_tc_0 = OpLoad %f32 %tesse_tc_0_ptr\n"
4478                 "%tesse_tc_1 = OpLoad %f32 %tesse_tc_1_ptr\n"
4479                 "%tesse_tc_2 = OpLoad %f32 %tesse_tc_2_ptr\n"
4480                 "%tesse_in_pos_0_ptr = OpAccessChain %ip_v4f32 %tesse_in_position %c_i32_0\n"
4481                 "%tesse_in_pos_1_ptr = OpAccessChain %ip_v4f32 %tesse_in_position %c_i32_1\n"
4482                 "%tesse_in_pos_2_ptr = OpAccessChain %ip_v4f32 %tesse_in_position %c_i32_2\n"
4483                 "%tesse_in_pos_0 = OpLoad %v4f32 %tesse_in_pos_0_ptr\n"
4484                 "%tesse_in_pos_1 = OpLoad %v4f32 %tesse_in_pos_1_ptr\n"
4485                 "%tesse_in_pos_2 = OpLoad %v4f32 %tesse_in_pos_2_ptr\n"
4486                 "%tesse_in_pos_0_weighted = OpVectorTimesScalar %v4f32 %tesse_in_pos_0 %tesse_tc_0\n"
4487                 "%tesse_in_pos_1_weighted = OpVectorTimesScalar %v4f32 %tesse_in_pos_1 %tesse_tc_1\n"
4488                 "%tesse_in_pos_2_weighted = OpVectorTimesScalar %v4f32 %tesse_in_pos_2 %tesse_tc_2\n"
4489                 "%tesse_out_pos_ptr = OpAccessChain %op_v4f32 %tesse_stream %c_i32_0\n"
4490                 "%tesse_in_pos_0_plus_pos_1 = OpFAdd %v4f32 %tesse_in_pos_0_weighted %tesse_in_pos_1_weighted\n"
4491                 "%tesse_computed_out = OpFAdd %v4f32 %tesse_in_pos_0_plus_pos_1 %tesse_in_pos_2_weighted\n"
4492                 "OpStore %tesse_out_pos_ptr %tesse_computed_out\n"
4493                 "%tesse_in_clr_0_ptr = OpAccessChain %ip_v4f32 %tesse_in_color %c_i32_0\n"
4494                 "%tesse_in_clr_1_ptr = OpAccessChain %ip_v4f32 %tesse_in_color %c_i32_1\n"
4495                 "%tesse_in_clr_2_ptr = OpAccessChain %ip_v4f32 %tesse_in_color %c_i32_2\n"
4496                 "%tesse_in_clr_0 = OpLoad %v4f32 %tesse_in_clr_0_ptr\n"
4497                 "%tesse_in_clr_1 = OpLoad %v4f32 %tesse_in_clr_1_ptr\n"
4498                 "%tesse_in_clr_2 = OpLoad %v4f32 %tesse_in_clr_2_ptr\n"
4499                 "%tesse_in_clr_0_weighted = OpVectorTimesScalar %v4f32 %tesse_in_clr_0 %tesse_tc_0\n"
4500                 "%tesse_in_clr_1_weighted = OpVectorTimesScalar %v4f32 %tesse_in_clr_1 %tesse_tc_1\n"
4501                 "%tesse_in_clr_2_weighted = OpVectorTimesScalar %v4f32 %tesse_in_clr_2 %tesse_tc_2\n"
4502                 "%tesse_in_clr_0_plus_col_1 = OpFAdd %v4f32 %tesse_in_clr_0_weighted %tesse_in_clr_1_weighted\n"
4503                 "%tesse_computed_clr = OpFAdd %v4f32 %tesse_in_clr_0_plus_col_1 %tesse_in_clr_2_weighted\n"
4504                 "OpStore %tesse_out_color %tesse_computed_clr\n"
4505                 "OpReturn\n"
4506                 "OpFunctionEnd\n"
4507
4508                 "; Fragment Entry\n"
4509                 "%frag_main = OpFunction %void None %fun\n"
4510                 "%frag_label_main = OpLabel\n"
4511                 "%frag_tmp1 = OpLoad %v4f32 %frag_vtxColor\n"
4512                 "OpStore %frag_fragColor %frag_tmp1\n"
4513                 "OpReturn\n"
4514                 "OpFunctionEnd\n";
4515 }
4516
4517 // This has two shaders of each stage. The first
4518 // is a passthrough, the second inverts the color.
4519 void createMultipleEntries(vk::SourceCollections& dst, InstanceContext)
4520 {
4521         dst.spirvAsmSources.add("vert") <<
4522         // This module contains 2 vertex shaders. One that is a passthrough
4523         // and a second that inverts the color of the output (1.0 - color).
4524                 "OpCapability Shader\n"
4525                 "OpMemoryModel Logical GLSL450\n"
4526                 "OpEntryPoint Vertex %main \"vert1\" %Position %vtxColor %color %vtxPosition %vertex_id %instance_id\n"
4527                 "OpEntryPoint Vertex %main2 \"vert2\" %Position %vtxColor %color %vtxPosition %vertex_id %instance_id\n"
4528
4529                 "OpName %main \"vert1\"\n"
4530                 "OpName %main2 \"vert2\"\n"
4531                 "OpName %vtxPosition \"vtxPosition\"\n"
4532                 "OpName %Position \"position\"\n"
4533                 "OpName %vtxColor \"vtxColor\"\n"
4534                 "OpName %color \"color\"\n"
4535                 "OpName %vertex_id \"gl_VertexIndex\"\n"
4536                 "OpName %instance_id \"gl_InstanceIndex\"\n"
4537
4538                 "OpDecorate %vtxPosition Location 2\n"
4539                 "OpDecorate %Position Location 0\n"
4540                 "OpDecorate %vtxColor Location 1\n"
4541                 "OpDecorate %color Location 1\n"
4542                 "OpDecorate %vertex_id BuiltIn VertexIndex\n"
4543                 "OpDecorate %instance_id BuiltIn InstanceIndex\n"
4544                 SPIRV_ASSEMBLY_TYPES
4545                 SPIRV_ASSEMBLY_CONSTANTS
4546                 SPIRV_ASSEMBLY_ARRAYS
4547                 "%cval = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
4548                 "%vtxPosition = OpVariable %op_v4f32 Output\n"
4549                 "%Position = OpVariable %ip_v4f32 Input\n"
4550                 "%vtxColor = OpVariable %op_v4f32 Output\n"
4551                 "%color = OpVariable %ip_v4f32 Input\n"
4552                 "%vertex_id = OpVariable %ip_i32 Input\n"
4553                 "%instance_id = OpVariable %ip_i32 Input\n"
4554
4555                 "%main = OpFunction %void None %fun\n"
4556                 "%label = OpLabel\n"
4557                 "%tmp_position = OpLoad %v4f32 %Position\n"
4558                 "OpStore %vtxPosition %tmp_position\n"
4559                 "%tmp_color = OpLoad %v4f32 %color\n"
4560                 "OpStore %vtxColor %tmp_color\n"
4561                 "OpReturn\n"
4562                 "OpFunctionEnd\n"
4563
4564                 "%main2 = OpFunction %void None %fun\n"
4565                 "%label2 = OpLabel\n"
4566                 "%tmp_position2 = OpLoad %v4f32 %Position\n"
4567                 "OpStore %vtxPosition %tmp_position2\n"
4568                 "%tmp_color2 = OpLoad %v4f32 %color\n"
4569                 "%tmp_color3 = OpFSub %v4f32 %cval %tmp_color2\n"
4570                 "%tmp_color4 = OpVectorInsertDynamic %v4f32 %tmp_color3 %c_f32_1 %c_i32_3\n"
4571                 "OpStore %vtxColor %tmp_color4\n"
4572                 "OpReturn\n"
4573                 "OpFunctionEnd\n";
4574
4575         dst.spirvAsmSources.add("frag") <<
4576                 // This is a single module that contains 2 fragment shaders.
4577                 // One that passes color through and the other that inverts the output
4578                 // color (1.0 - color).
4579                 "OpCapability Shader\n"
4580                 "OpMemoryModel Logical GLSL450\n"
4581                 "OpEntryPoint Fragment %main \"frag1\" %vtxColor %fragColor\n"
4582                 "OpEntryPoint Fragment %main2 \"frag2\" %vtxColor %fragColor\n"
4583                 "OpExecutionMode %main OriginUpperLeft\n"
4584                 "OpExecutionMode %main2 OriginUpperLeft\n"
4585
4586                 "OpName %main \"frag1\"\n"
4587                 "OpName %main2 \"frag2\"\n"
4588                 "OpName %fragColor \"fragColor\"\n"
4589                 "OpName %vtxColor \"vtxColor\"\n"
4590                 "OpDecorate %fragColor Location 0\n"
4591                 "OpDecorate %vtxColor Location 1\n"
4592                 SPIRV_ASSEMBLY_TYPES
4593                 SPIRV_ASSEMBLY_CONSTANTS
4594                 SPIRV_ASSEMBLY_ARRAYS
4595                 "%cval = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
4596                 "%fragColor = OpVariable %op_v4f32 Output\n"
4597                 "%vtxColor = OpVariable %ip_v4f32 Input\n"
4598
4599                 "%main = OpFunction %void None %fun\n"
4600                 "%label_main = OpLabel\n"
4601                 "%tmp1 = OpLoad %v4f32 %vtxColor\n"
4602                 "OpStore %fragColor %tmp1\n"
4603                 "OpReturn\n"
4604                 "OpFunctionEnd\n"
4605
4606                 "%main2 = OpFunction %void None %fun\n"
4607                 "%label_main2 = OpLabel\n"
4608                 "%tmp2 = OpLoad %v4f32 %vtxColor\n"
4609                 "%tmp3 = OpFSub %v4f32 %cval %tmp2\n"
4610                 "%tmp4 = OpVectorInsertDynamic %v4f32 %tmp3 %c_f32_1 %c_i32_3\n"
4611                 "OpStore %fragColor %tmp4\n"
4612                 "OpReturn\n"
4613                 "OpFunctionEnd\n";
4614
4615         dst.spirvAsmSources.add("geom") <<
4616                 "OpCapability Geometry\n"
4617                 "OpCapability ClipDistance\n"
4618                 "OpCapability CullDistance\n"
4619                 "OpMemoryModel Logical GLSL450\n"
4620                 "OpEntryPoint Geometry %geom1_main \"geom1\" %out_gl_position %gl_in %out_color %in_color\n"
4621                 "OpEntryPoint Geometry %geom2_main \"geom2\" %out_gl_position %gl_in %out_color %in_color\n"
4622                 "OpExecutionMode %geom1_main Triangles\n"
4623                 "OpExecutionMode %geom2_main Triangles\n"
4624                 "OpExecutionMode %geom1_main OutputTriangleStrip\n"
4625                 "OpExecutionMode %geom2_main OutputTriangleStrip\n"
4626                 "OpExecutionMode %geom1_main OutputVertices 3\n"
4627                 "OpExecutionMode %geom2_main OutputVertices 3\n"
4628                 "OpName %geom1_main \"geom1\"\n"
4629                 "OpName %geom2_main \"geom2\"\n"
4630                 "OpName %per_vertex_in \"gl_PerVertex\"\n"
4631                 "OpMemberName %per_vertex_in 0 \"gl_Position\"\n"
4632                 "OpMemberName %per_vertex_in 1 \"gl_PointSize\"\n"
4633                 "OpMemberName %per_vertex_in 2 \"gl_ClipDistance\"\n"
4634                 "OpMemberName %per_vertex_in 3 \"gl_CullDistance\"\n"
4635                 "OpName %gl_in \"gl_in\"\n"
4636                 "OpName %out_color \"out_color\"\n"
4637                 "OpName %in_color \"in_color\"\n"
4638                 "OpDecorate %out_gl_position BuiltIn Position\n"
4639                 "OpMemberDecorate %per_vertex_in 0 BuiltIn Position\n"
4640                 "OpMemberDecorate %per_vertex_in 1 BuiltIn PointSize\n"
4641                 "OpMemberDecorate %per_vertex_in 2 BuiltIn ClipDistance\n"
4642                 "OpMemberDecorate %per_vertex_in 3 BuiltIn CullDistance\n"
4643                 "OpDecorate %per_vertex_in Block\n"
4644                 "OpDecorate %out_color Location 1\n"
4645                 "OpDecorate %in_color Location 1\n"
4646                 SPIRV_ASSEMBLY_TYPES
4647                 SPIRV_ASSEMBLY_CONSTANTS
4648                 SPIRV_ASSEMBLY_ARRAYS
4649                 "%cval = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
4650                 "%per_vertex_in = OpTypeStruct %v4f32 %f32 %a1f32 %a1f32\n"
4651                 "%a3_per_vertex_in = OpTypeArray %per_vertex_in %c_u32_3\n"
4652                 "%ip_a3_per_vertex_in = OpTypePointer Input %a3_per_vertex_in\n"
4653                 "%gl_in = OpVariable %ip_a3_per_vertex_in Input\n"
4654                 "%out_color = OpVariable %op_v4f32 Output\n"
4655                 "%in_color = OpVariable %ip_a3v4f32 Input\n"
4656                 "%out_gl_position = OpVariable %op_v4f32 Output\n"
4657
4658                 "%geom1_main = OpFunction %void None %fun\n"
4659                 "%geom1_label = OpLabel\n"
4660                 "%geom1_gl_in_0_gl_position = OpAccessChain %ip_v4f32 %gl_in %c_i32_0 %c_i32_0\n"
4661                 "%geom1_gl_in_1_gl_position = OpAccessChain %ip_v4f32 %gl_in %c_i32_1 %c_i32_0\n"
4662                 "%geom1_gl_in_2_gl_position = OpAccessChain %ip_v4f32 %gl_in %c_i32_2 %c_i32_0\n"
4663                 "%geom1_in_position_0 = OpLoad %v4f32 %geom1_gl_in_0_gl_position\n"
4664                 "%geom1_in_position_1 = OpLoad %v4f32 %geom1_gl_in_1_gl_position\n"
4665                 "%geom1_in_position_2 = OpLoad %v4f32 %geom1_gl_in_2_gl_position \n"
4666                 "%geom1_in_color_0_ptr = OpAccessChain %ip_v4f32 %in_color %c_i32_0\n"
4667                 "%geom1_in_color_1_ptr = OpAccessChain %ip_v4f32 %in_color %c_i32_1\n"
4668                 "%geom1_in_color_2_ptr = OpAccessChain %ip_v4f32 %in_color %c_i32_2\n"
4669                 "%geom1_in_color_0 = OpLoad %v4f32 %geom1_in_color_0_ptr\n"
4670                 "%geom1_in_color_1 = OpLoad %v4f32 %geom1_in_color_1_ptr\n"
4671                 "%geom1_in_color_2 = OpLoad %v4f32 %geom1_in_color_2_ptr\n"
4672                 "OpStore %out_gl_position %geom1_in_position_0\n"
4673                 "OpStore %out_color %geom1_in_color_0\n"
4674                 "OpEmitVertex\n"
4675                 "OpStore %out_gl_position %geom1_in_position_1\n"
4676                 "OpStore %out_color %geom1_in_color_1\n"
4677                 "OpEmitVertex\n"
4678                 "OpStore %out_gl_position %geom1_in_position_2\n"
4679                 "OpStore %out_color %geom1_in_color_2\n"
4680                 "OpEmitVertex\n"
4681                 "OpEndPrimitive\n"
4682                 "OpReturn\n"
4683                 "OpFunctionEnd\n"
4684
4685                 "%geom2_main = OpFunction %void None %fun\n"
4686                 "%geom2_label = OpLabel\n"
4687                 "%geom2_gl_in_0_gl_position = OpAccessChain %ip_v4f32 %gl_in %c_i32_0 %c_i32_0\n"
4688                 "%geom2_gl_in_1_gl_position = OpAccessChain %ip_v4f32 %gl_in %c_i32_1 %c_i32_0\n"
4689                 "%geom2_gl_in_2_gl_position = OpAccessChain %ip_v4f32 %gl_in %c_i32_2 %c_i32_0\n"
4690                 "%geom2_in_position_0 = OpLoad %v4f32 %geom2_gl_in_0_gl_position\n"
4691                 "%geom2_in_position_1 = OpLoad %v4f32 %geom2_gl_in_1_gl_position\n"
4692                 "%geom2_in_position_2 = OpLoad %v4f32 %geom2_gl_in_2_gl_position \n"
4693                 "%geom2_in_color_0_ptr = OpAccessChain %ip_v4f32 %in_color %c_i32_0\n"
4694                 "%geom2_in_color_1_ptr = OpAccessChain %ip_v4f32 %in_color %c_i32_1\n"
4695                 "%geom2_in_color_2_ptr = OpAccessChain %ip_v4f32 %in_color %c_i32_2\n"
4696                 "%geom2_in_color_0 = OpLoad %v4f32 %geom2_in_color_0_ptr\n"
4697                 "%geom2_in_color_1 = OpLoad %v4f32 %geom2_in_color_1_ptr\n"
4698                 "%geom2_in_color_2 = OpLoad %v4f32 %geom2_in_color_2_ptr\n"
4699                 "%geom2_transformed_in_color_0 = OpFSub %v4f32 %cval %geom2_in_color_0\n"
4700                 "%geom2_transformed_in_color_1 = OpFSub %v4f32 %cval %geom2_in_color_1\n"
4701                 "%geom2_transformed_in_color_2 = OpFSub %v4f32 %cval %geom2_in_color_2\n"
4702                 "%geom2_transformed_in_color_0_a = OpVectorInsertDynamic %v4f32 %geom2_transformed_in_color_0 %c_f32_1 %c_i32_3\n"
4703                 "%geom2_transformed_in_color_1_a = OpVectorInsertDynamic %v4f32 %geom2_transformed_in_color_1 %c_f32_1 %c_i32_3\n"
4704                 "%geom2_transformed_in_color_2_a = OpVectorInsertDynamic %v4f32 %geom2_transformed_in_color_2 %c_f32_1 %c_i32_3\n"
4705                 "OpStore %out_gl_position %geom2_in_position_0\n"
4706                 "OpStore %out_color %geom2_transformed_in_color_0_a\n"
4707                 "OpEmitVertex\n"
4708                 "OpStore %out_gl_position %geom2_in_position_1\n"
4709                 "OpStore %out_color %geom2_transformed_in_color_1_a\n"
4710                 "OpEmitVertex\n"
4711                 "OpStore %out_gl_position %geom2_in_position_2\n"
4712                 "OpStore %out_color %geom2_transformed_in_color_2_a\n"
4713                 "OpEmitVertex\n"
4714                 "OpEndPrimitive\n"
4715                 "OpReturn\n"
4716                 "OpFunctionEnd\n";
4717
4718         dst.spirvAsmSources.add("tessc") <<
4719                 "OpCapability Tessellation\n"
4720                 "OpMemoryModel Logical GLSL450\n"
4721                 "OpEntryPoint TessellationControl %tessc1_main \"tessc1\" %out_color %gl_InvocationID %in_color %out_position %in_position %gl_TessLevelOuter %gl_TessLevelInner\n"
4722                 "OpEntryPoint TessellationControl %tessc2_main \"tessc2\" %out_color %gl_InvocationID %in_color %out_position %in_position %gl_TessLevelOuter %gl_TessLevelInner\n"
4723                 "OpExecutionMode %tessc1_main OutputVertices 3\n"
4724                 "OpExecutionMode %tessc2_main OutputVertices 3\n"
4725                 "OpName %tessc1_main \"tessc1\"\n"
4726                 "OpName %tessc2_main \"tessc2\"\n"
4727                 "OpName %out_color \"out_color\"\n"
4728                 "OpName %gl_InvocationID \"gl_InvocationID\"\n"
4729                 "OpName %in_color \"in_color\"\n"
4730                 "OpName %out_position \"out_position\"\n"
4731                 "OpName %in_position \"in_position\"\n"
4732                 "OpName %gl_TessLevelOuter \"gl_TessLevelOuter\"\n"
4733                 "OpName %gl_TessLevelInner \"gl_TessLevelInner\"\n"
4734                 "OpDecorate %out_color Location 1\n"
4735                 "OpDecorate %gl_InvocationID BuiltIn InvocationId\n"
4736                 "OpDecorate %in_color Location 1\n"
4737                 "OpDecorate %out_position Location 2\n"
4738                 "OpDecorate %in_position Location 2\n"
4739                 "OpDecorate %gl_TessLevelOuter Patch\n"
4740                 "OpDecorate %gl_TessLevelOuter BuiltIn TessLevelOuter\n"
4741                 "OpDecorate %gl_TessLevelInner Patch\n"
4742                 "OpDecorate %gl_TessLevelInner BuiltIn TessLevelInner\n"
4743                 SPIRV_ASSEMBLY_TYPES
4744                 SPIRV_ASSEMBLY_CONSTANTS
4745                 SPIRV_ASSEMBLY_ARRAYS
4746                 "%cval = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
4747                 "%out_color = OpVariable %op_a3v4f32 Output\n"
4748                 "%gl_InvocationID = OpVariable %ip_i32 Input\n"
4749                 "%in_color = OpVariable %ip_a32v4f32 Input\n"
4750                 "%out_position = OpVariable %op_a3v4f32 Output\n"
4751                 "%in_position = OpVariable %ip_a32v4f32 Input\n"
4752                 "%gl_TessLevelOuter = OpVariable %op_a4f32 Output\n"
4753                 "%gl_TessLevelInner = OpVariable %op_a2f32 Output\n"
4754
4755                 "%tessc1_main = OpFunction %void None %fun\n"
4756                 "%tessc1_label = OpLabel\n"
4757                 "%tessc1_invocation_id = OpLoad %i32 %gl_InvocationID\n"
4758                 "%tessc1_in_color_ptr = OpAccessChain %ip_v4f32 %in_color %tessc1_invocation_id\n"
4759                 "%tessc1_in_position_ptr = OpAccessChain %ip_v4f32 %in_position %tessc1_invocation_id\n"
4760                 "%tessc1_in_color_val = OpLoad %v4f32 %tessc1_in_color_ptr\n"
4761                 "%tessc1_in_position_val = OpLoad %v4f32 %tessc1_in_position_ptr\n"
4762                 "%tessc1_out_color_ptr = OpAccessChain %op_v4f32 %out_color %tessc1_invocation_id\n"
4763                 "%tessc1_out_position_ptr = OpAccessChain %op_v4f32 %out_position %tessc1_invocation_id\n"
4764                 "OpStore %tessc1_out_color_ptr %tessc1_in_color_val\n"
4765                 "OpStore %tessc1_out_position_ptr %tessc1_in_position_val\n"
4766                 "%tessc1_is_first_invocation = OpIEqual %bool %tessc1_invocation_id %c_i32_0\n"
4767                 "OpSelectionMerge %tessc1_merge_label None\n"
4768                 "OpBranchConditional %tessc1_is_first_invocation %tessc1_first_invocation %tessc1_merge_label\n"
4769                 "%tessc1_first_invocation = OpLabel\n"
4770                 "%tessc1_tess_outer_0 = OpAccessChain %op_f32 %gl_TessLevelOuter %c_i32_0\n"
4771                 "%tessc1_tess_outer_1 = OpAccessChain %op_f32 %gl_TessLevelOuter %c_i32_1\n"
4772                 "%tessc1_tess_outer_2 = OpAccessChain %op_f32 %gl_TessLevelOuter %c_i32_2\n"
4773                 "%tessc1_tess_inner = OpAccessChain %op_f32 %gl_TessLevelInner %c_i32_0\n"
4774                 "OpStore %tessc1_tess_outer_0 %c_f32_1\n"
4775                 "OpStore %tessc1_tess_outer_1 %c_f32_1\n"
4776                 "OpStore %tessc1_tess_outer_2 %c_f32_1\n"
4777                 "OpStore %tessc1_tess_inner %c_f32_1\n"
4778                 "OpBranch %tessc1_merge_label\n"
4779                 "%tessc1_merge_label = OpLabel\n"
4780                 "OpReturn\n"
4781                 "OpFunctionEnd\n"
4782
4783                 "%tessc2_main = OpFunction %void None %fun\n"
4784                 "%tessc2_label = OpLabel\n"
4785                 "%tessc2_invocation_id = OpLoad %i32 %gl_InvocationID\n"
4786                 "%tessc2_in_color_ptr = OpAccessChain %ip_v4f32 %in_color %tessc2_invocation_id\n"
4787                 "%tessc2_in_position_ptr = OpAccessChain %ip_v4f32 %in_position %tessc2_invocation_id\n"
4788                 "%tessc2_in_color_val = OpLoad %v4f32 %tessc2_in_color_ptr\n"
4789                 "%tessc2_in_position_val = OpLoad %v4f32 %tessc2_in_position_ptr\n"
4790                 "%tessc2_out_color_ptr = OpAccessChain %op_v4f32 %out_color %tessc2_invocation_id\n"
4791                 "%tessc2_out_position_ptr = OpAccessChain %op_v4f32 %out_position %tessc2_invocation_id\n"
4792                 "%tessc2_transformed_color = OpFSub %v4f32 %cval %tessc2_in_color_val\n"
4793                 "%tessc2_transformed_color_a = OpVectorInsertDynamic %v4f32 %tessc2_transformed_color %c_f32_1 %c_i32_3\n"
4794                 "OpStore %tessc2_out_color_ptr %tessc2_transformed_color_a\n"
4795                 "OpStore %tessc2_out_position_ptr %tessc2_in_position_val\n"
4796                 "%tessc2_is_first_invocation = OpIEqual %bool %tessc2_invocation_id %c_i32_0\n"
4797                 "OpSelectionMerge %tessc2_merge_label None\n"
4798                 "OpBranchConditional %tessc2_is_first_invocation %tessc2_first_invocation %tessc2_merge_label\n"
4799                 "%tessc2_first_invocation = OpLabel\n"
4800                 "%tessc2_tess_outer_0 = OpAccessChain %op_f32 %gl_TessLevelOuter %c_i32_0\n"
4801                 "%tessc2_tess_outer_1 = OpAccessChain %op_f32 %gl_TessLevelOuter %c_i32_1\n"
4802                 "%tessc2_tess_outer_2 = OpAccessChain %op_f32 %gl_TessLevelOuter %c_i32_2\n"
4803                 "%tessc2_tess_inner = OpAccessChain %op_f32 %gl_TessLevelInner %c_i32_0\n"
4804                 "OpStore %tessc2_tess_outer_0 %c_f32_1\n"
4805                 "OpStore %tessc2_tess_outer_1 %c_f32_1\n"
4806                 "OpStore %tessc2_tess_outer_2 %c_f32_1\n"
4807                 "OpStore %tessc2_tess_inner %c_f32_1\n"
4808                 "OpBranch %tessc2_merge_label\n"
4809                 "%tessc2_merge_label = OpLabel\n"
4810                 "OpReturn\n"
4811                 "OpFunctionEnd\n";
4812
4813         dst.spirvAsmSources.add("tesse") <<
4814                 "OpCapability Tessellation\n"
4815                 "OpCapability ClipDistance\n"
4816                 "OpCapability CullDistance\n"
4817                 "OpMemoryModel Logical GLSL450\n"
4818                 "OpEntryPoint TessellationEvaluation %tesse1_main \"tesse1\" %stream %gl_tessCoord %in_position %out_color %in_color \n"
4819                 "OpEntryPoint TessellationEvaluation %tesse2_main \"tesse2\" %stream %gl_tessCoord %in_position %out_color %in_color \n"
4820                 "OpExecutionMode %tesse1_main Triangles\n"
4821                 "OpExecutionMode %tesse1_main SpacingEqual\n"
4822                 "OpExecutionMode %tesse1_main VertexOrderCcw\n"
4823                 "OpExecutionMode %tesse2_main Triangles\n"
4824                 "OpExecutionMode %tesse2_main SpacingEqual\n"
4825                 "OpExecutionMode %tesse2_main VertexOrderCcw\n"
4826                 "OpName %tesse1_main \"tesse1\"\n"
4827                 "OpName %tesse2_main \"tesse2\"\n"
4828                 "OpName %per_vertex_out \"gl_PerVertex\"\n"
4829                 "OpMemberName %per_vertex_out 0 \"gl_Position\"\n"
4830                 "OpMemberName %per_vertex_out 1 \"gl_PointSize\"\n"
4831                 "OpMemberName %per_vertex_out 2 \"gl_ClipDistance\"\n"
4832                 "OpMemberName %per_vertex_out 3 \"gl_CullDistance\"\n"
4833                 "OpName %stream \"\"\n"
4834                 "OpName %gl_tessCoord \"gl_TessCoord\"\n"
4835                 "OpName %in_position \"in_position\"\n"
4836                 "OpName %out_color \"out_color\"\n"
4837                 "OpName %in_color \"in_color\"\n"
4838                 "OpMemberDecorate %per_vertex_out 0 BuiltIn Position\n"
4839                 "OpMemberDecorate %per_vertex_out 1 BuiltIn PointSize\n"
4840                 "OpMemberDecorate %per_vertex_out 2 BuiltIn ClipDistance\n"
4841                 "OpMemberDecorate %per_vertex_out 3 BuiltIn CullDistance\n"
4842                 "OpDecorate %per_vertex_out Block\n"
4843                 "OpDecorate %gl_tessCoord BuiltIn TessCoord\n"
4844                 "OpDecorate %in_position Location 2\n"
4845                 "OpDecorate %out_color Location 1\n"
4846                 "OpDecorate %in_color Location 1\n"
4847                 SPIRV_ASSEMBLY_TYPES
4848                 SPIRV_ASSEMBLY_CONSTANTS
4849                 SPIRV_ASSEMBLY_ARRAYS
4850                 "%cval = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
4851                 "%per_vertex_out = OpTypeStruct %v4f32 %f32 %a1f32 %a1f32\n"
4852                 "%op_per_vertex_out = OpTypePointer Output %per_vertex_out\n"
4853                 "%stream = OpVariable %op_per_vertex_out Output\n"
4854                 "%gl_tessCoord = OpVariable %ip_v3f32 Input\n"
4855                 "%in_position = OpVariable %ip_a32v4f32 Input\n"
4856                 "%out_color = OpVariable %op_v4f32 Output\n"
4857                 "%in_color = OpVariable %ip_a32v4f32 Input\n"
4858
4859                 "%tesse1_main = OpFunction %void None %fun\n"
4860                 "%tesse1_label = OpLabel\n"
4861                 "%tesse1_tc_0_ptr = OpAccessChain %ip_f32 %gl_tessCoord %c_u32_0\n"
4862                 "%tesse1_tc_1_ptr = OpAccessChain %ip_f32 %gl_tessCoord %c_u32_1\n"
4863                 "%tesse1_tc_2_ptr = OpAccessChain %ip_f32 %gl_tessCoord %c_u32_2\n"
4864                 "%tesse1_tc_0 = OpLoad %f32 %tesse1_tc_0_ptr\n"
4865                 "%tesse1_tc_1 = OpLoad %f32 %tesse1_tc_1_ptr\n"
4866                 "%tesse1_tc_2 = OpLoad %f32 %tesse1_tc_2_ptr\n"
4867                 "%tesse1_in_pos_0_ptr = OpAccessChain %ip_v4f32 %in_position %c_i32_0\n"
4868                 "%tesse1_in_pos_1_ptr = OpAccessChain %ip_v4f32 %in_position %c_i32_1\n"
4869                 "%tesse1_in_pos_2_ptr = OpAccessChain %ip_v4f32 %in_position %c_i32_2\n"
4870                 "%tesse1_in_pos_0 = OpLoad %v4f32 %tesse1_in_pos_0_ptr\n"
4871                 "%tesse1_in_pos_1 = OpLoad %v4f32 %tesse1_in_pos_1_ptr\n"
4872                 "%tesse1_in_pos_2 = OpLoad %v4f32 %tesse1_in_pos_2_ptr\n"
4873                 "%tesse1_in_pos_0_weighted = OpVectorTimesScalar %v4f32 %tesse1_in_pos_0 %tesse1_tc_0\n"
4874                 "%tesse1_in_pos_1_weighted = OpVectorTimesScalar %v4f32 %tesse1_in_pos_1 %tesse1_tc_1\n"
4875                 "%tesse1_in_pos_2_weighted = OpVectorTimesScalar %v4f32 %tesse1_in_pos_2 %tesse1_tc_2\n"
4876                 "%tesse1_out_pos_ptr = OpAccessChain %op_v4f32 %stream %c_i32_0\n"
4877                 "%tesse1_in_pos_0_plus_pos_1 = OpFAdd %v4f32 %tesse1_in_pos_0_weighted %tesse1_in_pos_1_weighted\n"
4878                 "%tesse1_computed_out = OpFAdd %v4f32 %tesse1_in_pos_0_plus_pos_1 %tesse1_in_pos_2_weighted\n"
4879                 "OpStore %tesse1_out_pos_ptr %tesse1_computed_out\n"
4880                 "%tesse1_in_clr_0_ptr = OpAccessChain %ip_v4f32 %in_color %c_i32_0\n"
4881                 "%tesse1_in_clr_1_ptr = OpAccessChain %ip_v4f32 %in_color %c_i32_1\n"
4882                 "%tesse1_in_clr_2_ptr = OpAccessChain %ip_v4f32 %in_color %c_i32_2\n"
4883                 "%tesse1_in_clr_0 = OpLoad %v4f32 %tesse1_in_clr_0_ptr\n"
4884                 "%tesse1_in_clr_1 = OpLoad %v4f32 %tesse1_in_clr_1_ptr\n"
4885                 "%tesse1_in_clr_2 = OpLoad %v4f32 %tesse1_in_clr_2_ptr\n"
4886                 "%tesse1_in_clr_0_weighted = OpVectorTimesScalar %v4f32 %tesse1_in_clr_0 %tesse1_tc_0\n"
4887                 "%tesse1_in_clr_1_weighted = OpVectorTimesScalar %v4f32 %tesse1_in_clr_1 %tesse1_tc_1\n"
4888                 "%tesse1_in_clr_2_weighted = OpVectorTimesScalar %v4f32 %tesse1_in_clr_2 %tesse1_tc_2\n"
4889                 "%tesse1_in_clr_0_plus_col_1 = OpFAdd %v4f32 %tesse1_in_clr_0_weighted %tesse1_in_clr_1_weighted\n"
4890                 "%tesse1_computed_clr = OpFAdd %v4f32 %tesse1_in_clr_0_plus_col_1 %tesse1_in_clr_2_weighted\n"
4891                 "OpStore %out_color %tesse1_computed_clr\n"
4892                 "OpReturn\n"
4893                 "OpFunctionEnd\n"
4894
4895                 "%tesse2_main = OpFunction %void None %fun\n"
4896                 "%tesse2_label = OpLabel\n"
4897                 "%tesse2_tc_0_ptr = OpAccessChain %ip_f32 %gl_tessCoord %c_u32_0\n"
4898                 "%tesse2_tc_1_ptr = OpAccessChain %ip_f32 %gl_tessCoord %c_u32_1\n"
4899                 "%tesse2_tc_2_ptr = OpAccessChain %ip_f32 %gl_tessCoord %c_u32_2\n"
4900                 "%tesse2_tc_0 = OpLoad %f32 %tesse2_tc_0_ptr\n"
4901                 "%tesse2_tc_1 = OpLoad %f32 %tesse2_tc_1_ptr\n"
4902                 "%tesse2_tc_2 = OpLoad %f32 %tesse2_tc_2_ptr\n"
4903                 "%tesse2_in_pos_0_ptr = OpAccessChain %ip_v4f32 %in_position %c_i32_0\n"
4904                 "%tesse2_in_pos_1_ptr = OpAccessChain %ip_v4f32 %in_position %c_i32_1\n"
4905                 "%tesse2_in_pos_2_ptr = OpAccessChain %ip_v4f32 %in_position %c_i32_2\n"
4906                 "%tesse2_in_pos_0 = OpLoad %v4f32 %tesse2_in_pos_0_ptr\n"
4907                 "%tesse2_in_pos_1 = OpLoad %v4f32 %tesse2_in_pos_1_ptr\n"
4908                 "%tesse2_in_pos_2 = OpLoad %v4f32 %tesse2_in_pos_2_ptr\n"
4909                 "%tesse2_in_pos_0_weighted = OpVectorTimesScalar %v4f32 %tesse2_in_pos_0 %tesse2_tc_0\n"
4910                 "%tesse2_in_pos_1_weighted = OpVectorTimesScalar %v4f32 %tesse2_in_pos_1 %tesse2_tc_1\n"
4911                 "%tesse2_in_pos_2_weighted = OpVectorTimesScalar %v4f32 %tesse2_in_pos_2 %tesse2_tc_2\n"
4912                 "%tesse2_out_pos_ptr = OpAccessChain %op_v4f32 %stream %c_i32_0\n"
4913                 "%tesse2_in_pos_0_plus_pos_1 = OpFAdd %v4f32 %tesse2_in_pos_0_weighted %tesse2_in_pos_1_weighted\n"
4914                 "%tesse2_computed_out = OpFAdd %v4f32 %tesse2_in_pos_0_plus_pos_1 %tesse2_in_pos_2_weighted\n"
4915                 "OpStore %tesse2_out_pos_ptr %tesse2_computed_out\n"
4916                 "%tesse2_in_clr_0_ptr = OpAccessChain %ip_v4f32 %in_color %c_i32_0\n"
4917                 "%tesse2_in_clr_1_ptr = OpAccessChain %ip_v4f32 %in_color %c_i32_1\n"
4918                 "%tesse2_in_clr_2_ptr = OpAccessChain %ip_v4f32 %in_color %c_i32_2\n"
4919                 "%tesse2_in_clr_0 = OpLoad %v4f32 %tesse2_in_clr_0_ptr\n"
4920                 "%tesse2_in_clr_1 = OpLoad %v4f32 %tesse2_in_clr_1_ptr\n"
4921                 "%tesse2_in_clr_2 = OpLoad %v4f32 %tesse2_in_clr_2_ptr\n"
4922                 "%tesse2_in_clr_0_weighted = OpVectorTimesScalar %v4f32 %tesse2_in_clr_0 %tesse2_tc_0\n"
4923                 "%tesse2_in_clr_1_weighted = OpVectorTimesScalar %v4f32 %tesse2_in_clr_1 %tesse2_tc_1\n"
4924                 "%tesse2_in_clr_2_weighted = OpVectorTimesScalar %v4f32 %tesse2_in_clr_2 %tesse2_tc_2\n"
4925                 "%tesse2_in_clr_0_plus_col_1 = OpFAdd %v4f32 %tesse2_in_clr_0_weighted %tesse2_in_clr_1_weighted\n"
4926                 "%tesse2_computed_clr = OpFAdd %v4f32 %tesse2_in_clr_0_plus_col_1 %tesse2_in_clr_2_weighted\n"
4927                 "%tesse2_clr_transformed = OpFSub %v4f32 %cval %tesse2_computed_clr\n"
4928                 "%tesse2_clr_transformed_a = OpVectorInsertDynamic %v4f32 %tesse2_clr_transformed %c_f32_1 %c_i32_3\n"
4929                 "OpStore %out_color %tesse2_clr_transformed_a\n"
4930                 "OpReturn\n"
4931                 "OpFunctionEnd\n";
4932 }
4933
4934 // Sets up and runs a Vulkan pipeline, then spot-checks the resulting image.
4935 // Feeds the pipeline a set of colored triangles, which then must occur in the
4936 // rendered image.  The surface is cleared before executing the pipeline, so
4937 // whatever the shaders draw can be directly spot-checked.
4938 TestStatus runAndVerifyDefaultPipeline (Context& context, InstanceContext instance)
4939 {
4940         const VkDevice                                                          vkDevice                                = context.getDevice();
4941         const DeviceInterface&                                          vk                                              = context.getDeviceInterface();
4942         const VkQueue                                                           queue                                   = context.getUniversalQueue();
4943         const deUint32                                                          queueFamilyIndex                = context.getUniversalQueueFamilyIndex();
4944         const tcu::UVec2                                                        renderSize                              (256, 256);
4945         vector<ModuleHandleSp>                                          modules;
4946         map<VkShaderStageFlagBits, VkShaderModule>      moduleByStage;
4947         const int                                                                       testSpecificSeed                = 31354125;
4948         const int                                                                       seed                                    = context.getTestContext().getCommandLine().getBaseSeed() ^ testSpecificSeed;
4949         bool                                                                            supportsGeometry                = false;
4950         bool                                                                            supportsTessellation    = false;
4951         bool                                                                            hasTessellation         = false;
4952
4953         const VkPhysicalDeviceFeatures&                         features                                = context.getDeviceFeatures();
4954         supportsGeometry                = features.geometryShader == VK_TRUE;
4955         supportsTessellation    = features.tessellationShader == VK_TRUE;
4956         hasTessellation                 = (instance.requiredStages & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) ||
4957                                                                 (instance.requiredStages & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
4958
4959         if (hasTessellation && !supportsTessellation)
4960         {
4961                 throw tcu::NotSupportedError(std::string("Tessellation not supported"));
4962         }
4963
4964         if ((instance.requiredStages & VK_SHADER_STAGE_GEOMETRY_BIT) &&
4965                 !supportsGeometry)
4966         {
4967                 throw tcu::NotSupportedError(std::string("Geometry not supported"));
4968         }
4969
4970         de::Random(seed).shuffle(instance.inputColors, instance.inputColors+4);
4971         de::Random(seed).shuffle(instance.outputColors, instance.outputColors+4);
4972         const Vec4                                                              vertexData[]                    =
4973         {
4974                 // Upper left corner:
4975                 Vec4(-1.0f, -1.0f, 0.0f, 1.0f), instance.inputColors[0].toVec(),
4976                 Vec4(-0.5f, -1.0f, 0.0f, 1.0f), instance.inputColors[0].toVec(),
4977                 Vec4(-1.0f, -0.5f, 0.0f, 1.0f), instance.inputColors[0].toVec(),
4978
4979                 // Upper right corner:
4980                 Vec4(+0.5f, -1.0f, 0.0f, 1.0f), instance.inputColors[1].toVec(),
4981                 Vec4(+1.0f, -1.0f, 0.0f, 1.0f), instance.inputColors[1].toVec(),
4982                 Vec4(+1.0f, -0.5f, 0.0f, 1.0f), instance.inputColors[1].toVec(),
4983
4984                 // Lower left corner:
4985                 Vec4(-1.0f, +0.5f, 0.0f, 1.0f), instance.inputColors[2].toVec(),
4986                 Vec4(-0.5f, +1.0f, 0.0f, 1.0f), instance.inputColors[2].toVec(),
4987                 Vec4(-1.0f, +1.0f, 0.0f, 1.0f), instance.inputColors[2].toVec(),
4988
4989                 // Lower right corner:
4990                 Vec4(+1.0f, +0.5f, 0.0f, 1.0f), instance.inputColors[3].toVec(),
4991                 Vec4(+1.0f, +1.0f, 0.0f, 1.0f), instance.inputColors[3].toVec(),
4992                 Vec4(+0.5f, +1.0f, 0.0f, 1.0f), instance.inputColors[3].toVec()
4993         };
4994         const size_t                                                    singleVertexDataSize    = 2 * sizeof(Vec4);
4995         const size_t                                                    vertexCount                             = sizeof(vertexData) / singleVertexDataSize;
4996
4997         const VkBufferCreateInfo                                vertexBufferParams              =
4998         {
4999                 VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,   //      VkStructureType         sType;
5000                 DE_NULL,                                                                //      const void*                     pNext;
5001                 0u,                                                                             //      VkBufferCreateFlags     flags;
5002                 (VkDeviceSize)sizeof(vertexData),               //      VkDeviceSize            size;
5003                 VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,              //      VkBufferUsageFlags      usage;
5004                 VK_SHARING_MODE_EXCLUSIVE,                              //      VkSharingMode           sharingMode;
5005                 1u,                                                                             //      deUint32                        queueFamilyCount;
5006                 &queueFamilyIndex,                                              //      const deUint32*         pQueueFamilyIndices;
5007         };
5008         const Unique<VkBuffer>                                  vertexBuffer                    (createBuffer(vk, vkDevice, &vertexBufferParams));
5009         const UniquePtr<Allocation>                             vertexBufferMemory              (context.getDefaultAllocator().allocate(getBufferMemoryRequirements(vk, vkDevice, *vertexBuffer), MemoryRequirement::HostVisible));
5010
5011         VK_CHECK(vk.bindBufferMemory(vkDevice, *vertexBuffer, vertexBufferMemory->getMemory(), vertexBufferMemory->getOffset()));
5012
5013         const VkDeviceSize                                              imageSizeBytes                  = (VkDeviceSize)(sizeof(deUint32)*renderSize.x()*renderSize.y());
5014         const VkBufferCreateInfo                                readImageBufferParams   =
5015         {
5016                 VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,           //      VkStructureType         sType;
5017                 DE_NULL,                                                                        //      const void*                     pNext;
5018                 0u,                                                                                     //      VkBufferCreateFlags     flags;
5019                 imageSizeBytes,                                                         //      VkDeviceSize            size;
5020                 VK_BUFFER_USAGE_TRANSFER_DST_BIT,                       //      VkBufferUsageFlags      usage;
5021                 VK_SHARING_MODE_EXCLUSIVE,                                      //      VkSharingMode           sharingMode;
5022                 1u,                                                                                     //      deUint32                        queueFamilyCount;
5023                 &queueFamilyIndex,                                                      //      const deUint32*         pQueueFamilyIndices;
5024         };
5025         const Unique<VkBuffer>                                  readImageBuffer                 (createBuffer(vk, vkDevice, &readImageBufferParams));
5026         const UniquePtr<Allocation>                             readImageBufferMemory   (context.getDefaultAllocator().allocate(getBufferMemoryRequirements(vk, vkDevice, *readImageBuffer), MemoryRequirement::HostVisible));
5027
5028         VK_CHECK(vk.bindBufferMemory(vkDevice, *readImageBuffer, readImageBufferMemory->getMemory(), readImageBufferMemory->getOffset()));
5029
5030         const VkImageCreateInfo                                 imageParams                             =
5031         {
5032                 VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,                                                                    //      VkStructureType         sType;
5033                 DE_NULL,                                                                                                                                //      const void*                     pNext;
5034                 0u,                                                                                                                                             //      VkImageCreateFlags      flags;
5035                 VK_IMAGE_TYPE_2D,                                                                                                               //      VkImageType                     imageType;
5036                 VK_FORMAT_R8G8B8A8_UNORM,                                                                                               //      VkFormat                        format;
5037                 { renderSize.x(), renderSize.y(), 1 },                                                                  //      VkExtent3D                      extent;
5038                 1u,                                                                                                                                             //      deUint32                        mipLevels;
5039                 1u,                                                                                                                                             //      deUint32                        arraySize;
5040                 VK_SAMPLE_COUNT_1_BIT,                                                                                                  //      deUint32                        samples;
5041                 VK_IMAGE_TILING_OPTIMAL,                                                                                                //      VkImageTiling           tiling;
5042                 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT|VK_IMAGE_USAGE_TRANSFER_SRC_BIT,    //      VkImageUsageFlags       usage;
5043                 VK_SHARING_MODE_EXCLUSIVE,                                                                                              //      VkSharingMode           sharingMode;
5044                 1u,                                                                                                                                             //      deUint32                        queueFamilyCount;
5045                 &queueFamilyIndex,                                                                                                              //      const deUint32*         pQueueFamilyIndices;
5046                 VK_IMAGE_LAYOUT_UNDEFINED,                                                                                              //      VkImageLayout           initialLayout;
5047         };
5048
5049         const Unique<VkImage>                                   image                                   (createImage(vk, vkDevice, &imageParams));
5050         const UniquePtr<Allocation>                             imageMemory                             (context.getDefaultAllocator().allocate(getImageMemoryRequirements(vk, vkDevice, *image), MemoryRequirement::Any));
5051
5052         VK_CHECK(vk.bindImageMemory(vkDevice, *image, imageMemory->getMemory(), imageMemory->getOffset()));
5053
5054         const VkAttachmentDescription                   colorAttDesc                    =
5055         {
5056                 0u,                                                                                             //      VkAttachmentDescriptionFlags    flags;
5057                 VK_FORMAT_R8G8B8A8_UNORM,                                               //      VkFormat                                                format;
5058                 VK_SAMPLE_COUNT_1_BIT,                                                  //      deUint32                                                samples;
5059                 VK_ATTACHMENT_LOAD_OP_CLEAR,                                    //      VkAttachmentLoadOp                              loadOp;
5060                 VK_ATTACHMENT_STORE_OP_STORE,                                   //      VkAttachmentStoreOp                             storeOp;
5061                 VK_ATTACHMENT_LOAD_OP_DONT_CARE,                                //      VkAttachmentLoadOp                              stencilLoadOp;
5062                 VK_ATTACHMENT_STORE_OP_DONT_CARE,                               //      VkAttachmentStoreOp                             stencilStoreOp;
5063                 VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,               //      VkImageLayout                                   initialLayout;
5064                 VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,               //      VkImageLayout                                   finalLayout;
5065         };
5066         const VkAttachmentReference                             colorAttRef                             =
5067         {
5068                 0u,                                                                                             //      deUint32                attachment;
5069                 VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,               //      VkImageLayout   layout;
5070         };
5071         const VkSubpassDescription                              subpassDesc                             =
5072         {
5073                 0u,                                                                                             //      VkSubpassDescriptionFlags               flags;
5074                 VK_PIPELINE_BIND_POINT_GRAPHICS,                                //      VkPipelineBindPoint                             pipelineBindPoint;
5075                 0u,                                                                                             //      deUint32                                                inputCount;
5076                 DE_NULL,                                                                                //      const VkAttachmentReference*    pInputAttachments;
5077                 1u,                                                                                             //      deUint32                                                colorCount;
5078                 &colorAttRef,                                                                   //      const VkAttachmentReference*    pColorAttachments;
5079                 DE_NULL,                                                                                //      const VkAttachmentReference*    pResolveAttachments;
5080                 DE_NULL,                                                                                //      const VkAttachmentReference*    pDepthStencilAttachment;
5081                 0u,                                                                                             //      deUint32                                                preserveCount;
5082                 DE_NULL,                                                                                //      const VkAttachmentReference*    pPreserveAttachments;
5083
5084         };
5085         const VkRenderPassCreateInfo                    renderPassParams                =
5086         {
5087                 VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,              //      VkStructureType                                 sType;
5088                 DE_NULL,                                                                                //      const void*                                             pNext;
5089                 (VkRenderPassCreateFlags)0,
5090                 1u,                                                                                             //      deUint32                                                attachmentCount;
5091                 &colorAttDesc,                                                                  //      const VkAttachmentDescription*  pAttachments;
5092                 1u,                                                                                             //      deUint32                                                subpassCount;
5093                 &subpassDesc,                                                                   //      const VkSubpassDescription*             pSubpasses;
5094                 0u,                                                                                             //      deUint32                                                dependencyCount;
5095                 DE_NULL,                                                                                //      const VkSubpassDependency*              pDependencies;
5096         };
5097         const Unique<VkRenderPass>                              renderPass                              (createRenderPass(vk, vkDevice, &renderPassParams));
5098
5099         const VkImageViewCreateInfo                             colorAttViewParams              =
5100         {
5101                 VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,               //      VkStructureType                         sType;
5102                 DE_NULL,                                                                                //      const void*                                     pNext;
5103                 0u,                                                                                             //      VkImageViewCreateFlags          flags;
5104                 *image,                                                                                 //      VkImage                                         image;
5105                 VK_IMAGE_VIEW_TYPE_2D,                                                  //      VkImageViewType                         viewType;
5106                 VK_FORMAT_R8G8B8A8_UNORM,                                               //      VkFormat                                        format;
5107                 {
5108                         VK_COMPONENT_SWIZZLE_R,
5109                         VK_COMPONENT_SWIZZLE_G,
5110                         VK_COMPONENT_SWIZZLE_B,
5111                         VK_COMPONENT_SWIZZLE_A
5112                 },                                                                                              //      VkChannelMapping                        channels;
5113                 {
5114                         VK_IMAGE_ASPECT_COLOR_BIT,                                              //      VkImageAspectFlags      aspectMask;
5115                         0u,                                                                                             //      deUint32                        baseMipLevel;
5116                         1u,                                                                                             //      deUint32                        mipLevels;
5117                         0u,                                                                                             //      deUint32                        baseArrayLayer;
5118                         1u,                                                                                             //      deUint32                        arraySize;
5119                 },                                                                                              //      VkImageSubresourceRange         subresourceRange;
5120         };
5121         const Unique<VkImageView>                               colorAttView                    (createImageView(vk, vkDevice, &colorAttViewParams));
5122
5123
5124         // Pipeline layout
5125         const VkPipelineLayoutCreateInfo                pipelineLayoutParams    =
5126         {
5127                 VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,                  //      VkStructureType                                 sType;
5128                 DE_NULL,                                                                                                //      const void*                                             pNext;
5129                 (VkPipelineLayoutCreateFlags)0,
5130                 0u,                                                                                                             //      deUint32                                                descriptorSetCount;
5131                 DE_NULL,                                                                                                //      const VkDescriptorSetLayout*    pSetLayouts;
5132                 0u,                                                                                                             //      deUint32                                                pushConstantRangeCount;
5133                 DE_NULL,                                                                                                //      const VkPushConstantRange*              pPushConstantRanges;
5134         };
5135         const Unique<VkPipelineLayout>                  pipelineLayout                  (createPipelineLayout(vk, vkDevice, &pipelineLayoutParams));
5136
5137         // Pipeline
5138         vector<VkPipelineShaderStageCreateInfo>         shaderStageParams;
5139         // We need these vectors to make sure that information about specialization constants for each stage can outlive createGraphicsPipeline().
5140         vector<vector<VkSpecializationMapEntry> >       specConstantEntries;
5141         vector<VkSpecializationInfo>                            specializationInfos;
5142         createPipelineShaderStages(vk, vkDevice, instance, context, modules, shaderStageParams);
5143
5144         // And we don't want the reallocation of these vectors to invalidate pointers pointing to their contents.
5145         specConstantEntries.reserve(shaderStageParams.size());
5146         specializationInfos.reserve(shaderStageParams.size());
5147
5148         // Patch the specialization info field in PipelineShaderStageCreateInfos.
5149         for (vector<VkPipelineShaderStageCreateInfo>::iterator stageInfo = shaderStageParams.begin(); stageInfo != shaderStageParams.end(); ++stageInfo)
5150         {
5151                 const StageToSpecConstantMap::const_iterator stageIt = instance.specConstants.find(stageInfo->stage);
5152
5153                 if (stageIt != instance.specConstants.end())
5154                 {
5155                         const size_t                                            numSpecConstants        = stageIt->second.size();
5156                         vector<VkSpecializationMapEntry>        entries;
5157                         VkSpecializationInfo                            specInfo;
5158
5159                         entries.resize(numSpecConstants);
5160
5161                         // Only support 32-bit integers as spec constants now. And their constant IDs are numbered sequentially starting from 0.
5162                         for (size_t ndx = 0; ndx < numSpecConstants; ++ndx)
5163                         {
5164                                 entries[ndx].constantID = (deUint32)ndx;
5165                                 entries[ndx].offset             = deUint32(ndx * sizeof(deInt32));
5166                                 entries[ndx].size               = sizeof(deInt32);
5167                         }
5168
5169                         specConstantEntries.push_back(entries);
5170
5171                         specInfo.mapEntryCount  = (deUint32)numSpecConstants;
5172                         specInfo.pMapEntries    = specConstantEntries.back().data();
5173                         specInfo.dataSize               = numSpecConstants * sizeof(deInt32);
5174                         specInfo.pData                  = stageIt->second.data();
5175                         specializationInfos.push_back(specInfo);
5176
5177                         stageInfo->pSpecializationInfo = &specializationInfos.back();
5178                 }
5179         }
5180         const VkPipelineDepthStencilStateCreateInfo     depthStencilParams              =
5181         {
5182                 VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,     //      VkStructureType         sType;
5183                 DE_NULL,                                                                                                        //      const void*                     pNext;
5184                 (VkPipelineDepthStencilStateCreateFlags)0,
5185                 DE_FALSE,                                                                                                       //      deUint32                        depthTestEnable;
5186                 DE_FALSE,                                                                                                       //      deUint32                        depthWriteEnable;
5187                 VK_COMPARE_OP_ALWAYS,                                                                           //      VkCompareOp                     depthCompareOp;
5188                 DE_FALSE,                                                                                                       //      deUint32                        depthBoundsTestEnable;
5189                 DE_FALSE,                                                                                                       //      deUint32                        stencilTestEnable;
5190                 {
5191                         VK_STENCIL_OP_KEEP,                                                                                     //      VkStencilOp     stencilFailOp;
5192                         VK_STENCIL_OP_KEEP,                                                                                     //      VkStencilOp     stencilPassOp;
5193                         VK_STENCIL_OP_KEEP,                                                                                     //      VkStencilOp     stencilDepthFailOp;
5194                         VK_COMPARE_OP_ALWAYS,                                                                           //      VkCompareOp     stencilCompareOp;
5195                         0u,                                                                                                                     //      deUint32        stencilCompareMask;
5196                         0u,                                                                                                                     //      deUint32        stencilWriteMask;
5197                         0u,                                                                                                                     //      deUint32        stencilReference;
5198                 },                                                                                                                      //      VkStencilOpState        front;
5199                 {
5200                         VK_STENCIL_OP_KEEP,                                                                                     //      VkStencilOp     stencilFailOp;
5201                         VK_STENCIL_OP_KEEP,                                                                                     //      VkStencilOp     stencilPassOp;
5202                         VK_STENCIL_OP_KEEP,                                                                                     //      VkStencilOp     stencilDepthFailOp;
5203                         VK_COMPARE_OP_ALWAYS,                                                                           //      VkCompareOp     stencilCompareOp;
5204                         0u,                                                                                                                     //      deUint32        stencilCompareMask;
5205                         0u,                                                                                                                     //      deUint32        stencilWriteMask;
5206                         0u,                                                                                                                     //      deUint32        stencilReference;
5207                 },                                                                                                                      //      VkStencilOpState        back;
5208                 -1.0f,                                                                                                          //      float                           minDepthBounds;
5209                 +1.0f,                                                                                                          //      float                           maxDepthBounds;
5210         };
5211         const VkViewport                                                viewport0                               =
5212         {
5213                 0.0f,                                                                                                           //      float   originX;
5214                 0.0f,                                                                                                           //      float   originY;
5215                 (float)renderSize.x(),                                                                          //      float   width;
5216                 (float)renderSize.y(),                                                                          //      float   height;
5217                 0.0f,                                                                                                           //      float   minDepth;
5218                 1.0f,                                                                                                           //      float   maxDepth;
5219         };
5220         const VkRect2D                                                  scissor0                                =
5221         {
5222                 {
5223                         0u,                                                                                                                     //      deInt32 x;
5224                         0u,                                                                                                                     //      deInt32 y;
5225                 },                                                                                                                      //      VkOffset2D      offset;
5226                 {
5227                         renderSize.x(),                                                                                         //      deInt32 width;
5228                         renderSize.y(),                                                                                         //      deInt32 height;
5229                 },                                                                                                                      //      VkExtent2D      extent;
5230         };
5231         const VkPipelineViewportStateCreateInfo         viewportParams                  =
5232         {
5233                 VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,          //      VkStructureType         sType;
5234                 DE_NULL,                                                                                                        //      const void*                     pNext;
5235                 (VkPipelineViewportStateCreateFlags)0,
5236                 1u,                                                                                                                     //      deUint32                        viewportCount;
5237                 &viewport0,
5238                 1u,
5239                 &scissor0
5240         };
5241         const VkSampleMask                                                      sampleMask                              = ~0u;
5242         const VkPipelineMultisampleStateCreateInfo      multisampleParams               =
5243         {
5244                 VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,       //      VkStructureType                 sType;
5245                 DE_NULL,                                                                                                        //      const void*                             pNext;
5246                 (VkPipelineMultisampleStateCreateFlags)0,
5247                 VK_SAMPLE_COUNT_1_BIT,                                                                          //      VkSampleCountFlagBits   rasterSamples;
5248                 DE_FALSE,                                                                                                       //      deUint32                                sampleShadingEnable;
5249                 0.0f,                                                                                                           //      float                                   minSampleShading;
5250                 &sampleMask,                                                                                            //      const VkSampleMask*             pSampleMask;
5251                 DE_FALSE,                                                                                                       //      VkBool32                                alphaToCoverageEnable;
5252                 DE_FALSE,                                                                                                       //      VkBool32                                alphaToOneEnable;
5253         };
5254         const VkPipelineRasterizationStateCreateInfo    rasterParams            =
5255         {
5256                 VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,     //      VkStructureType sType;
5257                 DE_NULL,                                                                                                        //      const void*             pNext;
5258                 (VkPipelineRasterizationStateCreateFlags)0,
5259                 DE_TRUE,                                                                                                        //      deUint32                depthClipEnable;
5260                 DE_FALSE,                                                                                                       //      deUint32                rasterizerDiscardEnable;
5261                 VK_POLYGON_MODE_FILL,                                                                           //      VkFillMode              fillMode;
5262                 VK_CULL_MODE_NONE,                                                                                      //      VkCullMode              cullMode;
5263                 VK_FRONT_FACE_COUNTER_CLOCKWISE,                                                        //      VkFrontFace             frontFace;
5264                 VK_FALSE,                                                                                                       //      VkBool32                depthBiasEnable;
5265                 0.0f,                                                                                                           //      float                   depthBias;
5266                 0.0f,                                                                                                           //      float                   depthBiasClamp;
5267                 0.0f,                                                                                                           //      float                   slopeScaledDepthBias;
5268                 1.0f,                                                                                                           //      float                   lineWidth;
5269         };
5270         const VkPrimitiveTopology topology = hasTessellation? VK_PRIMITIVE_TOPOLOGY_PATCH_LIST: VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
5271         const VkPipelineInputAssemblyStateCreateInfo    inputAssemblyParams     =
5272         {
5273                 VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,    //      VkStructureType         sType;
5274                 DE_NULL,                                                                                                                //      const void*                     pNext;
5275                 (VkPipelineInputAssemblyStateCreateFlags)0,
5276                 topology,                                                                                                               //      VkPrimitiveTopology     topology;
5277                 DE_FALSE,                                                                                                               //      deUint32                        primitiveRestartEnable;
5278         };
5279         const VkVertexInputBindingDescription           vertexBinding0 =
5280         {
5281                 0u,                                                                     // deUint32                                     binding;
5282                 deUint32(singleVertexDataSize),         // deUint32                                     strideInBytes;
5283                 VK_VERTEX_INPUT_RATE_VERTEX                     // VkVertexInputStepRate        stepRate;
5284         };
5285         const VkVertexInputAttributeDescription         vertexAttrib0[2] =
5286         {
5287                 {
5288                         0u,                                                                     // deUint32     location;
5289                         0u,                                                                     // deUint32     binding;
5290                         VK_FORMAT_R32G32B32A32_SFLOAT,          // VkFormat     format;
5291                         0u                                                                      // deUint32     offsetInBytes;
5292                 },
5293                 {
5294                         1u,                                                                     // deUint32     location;
5295                         0u,                                                                     // deUint32     binding;
5296                         VK_FORMAT_R32G32B32A32_SFLOAT,          // VkFormat     format;
5297                         sizeof(Vec4),                                           // deUint32     offsetInBytes;
5298                 }
5299         };
5300
5301         const VkPipelineVertexInputStateCreateInfo      vertexInputStateParams  =
5302         {
5303                 VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,      //      VkStructureType                                                         sType;
5304                 DE_NULL,                                                                                                        //      const void*                                                                     pNext;
5305                 (VkPipelineVertexInputStateCreateFlags)0,
5306                 1u,                                                                                                                     //      deUint32                                                                        bindingCount;
5307                 &vertexBinding0,                                                                                        //      const VkVertexInputBindingDescription*          pVertexBindingDescriptions;
5308                 2u,                                                                                                                     //      deUint32                                                                        attributeCount;
5309                 vertexAttrib0,                                                                                          //      const VkVertexInputAttributeDescription*        pVertexAttributeDescriptions;
5310         };
5311         const VkPipelineColorBlendAttachmentState       attBlendParams                  =
5312         {
5313                 DE_FALSE,                                                                                                       //      deUint32                blendEnable;
5314                 VK_BLEND_FACTOR_ONE,                                                                            //      VkBlend                 srcBlendColor;
5315                 VK_BLEND_FACTOR_ZERO,                                                                           //      VkBlend                 destBlendColor;
5316                 VK_BLEND_OP_ADD,                                                                                        //      VkBlendOp               blendOpColor;
5317                 VK_BLEND_FACTOR_ONE,                                                                            //      VkBlend                 srcBlendAlpha;
5318                 VK_BLEND_FACTOR_ZERO,                                                                           //      VkBlend                 destBlendAlpha;
5319                 VK_BLEND_OP_ADD,                                                                                        //      VkBlendOp               blendOpAlpha;
5320                 (VK_COLOR_COMPONENT_R_BIT|
5321                  VK_COLOR_COMPONENT_G_BIT|
5322                  VK_COLOR_COMPONENT_B_BIT|
5323                  VK_COLOR_COMPONENT_A_BIT),                                                                     //      VkChannelFlags  channelWriteMask;
5324         };
5325         const VkPipelineColorBlendStateCreateInfo       blendParams                             =
5326         {
5327                 VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,       //      VkStructureType                                                         sType;
5328                 DE_NULL,                                                                                                        //      const void*                                                                     pNext;
5329                 (VkPipelineColorBlendStateCreateFlags)0,
5330                 DE_FALSE,                                                                                                       //      VkBool32                                                                        logicOpEnable;
5331                 VK_LOGIC_OP_COPY,                                                                                       //      VkLogicOp                                                                       logicOp;
5332                 1u,                                                                                                                     //      deUint32                                                                        attachmentCount;
5333                 &attBlendParams,                                                                                        //      const VkPipelineColorBlendAttachmentState*      pAttachments;
5334                 { 0.0f, 0.0f, 0.0f, 0.0f },                                                                     //      float                                                                           blendConst[4];
5335         };
5336         const VkPipelineTessellationStateCreateInfo     tessellationState       =
5337         {
5338                 VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO,
5339                 DE_NULL,
5340                 (VkPipelineTessellationStateCreateFlags)0,
5341                 3u
5342         };
5343
5344         const VkPipelineTessellationStateCreateInfo* tessellationInfo   =       hasTessellation ? &tessellationState: DE_NULL;
5345         const VkGraphicsPipelineCreateInfo              pipelineParams                  =
5346         {
5347                 VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,                //      VkStructureType                                                                 sType;
5348                 DE_NULL,                                                                                                //      const void*                                                                             pNext;
5349                 0u,                                                                                                             //      VkPipelineCreateFlags                                                   flags;
5350                 (deUint32)shaderStageParams.size(),                                             //      deUint32                                                                                stageCount;
5351                 &shaderStageParams[0],                                                                  //      const VkPipelineShaderStageCreateInfo*                  pStages;
5352                 &vertexInputStateParams,                                                                //      const VkPipelineVertexInputStateCreateInfo*             pVertexInputState;
5353                 &inputAssemblyParams,                                                                   //      const VkPipelineInputAssemblyStateCreateInfo*   pInputAssemblyState;
5354                 tessellationInfo,                                                                               //      const VkPipelineTessellationStateCreateInfo*    pTessellationState;
5355                 &viewportParams,                                                                                //      const VkPipelineViewportStateCreateInfo*                pViewportState;
5356                 &rasterParams,                                                                                  //      const VkPipelineRasterStateCreateInfo*                  pRasterState;
5357                 &multisampleParams,                                                                             //      const VkPipelineMultisampleStateCreateInfo*             pMultisampleState;
5358                 &depthStencilParams,                                                                    //      const VkPipelineDepthStencilStateCreateInfo*    pDepthStencilState;
5359                 &blendParams,                                                                                   //      const VkPipelineColorBlendStateCreateInfo*              pColorBlendState;
5360                 (const VkPipelineDynamicStateCreateInfo*)DE_NULL,               //      const VkPipelineDynamicStateCreateInfo*                 pDynamicState;
5361                 *pipelineLayout,                                                                                //      VkPipelineLayout                                                                layout;
5362                 *renderPass,                                                                                    //      VkRenderPass                                                                    renderPass;
5363                 0u,                                                                                                             //      deUint32                                                                                subpass;
5364                 DE_NULL,                                                                                                //      VkPipeline                                                                              basePipelineHandle;
5365                 0u,                                                                                                             //      deInt32                                                                                 basePipelineIndex;
5366         };
5367
5368         const Unique<VkPipeline>                                pipeline                                (createGraphicsPipeline(vk, vkDevice, DE_NULL, &pipelineParams));
5369
5370         // Framebuffer
5371         const VkFramebufferCreateInfo                   framebufferParams               =
5372         {
5373                 VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,                              //      VkStructureType         sType;
5374                 DE_NULL,                                                                                                //      const void*                     pNext;
5375                 (VkFramebufferCreateFlags)0,
5376                 *renderPass,                                                                                    //      VkRenderPass            renderPass;
5377                 1u,                                                                                                             //      deUint32                        attachmentCount;
5378                 &*colorAttView,                                                                                 //      const VkImageView*      pAttachments;
5379                 (deUint32)renderSize.x(),                                                               //      deUint32                        width;
5380                 (deUint32)renderSize.y(),                                                               //      deUint32                        height;
5381                 1u,                                                                                                             //      deUint32                        layers;
5382         };
5383         const Unique<VkFramebuffer>                             framebuffer                             (createFramebuffer(vk, vkDevice, &framebufferParams));
5384
5385         const VkCommandPoolCreateInfo                   cmdPoolParams                   =
5386         {
5387                 VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,                                     //      VkStructureType                 sType;
5388                 DE_NULL,                                                                                                        //      const void*                             pNext;
5389                 VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,                                //      VkCmdPoolCreateFlags    flags;
5390                 queueFamilyIndex,                                                                                       //      deUint32                                queueFamilyIndex;
5391         };
5392         const Unique<VkCommandPool>                             cmdPool                                 (createCommandPool(vk, vkDevice, &cmdPoolParams));
5393
5394         // Command buffer
5395         const VkCommandBufferAllocateInfo               cmdBufParams                    =
5396         {
5397                 VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,                 //      VkStructureType                 sType;
5398                 DE_NULL,                                                                                                //      const void*                             pNext;
5399                 *cmdPool,                                                                                               //      VkCmdPool                               pool;
5400                 VK_COMMAND_BUFFER_LEVEL_PRIMARY,                                                //      VkCmdBufferLevel                level;
5401                 1u,                                                                                                             //      deUint32                                count;
5402         };
5403         const Unique<VkCommandBuffer>                   cmdBuf                                  (allocateCommandBuffer(vk, vkDevice, &cmdBufParams));
5404
5405         const VkCommandBufferBeginInfo                  cmdBufBeginParams               =
5406         {
5407                 VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,                    //      VkStructureType                         sType;
5408                 DE_NULL,                                                                                                //      const void*                                     pNext;
5409                 (VkCommandBufferUsageFlags)0,
5410                 (const VkCommandBufferInheritanceInfo*)DE_NULL,
5411         };
5412
5413         // Record commands
5414         VK_CHECK(vk.beginCommandBuffer(*cmdBuf, &cmdBufBeginParams));
5415
5416         {
5417                 const VkMemoryBarrier           vertFlushBarrier        =
5418                 {
5419                         VK_STRUCTURE_TYPE_MEMORY_BARRIER,                       //      VkStructureType         sType;
5420                         DE_NULL,                                                                        //      const void*                     pNext;
5421                         VK_ACCESS_HOST_WRITE_BIT,                                       //      VkMemoryOutputFlags     outputMask;
5422                         VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT,            //      VkMemoryInputFlags      inputMask;
5423                 };
5424                 const VkImageMemoryBarrier      colorAttBarrier         =
5425                 {
5426                         VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,         //      VkStructureType                 sType;
5427                         DE_NULL,                                                                        //      const void*                             pNext;
5428                         0u,                                                                                     //      VkMemoryOutputFlags             outputMask;
5429                         VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,           //      VkMemoryInputFlags              inputMask;
5430                         VK_IMAGE_LAYOUT_UNDEFINED,                                      //      VkImageLayout                   oldLayout;
5431                         VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,       //      VkImageLayout                   newLayout;
5432                         queueFamilyIndex,                                                       //      deUint32                                srcQueueFamilyIndex;
5433                         queueFamilyIndex,                                                       //      deUint32                                destQueueFamilyIndex;
5434                         *image,                                                                         //      VkImage                                 image;
5435                         {
5436                                 VK_IMAGE_ASPECT_COLOR_BIT,                                      //      VkImageAspect   aspect;
5437                                 0u,                                                                                     //      deUint32                baseMipLevel;
5438                                 1u,                                                                                     //      deUint32                mipLevels;
5439                                 0u,                                                                                     //      deUint32                baseArraySlice;
5440                                 1u,                                                                                     //      deUint32                arraySize;
5441                         }                                                                                       //      VkImageSubresourceRange subresourceRange;
5442                 };
5443                 vk.cmdPipelineBarrier(*cmdBuf, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, (VkDependencyFlags)0, 1, &vertFlushBarrier, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &colorAttBarrier);
5444         }
5445
5446         {
5447                 const VkClearValue                      clearValue              = makeClearValueColorF32(0.125f, 0.25f, 0.75f, 1.0f);
5448                 const VkRenderPassBeginInfo     passBeginParams =
5449                 {
5450                         VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,                       //      VkStructureType         sType;
5451                         DE_NULL,                                                                                        //      const void*                     pNext;
5452                         *renderPass,                                                                            //      VkRenderPass            renderPass;
5453                         *framebuffer,                                                                           //      VkFramebuffer           framebuffer;
5454                         { { 0, 0 }, { renderSize.x(), renderSize.y() } },       //      VkRect2D                        renderArea;
5455                         1u,                                                                                                     //      deUint32                        clearValueCount;
5456                         &clearValue,                                                                            //      const VkClearValue*     pClearValues;
5457                 };
5458                 vk.cmdBeginRenderPass(*cmdBuf, &passBeginParams, VK_SUBPASS_CONTENTS_INLINE);
5459         }
5460
5461         vk.cmdBindPipeline(*cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, *pipeline);
5462         {
5463                 const VkDeviceSize bindingOffset = 0;
5464                 vk.cmdBindVertexBuffers(*cmdBuf, 0u, 1u, &vertexBuffer.get(), &bindingOffset);
5465         }
5466         vk.cmdDraw(*cmdBuf, deUint32(vertexCount), 1u /*run pipeline once*/, 0u /*first vertex*/, 0u /*first instanceIndex*/);
5467         vk.cmdEndRenderPass(*cmdBuf);
5468
5469         {
5470                 const VkImageMemoryBarrier      renderFinishBarrier     =
5471                 {
5472                         VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,         //      VkStructureType                 sType;
5473                         DE_NULL,                                                                        //      const void*                             pNext;
5474                         VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,           //      VkMemoryOutputFlags             outputMask;
5475                         VK_ACCESS_TRANSFER_READ_BIT,                            //      VkMemoryInputFlags              inputMask;
5476                         VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,       //      VkImageLayout                   oldLayout;
5477                         VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,           //      VkImageLayout                   newLayout;
5478                         queueFamilyIndex,                                                       //      deUint32                                srcQueueFamilyIndex;
5479                         queueFamilyIndex,                                                       //      deUint32                                destQueueFamilyIndex;
5480                         *image,                                                                         //      VkImage                                 image;
5481                         {
5482                                 VK_IMAGE_ASPECT_COLOR_BIT,                                      //      VkImageAspectFlags      aspectMask;
5483                                 0u,                                                                                     //      deUint32                        baseMipLevel;
5484                                 1u,                                                                                     //      deUint32                        mipLevels;
5485                                 0u,                                                                                     //      deUint32                        baseArraySlice;
5486                                 1u,                                                                                     //      deUint32                        arraySize;
5487                         }                                                                                       //      VkImageSubresourceRange subresourceRange;
5488                 };
5489                 vk.cmdPipelineBarrier(*cmdBuf, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 0, (const VkBufferMemoryBarrier*)DE_NULL, 1, &renderFinishBarrier);
5490         }
5491
5492         {
5493                 const VkBufferImageCopy copyParams      =
5494                 {
5495                         (VkDeviceSize)0u,                                               //      VkDeviceSize                    bufferOffset;
5496                         (deUint32)renderSize.x(),                               //      deUint32                                bufferRowLength;
5497                         (deUint32)renderSize.y(),                               //      deUint32                                bufferImageHeight;
5498                         {
5499                                 VK_IMAGE_ASPECT_COLOR_BIT,                              //      VkImageAspect           aspect;
5500                                 0u,                                                                             //      deUint32                        mipLevel;
5501                                 0u,                                                                             //      deUint32                        arrayLayer;
5502                                 1u,                                                                             //      deUint32                        arraySize;
5503                         },                                                                              //      VkImageSubresourceCopy  imageSubresource;
5504                         { 0u, 0u, 0u },                                                 //      VkOffset3D                              imageOffset;
5505                         { renderSize.x(), renderSize.y(), 1u }  //      VkExtent3D                              imageExtent;
5506                 };
5507                 vk.cmdCopyImageToBuffer(*cmdBuf, *image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, *readImageBuffer, 1u, &copyParams);
5508         }
5509
5510         {
5511                 const VkBufferMemoryBarrier     copyFinishBarrier       =
5512                 {
5513                         VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,        //      VkStructureType         sType;
5514                         DE_NULL,                                                                        //      const void*                     pNext;
5515                         VK_ACCESS_TRANSFER_WRITE_BIT,                           //      VkMemoryOutputFlags     outputMask;
5516                         VK_ACCESS_HOST_READ_BIT,                                        //      VkMemoryInputFlags      inputMask;
5517                         queueFamilyIndex,                                                       //      deUint32                        srcQueueFamilyIndex;
5518                         queueFamilyIndex,                                                       //      deUint32                        destQueueFamilyIndex;
5519                         *readImageBuffer,                                                       //      VkBuffer                        buffer;
5520                         0u,                                                                                     //      VkDeviceSize            offset;
5521                         imageSizeBytes                                                          //      VkDeviceSize            size;
5522                 };
5523                 vk.cmdPipelineBarrier(*cmdBuf, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, (VkDependencyFlags)0, 0, (const VkMemoryBarrier*)DE_NULL, 1, &copyFinishBarrier, 0, (const VkImageMemoryBarrier*)DE_NULL);
5524         }
5525
5526         VK_CHECK(vk.endCommandBuffer(*cmdBuf));
5527
5528         // Upload vertex data
5529         {
5530                 const VkMappedMemoryRange       range                   =
5531                 {
5532                         VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,  //      VkStructureType sType;
5533                         DE_NULL,                                                                //      const void*             pNext;
5534                         vertexBufferMemory->getMemory(),                //      VkDeviceMemory  mem;
5535                         0,                                                                              //      VkDeviceSize    offset;
5536                         (VkDeviceSize)sizeof(vertexData),               //      VkDeviceSize    size;
5537                 };
5538                 void*                                           vertexBufPtr    = vertexBufferMemory->getHostPtr();
5539
5540                 deMemcpy(vertexBufPtr, &vertexData[0], sizeof(vertexData));
5541                 VK_CHECK(vk.flushMappedMemoryRanges(vkDevice, 1u, &range));
5542         }
5543
5544         // Submit & wait for completion
5545         {
5546                 const VkFenceCreateInfo fenceParams     =
5547                 {
5548                         VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,    //      VkStructureType         sType;
5549                         DE_NULL,                                                                //      const void*                     pNext;
5550                         0u,                                                                             //      VkFenceCreateFlags      flags;
5551                 };
5552                 const Unique<VkFence>   fence           (createFence(vk, vkDevice, &fenceParams));
5553                 const VkSubmitInfo              submitInfo      =
5554                 {
5555                         VK_STRUCTURE_TYPE_SUBMIT_INFO,
5556                         DE_NULL,
5557                         0u,
5558                         (const VkSemaphore*)DE_NULL,
5559                         (const VkPipelineStageFlags*)DE_NULL,
5560                         1u,
5561                         &cmdBuf.get(),
5562                         0u,
5563                         (const VkSemaphore*)DE_NULL,
5564                 };
5565
5566                 VK_CHECK(vk.queueSubmit(queue, 1u, &submitInfo, *fence));
5567                 VK_CHECK(vk.waitForFences(vkDevice, 1u, &fence.get(), DE_TRUE, ~0ull));
5568         }
5569
5570         const void* imagePtr    = readImageBufferMemory->getHostPtr();
5571         const tcu::ConstPixelBufferAccess pixelBuffer(tcu::TextureFormat(tcu::TextureFormat::RGBA, tcu::TextureFormat::UNORM_INT8),
5572                                                                                                   renderSize.x(), renderSize.y(), 1, imagePtr);
5573         // Log image
5574         {
5575                 const VkMappedMemoryRange       range           =
5576                 {
5577                         VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE,  //      VkStructureType sType;
5578                         DE_NULL,                                                                //      const void*             pNext;
5579                         readImageBufferMemory->getMemory(),             //      VkDeviceMemory  mem;
5580                         0,                                                                              //      VkDeviceSize    offset;
5581                         imageSizeBytes,                                                 //      VkDeviceSize    size;
5582                 };
5583
5584                 VK_CHECK(vk.invalidateMappedMemoryRanges(vkDevice, 1u, &range));
5585                 context.getTestContext().getLog() << TestLog::Image("Result", "Result", pixelBuffer);
5586         }
5587
5588         const RGBA threshold(1, 1, 1, 1);
5589         const RGBA upperLeft(pixelBuffer.getPixel(1, 1));
5590         if (!tcu::compareThreshold(upperLeft, instance.outputColors[0], threshold))
5591                 return TestStatus::fail("Upper left corner mismatch");
5592
5593         const RGBA upperRight(pixelBuffer.getPixel(pixelBuffer.getWidth() - 1, 1));
5594         if (!tcu::compareThreshold(upperRight, instance.outputColors[1], threshold))
5595                 return TestStatus::fail("Upper right corner mismatch");
5596
5597         const RGBA lowerLeft(pixelBuffer.getPixel(1, pixelBuffer.getHeight() - 1));
5598         if (!tcu::compareThreshold(lowerLeft, instance.outputColors[2], threshold))
5599                 return TestStatus::fail("Lower left corner mismatch");
5600
5601         const RGBA lowerRight(pixelBuffer.getPixel(pixelBuffer.getWidth() - 1, pixelBuffer.getHeight() - 1));
5602         if (!tcu::compareThreshold(lowerRight, instance.outputColors[3], threshold))
5603                 return TestStatus::fail("Lower right corner mismatch");
5604
5605         return TestStatus::pass("Rendered output matches input");
5606 }
5607
5608 void createTestsForAllStages (const std::string& name, const RGBA (&inputColors)[4], const RGBA (&outputColors)[4], const map<string, string>& testCodeFragments, const vector<deInt32>& specConstants, tcu::TestCaseGroup* tests)
5609 {
5610         const ShaderElement             vertFragPipelineStages[]                =
5611         {
5612                 ShaderElement("vert", "main", VK_SHADER_STAGE_VERTEX_BIT),
5613                 ShaderElement("frag", "main", VK_SHADER_STAGE_FRAGMENT_BIT),
5614         };
5615
5616         const ShaderElement             tessPipelineStages[]                    =
5617         {
5618                 ShaderElement("vert", "main", VK_SHADER_STAGE_VERTEX_BIT),
5619                 ShaderElement("tessc", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
5620                 ShaderElement("tesse", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
5621                 ShaderElement("frag", "main", VK_SHADER_STAGE_FRAGMENT_BIT),
5622         };
5623
5624         const ShaderElement             geomPipelineStages[]                            =
5625         {
5626                 ShaderElement("vert", "main", VK_SHADER_STAGE_VERTEX_BIT),
5627                 ShaderElement("geom", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
5628                 ShaderElement("frag", "main", VK_SHADER_STAGE_FRAGMENT_BIT),
5629         };
5630
5631         StageToSpecConstantMap  specConstantMap;
5632
5633         specConstantMap[VK_SHADER_STAGE_VERTEX_BIT] = specConstants;
5634         addFunctionCaseWithPrograms<InstanceContext>(tests, name + "_vert", "", addShaderCodeCustomVertex, runAndVerifyDefaultPipeline,
5635                                                                                                  createInstanceContext(vertFragPipelineStages, inputColors, outputColors, testCodeFragments, specConstantMap));
5636
5637         specConstantMap.clear();
5638         specConstantMap[VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT] = specConstants;
5639         addFunctionCaseWithPrograms<InstanceContext>(tests, name + "_tessc", "", addShaderCodeCustomTessControl, runAndVerifyDefaultPipeline,
5640                                                                                                  createInstanceContext(tessPipelineStages, inputColors, outputColors, testCodeFragments, specConstantMap));
5641
5642         specConstantMap.clear();
5643         specConstantMap[VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT] = specConstants;
5644         addFunctionCaseWithPrograms<InstanceContext>(tests, name + "_tesse", "", addShaderCodeCustomTessEval, runAndVerifyDefaultPipeline,
5645                                                                                                  createInstanceContext(tessPipelineStages, inputColors, outputColors, testCodeFragments, specConstantMap));
5646
5647         specConstantMap.clear();
5648         specConstantMap[VK_SHADER_STAGE_GEOMETRY_BIT] = specConstants;
5649         addFunctionCaseWithPrograms<InstanceContext>(tests, name + "_geom", "", addShaderCodeCustomGeometry, runAndVerifyDefaultPipeline,
5650                                                                                                  createInstanceContext(geomPipelineStages, inputColors, outputColors, testCodeFragments, specConstantMap));
5651
5652         specConstantMap.clear();
5653         specConstantMap[VK_SHADER_STAGE_FRAGMENT_BIT] = specConstants;
5654         addFunctionCaseWithPrograms<InstanceContext>(tests, name + "_frag", "", addShaderCodeCustomFragment, runAndVerifyDefaultPipeline,
5655                                                                                                  createInstanceContext(vertFragPipelineStages, inputColors, outputColors, testCodeFragments, specConstantMap));
5656 }
5657
5658 inline void createTestsForAllStages (const std::string& name, const RGBA (&inputColors)[4], const RGBA (&outputColors)[4], const map<string, string>& testCodeFragments, tcu::TestCaseGroup* tests)
5659 {
5660         vector<deInt32> noSpecConstants;
5661         createTestsForAllStages(name, inputColors, outputColors, testCodeFragments, noSpecConstants, tests);
5662 }
5663
5664 } // anonymous
5665
5666 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
5667 {
5668         struct NameCodePair { string name, code; };
5669         RGBA                                                    defaultColors[4];
5670         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
5671         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
5672         map<string, string>                             fragments                               = passthruFragments();
5673         const NameCodePair                              tests[]                                 =
5674         {
5675                 {"unknown", "OpSource Unknown 321"},
5676                 {"essl", "OpSource ESSL 310"},
5677                 {"glsl", "OpSource GLSL 450"},
5678                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
5679                 {"opencl_c", "OpSource OpenCL_C 120"},
5680                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
5681                 {"file", opsourceGLSLWithFile},
5682                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
5683                 // Longest possible source string: SPIR-V limits instructions to 65535
5684                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
5685                 // contain 65530 UTF8 characters (one word each) plus one last word
5686                 // containing 3 ASCII characters and \0.
5687                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
5688         };
5689
5690         getDefaultColors(defaultColors);
5691         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
5692         {
5693                 fragments["debug"] = tests[testNdx].code;
5694                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
5695         }
5696
5697         return opSourceTests.release();
5698 }
5699
5700 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
5701 {
5702         struct NameCodePair { string name, code; };
5703         RGBA                                                            defaultColors[4];
5704         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
5705         map<string, string>                                     fragments                       = passthruFragments();
5706         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
5707         const NameCodePair                                      tests[]                         =
5708         {
5709                 {"empty", opsource + "OpSourceContinued \"\""},
5710                 {"short", opsource + "OpSourceContinued \"abcde\""},
5711                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
5712                 // Longest possible source string: SPIR-V limits instructions to 65535
5713                 // words, of which the first one is OpSourceContinued/length; the rest
5714                 // will contain 65533 UTF8 characters (one word each) plus one last word
5715                 // containing 3 ASCII characters and \0.
5716                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
5717         };
5718
5719         getDefaultColors(defaultColors);
5720         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
5721         {
5722                 fragments["debug"] = tests[testNdx].code;
5723                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
5724         }
5725
5726         return opSourceTests.release();
5727 }
5728
5729 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
5730 {
5731         RGBA                                                             defaultColors[4];
5732         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
5733         map<string, string>                                      fragments;
5734         getDefaultColors(defaultColors);
5735         fragments["debug"]                      =
5736                 "%name = OpString \"name\"\n";
5737
5738         fragments["pre_main"]   =
5739                 "OpNoLine\n"
5740                 "OpNoLine\n"
5741                 "OpLine %name 1 1\n"
5742                 "OpNoLine\n"
5743                 "OpLine %name 1 1\n"
5744                 "OpLine %name 1 1\n"
5745                 "%second_function = OpFunction %v4f32 None %v4f32_function\n"
5746                 "OpNoLine\n"
5747                 "OpLine %name 1 1\n"
5748                 "OpNoLine\n"
5749                 "OpLine %name 1 1\n"
5750                 "OpLine %name 1 1\n"
5751                 "%second_param1 = OpFunctionParameter %v4f32\n"
5752                 "OpNoLine\n"
5753                 "OpNoLine\n"
5754                 "%label_secondfunction = OpLabel\n"
5755                 "OpNoLine\n"
5756                 "OpReturnValue %second_param1\n"
5757                 "OpFunctionEnd\n"
5758                 "OpNoLine\n"
5759                 "OpNoLine\n";
5760
5761         fragments["testfun"]            =
5762                 // A %test_code function that returns its argument unchanged.
5763                 "OpNoLine\n"
5764                 "OpNoLine\n"
5765                 "OpLine %name 1 1\n"
5766                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5767                 "OpNoLine\n"
5768                 "%param1 = OpFunctionParameter %v4f32\n"
5769                 "OpNoLine\n"
5770                 "OpNoLine\n"
5771                 "%label_testfun = OpLabel\n"
5772                 "OpNoLine\n"
5773                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
5774                 "OpReturnValue %val1\n"
5775                 "OpFunctionEnd\n"
5776                 "OpLine %name 1 1\n"
5777                 "OpNoLine\n";
5778
5779         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
5780
5781         return opLineTests.release();
5782 }
5783
5784
5785 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
5786 {
5787         RGBA                                                                                                    defaultColors[4];
5788         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
5789         map<string, string>                                                                             fragments;
5790         std::vector<std::pair<std::string, std::string> >               problemStrings;
5791
5792         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
5793         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
5794         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
5795         getDefaultColors(defaultColors);
5796
5797         fragments["debug"]                      =
5798                 "%other_name = OpString \"other_name\"\n";
5799
5800         fragments["pre_main"]   =
5801                 "OpLine %file_name 32 0\n"
5802                 "OpLine %file_name 32 32\n"
5803                 "OpLine %file_name 32 40\n"
5804                 "OpLine %other_name 32 40\n"
5805                 "OpLine %other_name 0 100\n"
5806                 "OpLine %other_name 0 4294967295\n"
5807                 "OpLine %other_name 4294967295 0\n"
5808                 "OpLine %other_name 32 40\n"
5809                 "OpLine %file_name 0 0\n"
5810                 "%second_function = OpFunction %v4f32 None %v4f32_function\n"
5811                 "OpLine %file_name 1 0\n"
5812                 "%second_param1 = OpFunctionParameter %v4f32\n"
5813                 "OpLine %file_name 1 3\n"
5814                 "OpLine %file_name 1 2\n"
5815                 "%label_secondfunction = OpLabel\n"
5816                 "OpLine %file_name 0 2\n"
5817                 "OpReturnValue %second_param1\n"
5818                 "OpFunctionEnd\n"
5819                 "OpLine %file_name 0 2\n"
5820                 "OpLine %file_name 0 2\n";
5821
5822         fragments["testfun"]            =
5823                 // A %test_code function that returns its argument unchanged.
5824                 "OpLine %file_name 1 0\n"
5825                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5826                 "OpLine %file_name 16 330\n"
5827                 "%param1 = OpFunctionParameter %v4f32\n"
5828                 "OpLine %file_name 14 442\n"
5829                 "%label_testfun = OpLabel\n"
5830                 "OpLine %file_name 11 1024\n"
5831                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
5832                 "OpLine %file_name 2 97\n"
5833                 "OpReturnValue %val1\n"
5834                 "OpFunctionEnd\n"
5835                 "OpLine %file_name 5 32\n";
5836
5837         for (size_t i = 0; i < problemStrings.size(); ++i)
5838         {
5839                 map<string, string> testFragments = fragments;
5840                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
5841                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
5842         }
5843
5844         return opLineTests.release();
5845 }
5846
5847 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
5848 {
5849         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
5850         RGBA                                                    colors[4];
5851
5852
5853         const char                                              functionStart[] =
5854                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5855                 "%param1 = OpFunctionParameter %v4f32\n"
5856                 "%lbl    = OpLabel\n";
5857
5858         const char                                              functionEnd[]   =
5859                 "OpReturnValue %transformed_param\n"
5860                 "OpFunctionEnd\n";
5861
5862         struct NameConstantsCode
5863         {
5864                 string name;
5865                 string constants;
5866                 string code;
5867         };
5868
5869         NameConstantsCode tests[] =
5870         {
5871                 {
5872                         "vec4",
5873                         "%cnull = OpConstantNull %v4f32\n",
5874                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
5875                 },
5876                 {
5877                         "float",
5878                         "%cnull = OpConstantNull %f32\n",
5879                         "%vp = OpVariable %fp_v4f32 Function\n"
5880                         "%v  = OpLoad %v4f32 %vp\n"
5881                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
5882                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
5883                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
5884                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
5885                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
5886                 },
5887                 {
5888                         "bool",
5889                         "%cnull             = OpConstantNull %bool\n",
5890                         "%v                 = OpVariable %fp_v4f32 Function\n"
5891                         "                     OpStore %v %param1\n"
5892                         "                     OpSelectionMerge %false_label None\n"
5893                         "                     OpBranchConditional %cnull %true_label %false_label\n"
5894                         "%true_label        = OpLabel\n"
5895                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
5896                         "                     OpBranch %false_label\n"
5897                         "%false_label       = OpLabel\n"
5898                         "%transformed_param = OpLoad %v4f32 %v\n"
5899                 },
5900                 {
5901                         "i32",
5902                         "%cnull             = OpConstantNull %i32\n",
5903                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
5904                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
5905                         "                     OpSelectionMerge %false_label None\n"
5906                         "                     OpBranchConditional %b %true_label %false_label\n"
5907                         "%true_label        = OpLabel\n"
5908                         "                     OpStore %v %param1\n"
5909                         "                     OpBranch %false_label\n"
5910                         "%false_label       = OpLabel\n"
5911                         "%transformed_param = OpLoad %v4f32 %v\n"
5912                 },
5913                 {
5914                         "struct",
5915                         "%stype             = OpTypeStruct %f32 %v4f32\n"
5916                         "%fp_stype          = OpTypePointer Function %stype\n"
5917                         "%cnull             = OpConstantNull %stype\n",
5918                         "%v                 = OpVariable %fp_stype Function %cnull\n"
5919                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
5920                         "%f_val             = OpLoad %v4f32 %f\n"
5921                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
5922                 },
5923                 {
5924                         "array",
5925                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
5926                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
5927                         "%cnull             = OpConstantNull %a4_v4f32\n",
5928                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
5929                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
5930                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
5931                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
5932                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
5933                         "%f_val             = OpLoad %v4f32 %f\n"
5934                         "%f1_val            = OpLoad %v4f32 %f1\n"
5935                         "%f2_val            = OpLoad %v4f32 %f2\n"
5936                         "%f3_val            = OpLoad %v4f32 %f3\n"
5937                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
5938                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
5939                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
5940                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
5941                 },
5942                 {
5943                         "matrix",
5944                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
5945                         "%cnull             = OpConstantNull %mat4x4_f32\n",
5946                         // Our null matrix * any vector should result in a zero vector.
5947                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
5948                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
5949                 }
5950         };
5951
5952         getHalfColorsFullAlpha(colors);
5953
5954         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
5955         {
5956                 map<string, string> fragments;
5957                 fragments["pre_main"] = tests[testNdx].constants;
5958                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
5959                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
5960         }
5961         return opConstantNullTests.release();
5962 }
5963 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
5964 {
5965         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
5966         RGBA                                                    inputColors[4];
5967         RGBA                                                    outputColors[4];
5968
5969
5970         const char                                              functionStart[]  =
5971                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
5972                 "%param1 = OpFunctionParameter %v4f32\n"
5973                 "%lbl    = OpLabel\n";
5974
5975         const char                                              functionEnd[]           =
5976                 "OpReturnValue %transformed_param\n"
5977                 "OpFunctionEnd\n";
5978
5979         struct NameConstantsCode
5980         {
5981                 string name;
5982                 string constants;
5983                 string code;
5984         };
5985
5986         NameConstantsCode tests[] =
5987         {
5988                 {
5989                         "vec4",
5990
5991                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
5992                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
5993                 },
5994                 {
5995                         "struct",
5996
5997                         "%stype             = OpTypeStruct %v4f32 %f32\n"
5998                         "%fp_stype          = OpTypePointer Function %stype\n"
5999                         "%f32_n_1           = OpConstant %f32 -1.0\n"
6000                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
6001                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
6002                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
6003
6004                         "%v                 = OpVariable %fp_stype Function %cval\n"
6005                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6006                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
6007                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
6008                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
6009                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
6010                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
6011                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
6012                 },
6013                 {
6014                         // [1|0|0|0.5] [x] = x + 0.5
6015                         // [0|1|0|0.5] [y] = y + 0.5
6016                         // [0|0|1|0.5] [z] = z + 0.5
6017                         // [0|0|0|1  ] [1] = 1
6018                         "matrix",
6019
6020                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
6021                     "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
6022                     "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
6023                     "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
6024                     "%v4f32_0_5_0_5_0_5_1 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_1\n"
6025                         "%cval                = OpConstantComposite %mat4x4_f32 %v4f32_1_0_0_0 %v4f32_0_1_0_0 %v4f32_0_0_1_0 %v4f32_0_5_0_5_0_5_1\n",
6026
6027                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
6028                 },
6029                 {
6030                         "array",
6031
6032                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6033                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6034                         "%f32_n_1             = OpConstant %f32 -1.0\n"
6035                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
6036                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
6037
6038                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
6039                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
6040                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
6041                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
6042                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
6043                         "%f_val               = OpLoad %f32 %f\n"
6044                         "%f1_val              = OpLoad %f32 %f1\n"
6045                         "%f2_val              = OpLoad %f32 %f2\n"
6046                         "%f3_val              = OpLoad %f32 %f3\n"
6047                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
6048                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
6049                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
6050                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
6051                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6052                 },
6053                 {
6054                         //
6055                         // [
6056                         //   {
6057                         //      0.0,
6058                         //      [ 1.0, 1.0, 1.0, 1.0]
6059                         //   },
6060                         //   {
6061                         //      1.0,
6062                         //      [ 0.0, 0.5, 0.0, 0.0]
6063                         //   }, //     ^^^
6064                         //   {
6065                         //      0.0,
6066                         //      [ 1.0, 1.0, 1.0, 1.0]
6067                         //   }
6068                         // ]
6069                         "array_of_struct_of_array",
6070
6071                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6072                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6073                         "%stype               = OpTypeStruct %f32 %a4f32\n"
6074                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
6075                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
6076                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
6077                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6078                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
6079                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
6080                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
6081
6082                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
6083                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
6084                         "%f_l                 = OpLoad %f32 %f\n"
6085                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
6086                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6087                 }
6088         };
6089
6090         getHalfColorsFullAlpha(inputColors);
6091         outputColors[0] = RGBA(255, 255, 255, 255);
6092         outputColors[1] = RGBA(255, 127, 127, 255);
6093         outputColors[2] = RGBA(127, 255, 127, 255);
6094         outputColors[3] = RGBA(127, 127, 255, 255);
6095
6096         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6097         {
6098                 map<string, string> fragments;
6099                 fragments["pre_main"] = tests[testNdx].constants;
6100                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6101                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
6102         }
6103         return opConstantCompositeTests.release();
6104 }
6105
6106 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
6107 {
6108         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
6109         RGBA                                                    inputColors[4];
6110         RGBA                                                    outputColors[4];
6111         map<string, string>                             fragments;
6112
6113         // vec4 test_code(vec4 param) {
6114         //   vec4 result = param;
6115         //   for (int i = 0; i < 4; ++i) {
6116         //     if (i == 0) result[i] = 0.;
6117         //     else        result[i] = 1. - result[i];
6118         //   }
6119         //   return result;
6120         // }
6121         const char                                              function[]                      =
6122                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6123                 "%param1    = OpFunctionParameter %v4f32\n"
6124                 "%lbl       = OpLabel\n"
6125                 "%iptr      = OpVariable %fp_i32 Function\n"
6126                 "%result    = OpVariable %fp_v4f32 Function\n"
6127                 "             OpStore %iptr %c_i32_0\n"
6128                 "             OpStore %result %param1\n"
6129                 "             OpBranch %loop\n"
6130
6131                 // Loop entry block.
6132                 "%loop      = OpLabel\n"
6133                 "%ival      = OpLoad %i32 %iptr\n"
6134                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6135                 "             OpLoopMerge %exit %if_entry None\n"
6136                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
6137
6138                 // Merge block for loop.
6139                 "%exit      = OpLabel\n"
6140                 "%ret       = OpLoad %v4f32 %result\n"
6141                 "             OpReturnValue %ret\n"
6142
6143                 // If-statement entry block.
6144                 "%if_entry  = OpLabel\n"
6145                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6146                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
6147                 "             OpSelectionMerge %if_exit None\n"
6148                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
6149
6150                 // False branch for if-statement.
6151                 "%if_false  = OpLabel\n"
6152                 "%val       = OpLoad %f32 %loc\n"
6153                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
6154                 "             OpStore %loc %sub\n"
6155                 "             OpBranch %if_exit\n"
6156
6157                 // Merge block for if-statement.
6158                 "%if_exit   = OpLabel\n"
6159                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6160                 "             OpStore %iptr %ival_next\n"
6161                 "             OpBranch %loop\n"
6162
6163                 // True branch for if-statement.
6164                 "%if_true   = OpLabel\n"
6165                 "             OpStore %loc %c_f32_0\n"
6166                 "             OpBranch %if_exit\n"
6167
6168                 "             OpFunctionEnd\n";
6169
6170         fragments["testfun"]    = function;
6171
6172         inputColors[0]                  = RGBA(127, 127, 127, 0);
6173         inputColors[1]                  = RGBA(127, 0,   0,   0);
6174         inputColors[2]                  = RGBA(0,   127, 0,   0);
6175         inputColors[3]                  = RGBA(0,   0,   127, 0);
6176
6177         outputColors[0]                 = RGBA(0, 128, 128, 255);
6178         outputColors[1]                 = RGBA(0, 255, 255, 255);
6179         outputColors[2]                 = RGBA(0, 128, 255, 255);
6180         outputColors[3]                 = RGBA(0, 255, 128, 255);
6181
6182         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6183
6184         return group.release();
6185 }
6186
6187 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
6188 {
6189         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
6190         RGBA                                                    inputColors[4];
6191         RGBA                                                    outputColors[4];
6192         map<string, string>                             fragments;
6193
6194         const char                                              typesAndConstants[]     =
6195                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6196                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6197                 "%c_f32_p6  = OpConstant %f32 0.6\n"
6198                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6199
6200         // vec4 test_code(vec4 param) {
6201         //   vec4 result = param;
6202         //   for (int i = 0; i < 4; ++i) {
6203         //     switch (i) {
6204         //       case 0: result[i] += .2; break;
6205         //       case 1: result[i] += .6; break;
6206         //       case 2: result[i] += .4; break;
6207         //       case 3: result[i] += .8; break;
6208         //       default: break; // unreachable
6209         //     }
6210         //   }
6211         //   return result;
6212         // }
6213         const char                                              function[]                      =
6214                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6215                 "%param1    = OpFunctionParameter %v4f32\n"
6216                 "%lbl       = OpLabel\n"
6217                 "%iptr      = OpVariable %fp_i32 Function\n"
6218                 "%result    = OpVariable %fp_v4f32 Function\n"
6219                 "             OpStore %iptr %c_i32_0\n"
6220                 "             OpStore %result %param1\n"
6221                 "             OpBranch %loop\n"
6222
6223                 // Loop entry block.
6224                 "%loop      = OpLabel\n"
6225                 "%ival      = OpLoad %i32 %iptr\n"
6226                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6227                 "             OpLoopMerge %exit %switch_exit None\n"
6228                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
6229
6230                 // Merge block for loop.
6231                 "%exit      = OpLabel\n"
6232                 "%ret       = OpLoad %v4f32 %result\n"
6233                 "             OpReturnValue %ret\n"
6234
6235                 // Switch-statement entry block.
6236                 "%switch_entry   = OpLabel\n"
6237                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
6238                 "%val            = OpLoad %f32 %loc\n"
6239                 "                  OpSelectionMerge %switch_exit None\n"
6240                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6241
6242                 "%case2          = OpLabel\n"
6243                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
6244                 "                  OpStore %loc %addp4\n"
6245                 "                  OpBranch %switch_exit\n"
6246
6247                 "%switch_default = OpLabel\n"
6248                 "                  OpUnreachable\n"
6249
6250                 "%case3          = OpLabel\n"
6251                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
6252                 "                  OpStore %loc %addp8\n"
6253                 "                  OpBranch %switch_exit\n"
6254
6255                 "%case0          = OpLabel\n"
6256                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
6257                 "                  OpStore %loc %addp2\n"
6258                 "                  OpBranch %switch_exit\n"
6259
6260                 // Merge block for switch-statement.
6261                 "%switch_exit    = OpLabel\n"
6262                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
6263                 "                  OpStore %iptr %ival_next\n"
6264                 "                  OpBranch %loop\n"
6265
6266                 "%case1          = OpLabel\n"
6267                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
6268                 "                  OpStore %loc %addp6\n"
6269                 "                  OpBranch %switch_exit\n"
6270
6271                 "                  OpFunctionEnd\n";
6272
6273         fragments["pre_main"]   = typesAndConstants;
6274         fragments["testfun"]    = function;
6275
6276         inputColors[0]                  = RGBA(127, 27,  127, 51);
6277         inputColors[1]                  = RGBA(127, 0,   0,   51);
6278         inputColors[2]                  = RGBA(0,   27,  0,   51);
6279         inputColors[3]                  = RGBA(0,   0,   127, 51);
6280
6281         outputColors[0]                 = RGBA(178, 180, 229, 255);
6282         outputColors[1]                 = RGBA(178, 153, 102, 255);
6283         outputColors[2]                 = RGBA(51,  180, 102, 255);
6284         outputColors[3]                 = RGBA(51,  153, 229, 255);
6285
6286         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6287
6288         return group.release();
6289 }
6290
6291 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
6292 {
6293         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
6294         RGBA                                                    inputColors[4];
6295         RGBA                                                    outputColors[4];
6296         map<string, string>                             fragments;
6297
6298         const char                                              decorations[]           =
6299                 "OpDecorate %array_group         ArrayStride 4\n"
6300                 "OpDecorate %struct_member_group Offset 0\n"
6301                 "%array_group         = OpDecorationGroup\n"
6302                 "%struct_member_group = OpDecorationGroup\n"
6303
6304                 "OpDecorate %group1 RelaxedPrecision\n"
6305                 "OpDecorate %group3 RelaxedPrecision\n"
6306                 "OpDecorate %group3 Invariant\n"
6307                 "OpDecorate %group3 Restrict\n"
6308                 "%group0 = OpDecorationGroup\n"
6309                 "%group1 = OpDecorationGroup\n"
6310                 "%group3 = OpDecorationGroup\n";
6311
6312         const char                                              typesAndConstants[]     =
6313                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
6314                 "%struct1   = OpTypeStruct %a3f32\n"
6315                 "%struct2   = OpTypeStruct %a3f32\n"
6316                 "%fp_struct1 = OpTypePointer Function %struct1\n"
6317                 "%fp_struct2 = OpTypePointer Function %struct2\n"
6318                 "%c_f32_2    = OpConstant %f32 2.\n"
6319                 "%c_f32_n2   = OpConstant %f32 -2.\n"
6320
6321                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
6322                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
6323                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
6324                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
6325
6326         const char                                              function[]                      =
6327                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6328                 "%param     = OpFunctionParameter %v4f32\n"
6329                 "%entry     = OpLabel\n"
6330                 "%result    = OpVariable %fp_v4f32 Function\n"
6331                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
6332                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
6333                 "             OpStore %result %param\n"
6334                 "             OpStore %v_struct1 %c_struct1\n"
6335                 "             OpStore %v_struct2 %c_struct2\n"
6336                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
6337                 "%val1      = OpLoad %f32 %ptr1\n"
6338                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
6339                 "%val2      = OpLoad %f32 %ptr2\n"
6340                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
6341                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6342                 "%val       = OpLoad %f32 %ptr\n"
6343                 "%addresult = OpFAdd %f32 %addvalues %val\n"
6344                 "             OpStore %ptr %addresult\n"
6345                 "%ret       = OpLoad %v4f32 %result\n"
6346                 "             OpReturnValue %ret\n"
6347                 "             OpFunctionEnd\n";
6348
6349         struct CaseNameDecoration
6350         {
6351                 string name;
6352                 string decoration;
6353         };
6354
6355         CaseNameDecoration tests[] =
6356         {
6357                 {
6358                         "same_decoration_group_on_multiple_types",
6359                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
6360                 },
6361                 {
6362                         "empty_decoration_group",
6363                         "OpGroupDecorate %group0      %a3f32\n"
6364                         "OpGroupDecorate %group0      %result\n"
6365                 },
6366                 {
6367                         "one_element_decoration_group",
6368                         "OpGroupDecorate %array_group %a3f32\n"
6369                 },
6370                 {
6371                         "multiple_elements_decoration_group",
6372                         "OpGroupDecorate %group3      %v_struct1\n"
6373                 },
6374                 {
6375                         "multiple_decoration_groups_on_same_variable",
6376                         "OpGroupDecorate %group0      %v_struct2\n"
6377                         "OpGroupDecorate %group1      %v_struct2\n"
6378                         "OpGroupDecorate %group3      %v_struct2\n"
6379                 },
6380                 {
6381                         "same_decoration_group_multiple_times",
6382                         "OpGroupDecorate %group1      %addvalues\n"
6383                         "OpGroupDecorate %group1      %addvalues\n"
6384                         "OpGroupDecorate %group1      %addvalues\n"
6385                 },
6386
6387         };
6388
6389         getHalfColorsFullAlpha(inputColors);
6390         getHalfColorsFullAlpha(outputColors);
6391
6392         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
6393         {
6394                 fragments["decoration"] = decorations + tests[idx].decoration;
6395                 fragments["pre_main"]   = typesAndConstants;
6396                 fragments["testfun"]    = function;
6397
6398                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
6399         }
6400
6401         return group.release();
6402 }
6403
6404 struct SpecConstantTwoIntGraphicsCase
6405 {
6406         const char*             caseName;
6407         const char*             scDefinition0;
6408         const char*             scDefinition1;
6409         const char*             scResultType;
6410         const char*             scOperation;
6411         deInt32                 scActualValue0;
6412         deInt32                 scActualValue1;
6413         const char*             resultOperation;
6414         RGBA                    expectedColors[4];
6415
6416                                         SpecConstantTwoIntGraphicsCase (const char* name,
6417                                                                                         const char* definition0,
6418                                                                                         const char* definition1,
6419                                                                                         const char* resultType,
6420                                                                                         const char* operation,
6421                                                                                         deInt32         value0,
6422                                                                                         deInt32         value1,
6423                                                                                         const char* resultOp,
6424                                                                                         const RGBA      (&output)[4])
6425                                                 : caseName                      (name)
6426                                                 , scDefinition0         (definition0)
6427                                                 , scDefinition1         (definition1)
6428                                                 , scResultType          (resultType)
6429                                                 , scOperation           (operation)
6430                                                 , scActualValue0        (value0)
6431                                                 , scActualValue1        (value1)
6432                                                 , resultOperation       (resultOp)
6433         {
6434                 expectedColors[0] = output[0];
6435                 expectedColors[1] = output[1];
6436                 expectedColors[2] = output[2];
6437                 expectedColors[3] = output[3];
6438         }
6439 };
6440
6441 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
6442 {
6443         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
6444         vector<SpecConstantTwoIntGraphicsCase>  cases;
6445         RGBA                                                    inputColors[4];
6446         RGBA                                                    outputColors0[4];
6447         RGBA                                                    outputColors1[4];
6448         RGBA                                                    outputColors2[4];
6449
6450         const char      decorations1[]                  =
6451                 "OpDecorate %sc_0  SpecId 0\n"
6452                 "OpDecorate %sc_1  SpecId 1\n";
6453
6454         const char      typesAndConstants1[]    =
6455                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
6456                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
6457                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
6458
6459         const char      function1[]                             =
6460                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6461                 "%param     = OpFunctionParameter %v4f32\n"
6462                 "%label     = OpLabel\n"
6463                 "%result    = OpVariable %fp_v4f32 Function\n"
6464                 "             OpStore %result %param\n"
6465                 "%gen       = ${GEN_RESULT}\n"
6466                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
6467                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
6468                 "%val       = OpLoad %f32 %loc\n"
6469                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
6470                 "             OpStore %loc %add\n"
6471                 "%ret       = OpLoad %v4f32 %result\n"
6472                 "             OpReturnValue %ret\n"
6473                 "             OpFunctionEnd\n";
6474
6475         inputColors[0] = RGBA(127, 127, 127, 255);
6476         inputColors[1] = RGBA(127, 0,   0,   255);
6477         inputColors[2] = RGBA(0,   127, 0,   255);
6478         inputColors[3] = RGBA(0,   0,   127, 255);
6479
6480         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
6481         outputColors0[0] = RGBA(255, 127, 127, 255);
6482         outputColors0[1] = RGBA(255, 0,   0,   255);
6483         outputColors0[2] = RGBA(128, 127, 0,   255);
6484         outputColors0[3] = RGBA(128, 0,   127, 255);
6485
6486         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
6487         outputColors1[0] = RGBA(127, 255, 127, 255);
6488         outputColors1[1] = RGBA(127, 128, 0,   255);
6489         outputColors1[2] = RGBA(0,   255, 0,   255);
6490         outputColors1[3] = RGBA(0,   128, 127, 255);
6491
6492         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
6493         outputColors2[0] = RGBA(127, 127, 255, 255);
6494         outputColors2[1] = RGBA(127, 0,   128, 255);
6495         outputColors2[2] = RGBA(0,   127, 128, 255);
6496         outputColors2[3] = RGBA(0,   0,   255, 255);
6497
6498         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
6499         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
6500         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
6501
6502         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
6503         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
6504         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
6505         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
6506         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
6507         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
6508         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
6509         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
6510         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
6511         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
6512         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
6513         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
6514         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
6515         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
6516         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
6517         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
6518         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
6519         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
6520         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
6521         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
6522         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
6523         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
6524         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
6525         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
6526         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
6527         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
6528         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
6529         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
6530         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
6531         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
6532         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
6533         // OpSConvert, OpFConvert: these two instructions involve ints/floats of different bitwidths.
6534         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
6535
6536         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
6537         {
6538                 map<string, string>     specializations;
6539                 map<string, string>     fragments;
6540                 vector<deInt32>         specConstants;
6541
6542                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
6543                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
6544                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
6545                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
6546                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
6547
6548                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
6549                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
6550                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
6551
6552                 specConstants.push_back(cases[caseNdx].scActualValue0);
6553                 specConstants.push_back(cases[caseNdx].scActualValue1);
6554
6555                 createTestsForAllStages(cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants, group.get());
6556         }
6557
6558         const char      decorations2[]                  =
6559                 "OpDecorate %sc_0  SpecId 0\n"
6560                 "OpDecorate %sc_1  SpecId 1\n"
6561                 "OpDecorate %sc_2  SpecId 2\n";
6562
6563         const char      typesAndConstants2[]    =
6564                 "%v3i32     = OpTypeVector %i32 3\n"
6565
6566                 "%sc_0      = OpSpecConstant %i32 0\n"
6567                 "%sc_1      = OpSpecConstant %i32 0\n"
6568                 "%sc_2      = OpSpecConstant %i32 0\n"
6569
6570                 "%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
6571                 "%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0    0\n"     // (sc_0, 0, 0)
6572                 "%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0    1\n"     // (0, sc_1, 0)
6573                 "%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0    2\n"     // (0, 0, sc_2)
6574                 "%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %sc_vec3_1 1 0 4\n" // (0,    sc_0, sc_1)
6575                 "%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2 5 1 2\n" // (sc_2, sc_0, sc_1)
6576                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012            0\n"     // sc_2
6577                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012            1\n"     // sc_0
6578                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012            2\n"     // sc_1
6579                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"        // (sc_2 - sc_0)
6580                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";       // (sc_2 - sc_0) * sc_1
6581
6582         const char      function2[]                             =
6583                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6584                 "%param     = OpFunctionParameter %v4f32\n"
6585                 "%label     = OpLabel\n"
6586                 "%result    = OpVariable %fp_v4f32 Function\n"
6587                 "             OpStore %result %param\n"
6588                 "%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
6589                 "%val       = OpLoad %f32 %loc\n"
6590                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
6591                 "             OpStore %loc %add\n"
6592                 "%ret       = OpLoad %v4f32 %result\n"
6593                 "             OpReturnValue %ret\n"
6594                 "             OpFunctionEnd\n";
6595
6596         map<string, string>     fragments;
6597         vector<deInt32>         specConstants;
6598
6599         fragments["decoration"] = decorations2;
6600         fragments["pre_main"]   = typesAndConstants2;
6601         fragments["testfun"]    = function2;
6602
6603         specConstants.push_back(56789);
6604         specConstants.push_back(-2);
6605         specConstants.push_back(56788);
6606
6607         createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
6608
6609         return group.release();
6610 }
6611
6612 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
6613 {
6614         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
6615         RGBA                                                    inputColors[4];
6616         RGBA                                                    outputColors1[4];
6617         RGBA                                                    outputColors2[4];
6618         RGBA                                                    outputColors3[4];
6619         map<string, string>                             fragments1;
6620         map<string, string>                             fragments2;
6621         map<string, string>                             fragments3;
6622
6623         const char      typesAndConstants1[]    =
6624                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6625                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6626                 "%c_f32_p5  = OpConstant %f32 0.5\n"
6627                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6628
6629         // vec4 test_code(vec4 param) {
6630         //   vec4 result = param;
6631         //   for (int i = 0; i < 4; ++i) {
6632         //     float operand;
6633         //     switch (i) {
6634         //       case 0: operand = .2; break;
6635         //       case 1: operand = .5; break;
6636         //       case 2: operand = .4; break;
6637         //       case 3: operand = .0; break;
6638         //       default: break; // unreachable
6639         //     }
6640         //     result[i] += operand;
6641         //   }
6642         //   return result;
6643         // }
6644         const char      function1[]                             =
6645                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6646                 "%param1    = OpFunctionParameter %v4f32\n"
6647                 "%lbl       = OpLabel\n"
6648                 "%iptr      = OpVariable %fp_i32 Function\n"
6649                 "%result    = OpVariable %fp_v4f32 Function\n"
6650                 "             OpStore %iptr %c_i32_0\n"
6651                 "             OpStore %result %param1\n"
6652                 "             OpBranch %loop\n"
6653
6654                 "%loop      = OpLabel\n"
6655                 "%ival      = OpLoad %i32 %iptr\n"
6656                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6657                 "             OpLoopMerge %exit %phi None\n"
6658                 "             OpBranchConditional %lt_4 %entry %exit\n"
6659
6660                 "%entry     = OpLabel\n"
6661                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6662                 "%val       = OpLoad %f32 %loc\n"
6663                 "             OpSelectionMerge %phi None\n"
6664                 "             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6665
6666                 "%case0     = OpLabel\n"
6667                 "             OpBranch %phi\n"
6668                 "%case1     = OpLabel\n"
6669                 "             OpBranch %phi\n"
6670                 "%case2     = OpLabel\n"
6671                 "             OpBranch %phi\n"
6672                 "%case3     = OpLabel\n"
6673                 "             OpBranch %phi\n"
6674
6675                 "%default   = OpLabel\n"
6676                 "             OpUnreachable\n"
6677
6678                 "%phi       = OpLabel\n"
6679                 "%operand   = OpPhi %f32 %c_f32_p4 %case2 %c_f32_p5 %case1 %c_f32_p2 %case0 %c_f32_0 %case3\n" // not in the order of blocks
6680                 "%add       = OpFAdd %f32 %val %operand\n"
6681                 "             OpStore %loc %add\n"
6682                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6683                 "             OpStore %iptr %ival_next\n"
6684                 "             OpBranch %loop\n"
6685
6686                 "%exit      = OpLabel\n"
6687                 "%ret       = OpLoad %v4f32 %result\n"
6688                 "             OpReturnValue %ret\n"
6689
6690                 "             OpFunctionEnd\n";
6691
6692         fragments1["pre_main"]  = typesAndConstants1;
6693         fragments1["testfun"]   = function1;
6694
6695         getHalfColorsFullAlpha(inputColors);
6696
6697         outputColors1[0]                = RGBA(178, 255, 229, 255);
6698         outputColors1[1]                = RGBA(178, 127, 102, 255);
6699         outputColors1[2]                = RGBA(51,  255, 102, 255);
6700         outputColors1[3]                = RGBA(51,  127, 229, 255);
6701
6702         createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
6703
6704         const char      typesAndConstants2[]    =
6705                 "%c_f32_p2  = OpConstant %f32 0.2\n";
6706
6707         // Add .4 to the second element of the given parameter.
6708         const char      function2[]                             =
6709                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6710                 "%param     = OpFunctionParameter %v4f32\n"
6711                 "%entry     = OpLabel\n"
6712                 "%result    = OpVariable %fp_v4f32 Function\n"
6713                 "             OpStore %result %param\n"
6714                 "%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6715                 "%val       = OpLoad %f32 %loc\n"
6716                 "             OpBranch %phi\n"
6717
6718                 "%phi        = OpLabel\n"
6719                 "%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
6720                 "%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
6721                 "%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
6722                 "%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
6723                 "%still_loop = OpSLessThan %bool %step %c_i32_2\n"
6724                 "              OpLoopMerge %exit %phi None\n"
6725                 "              OpBranchConditional %still_loop %phi %exit\n"
6726
6727                 "%exit       = OpLabel\n"
6728                 "              OpStore %loc %accum\n"
6729                 "%ret        = OpLoad %v4f32 %result\n"
6730                 "              OpReturnValue %ret\n"
6731
6732                 "              OpFunctionEnd\n";
6733
6734         fragments2["pre_main"]  = typesAndConstants2;
6735         fragments2["testfun"]   = function2;
6736
6737         outputColors2[0]                        = RGBA(127, 229, 127, 255);
6738         outputColors2[1]                        = RGBA(127, 102, 0,   255);
6739         outputColors2[2]                        = RGBA(0,   229, 0,   255);
6740         outputColors2[3]                        = RGBA(0,   102, 127, 255);
6741
6742         createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
6743
6744         const char      typesAndConstants3[]    =
6745                 "%true      = OpConstantTrue %bool\n"
6746                 "%false     = OpConstantFalse %bool\n"
6747                 "%c_f32_p2  = OpConstant %f32 0.2\n";
6748
6749         // Swap the second and the third element of the given parameter.
6750         const char      function3[]                             =
6751                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6752                 "%param     = OpFunctionParameter %v4f32\n"
6753                 "%entry     = OpLabel\n"
6754                 "%result    = OpVariable %fp_v4f32 Function\n"
6755                 "             OpStore %result %param\n"
6756                 "%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
6757                 "%a_init    = OpLoad %f32 %a_loc\n"
6758                 "%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
6759                 "%b_init    = OpLoad %f32 %b_loc\n"
6760                 "             OpBranch %phi\n"
6761
6762                 "%phi        = OpLabel\n"
6763                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
6764                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
6765                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
6766                 "              OpLoopMerge %exit %phi None\n"
6767                 "              OpBranchConditional %still_loop %phi %exit\n"
6768
6769                 "%exit       = OpLabel\n"
6770                 "              OpStore %a_loc %a_next\n"
6771                 "              OpStore %b_loc %b_next\n"
6772                 "%ret        = OpLoad %v4f32 %result\n"
6773                 "              OpReturnValue %ret\n"
6774
6775                 "              OpFunctionEnd\n";
6776
6777         fragments3["pre_main"]  = typesAndConstants3;
6778         fragments3["testfun"]   = function3;
6779
6780         outputColors3[0]                        = RGBA(127, 127, 127, 255);
6781         outputColors3[1]                        = RGBA(127, 0,   0,   255);
6782         outputColors3[2]                        = RGBA(0,   0,   127, 255);
6783         outputColors3[3]                        = RGBA(0,   127, 0,   255);
6784
6785         createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
6786
6787         return group.release();
6788 }
6789
6790 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
6791 {
6792         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
6793         RGBA                                                    inputColors[4];
6794         RGBA                                                    outputColors[4];
6795
6796         // With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
6797         // For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
6798         // only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
6799         // On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
6800         const char                                              constantsAndTypes[]      =
6801                 "%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
6802                 "%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6803                 "%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
6804                 "%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
6805                 "%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n"
6806                 ;
6807
6808         const char                                              function[]       =
6809                 "%test_code      = OpFunction %v4f32 None %v4f32_function\n"
6810                 "%param          = OpFunctionParameter %v4f32\n"
6811                 "%label          = OpLabel\n"
6812                 "%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
6813                 "%var2           = OpVariable %fp_f32 Function\n"
6814                 "%red            = OpCompositeExtract %f32 %param 0\n"
6815                 "%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
6816                 "                  OpStore %var2 %plus_red\n"
6817                 "%val1           = OpLoad %f32 %var1\n"
6818                 "%val2           = OpLoad %f32 %var2\n"
6819                 "%mul            = OpFMul %f32 %val1 %val2\n"
6820                 "%add            = OpFAdd %f32 %mul %c_f32_n1\n"
6821                 "%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
6822                 "%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
6823                 "%success        = OpLogicalOr %bool %is0 %isn1n24\n"
6824                 "%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
6825                 "%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
6826                 "                  OpReturnValue %ret\n"
6827                 "                  OpFunctionEnd\n";
6828
6829         struct CaseNameDecoration
6830         {
6831                 string name;
6832                 string decoration;
6833         };
6834
6835
6836         CaseNameDecoration tests[] = {
6837                 {"multiplication",      "OpDecorate %mul NoContraction"},
6838                 {"addition",            "OpDecorate %add NoContraction"},
6839                 {"both",                        "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
6840         };
6841
6842         getHalfColorsFullAlpha(inputColors);
6843
6844         for (deUint8 idx = 0; idx < 4; ++idx)
6845         {
6846                 inputColors[idx].setRed(0);
6847                 outputColors[idx] = RGBA(0, 0, 0, 255);
6848         }
6849
6850         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
6851         {
6852                 map<string, string> fragments;
6853
6854                 fragments["decoration"] = tests[testNdx].decoration;
6855                 fragments["pre_main"] = constantsAndTypes;
6856                 fragments["testfun"] = function;
6857
6858                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
6859         }
6860
6861         return group.release();
6862 }
6863
6864 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
6865 {
6866         de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
6867         RGBA                                                    colors[4];
6868
6869         const char                                              constantsAndTypes[]      =
6870                 "%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
6871                 "%fp_a2f32          = OpTypePointer Function %a2f32\n"
6872                 "%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
6873                 "%fp_stype          = OpTypePointer Function %stype\n";
6874
6875         const char                                              function[]       =
6876                 "%test_code         = OpFunction %v4f32 None %v4f32_function\n"
6877                 "%param1            = OpFunctionParameter %v4f32\n"
6878                 "%lbl               = OpLabel\n"
6879                 "%v1                = OpVariable %fp_v4f32 Function\n"
6880                 "%v2                = OpVariable %fp_a2f32 Function\n"
6881                 "%v3                = OpVariable %fp_f32 Function\n"
6882                 "%v                 = OpVariable %fp_stype Function\n"
6883                 "%vv                = OpVariable %fp_stype Function\n"
6884                 "%vvv               = OpVariable %fp_f32 Function\n"
6885
6886                 "                     OpStore %v1 %c_v4f32_1_1_1_1\n"
6887                 "                     OpStore %v2 %c_a2f32_1\n"
6888                 "                     OpStore %v3 %c_f32_1\n"
6889
6890                 "%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6891                 "%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
6892                 "%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
6893                 "%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
6894                 "%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
6895                 "%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
6896
6897                 "                    OpStore %p_v4f32 %v1_v ${access_type}\n"
6898                 "                    OpStore %p_a2f32 %v2_v ${access_type}\n"
6899                 "                    OpStore %p_f32 %v3_v ${access_type}\n"
6900
6901                 "                    OpCopyMemory %vv %v ${access_type}\n"
6902                 "                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
6903
6904                 "%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
6905                 "%v_f32_2          = OpLoad %f32 %p_f32_2\n"
6906                 "%v_f32_3          = OpLoad %f32 %vvv\n"
6907
6908                 "%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
6909                 "%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
6910                 "                    OpReturnValue %ret2\n"
6911                 "                    OpFunctionEnd\n";
6912
6913         struct NameMemoryAccess
6914         {
6915                 string name;
6916                 string accessType;
6917         };
6918
6919
6920         NameMemoryAccess tests[] =
6921         {
6922                 { "none", "" },
6923                 { "volatile", "Volatile" },
6924                 { "aligned",  "Aligned 1" },
6925                 { "volatile_aligned",  "Volatile|Aligned 1" },
6926                 { "nontemporal_aligned",  "Nontemporal|Aligned 1" },
6927                 { "volatile_nontemporal",  "Volatile|Nontemporal" },
6928                 { "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
6929         };
6930
6931         getHalfColorsFullAlpha(colors);
6932
6933         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
6934         {
6935                 map<string, string> fragments;
6936                 map<string, string> memoryAccess;
6937                 memoryAccess["access_type"] = tests[testNdx].accessType;
6938
6939                 fragments["pre_main"] = constantsAndTypes;
6940                 fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
6941                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
6942         }
6943         return memoryAccessTests.release();
6944 }
6945 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
6946 {
6947         de::MovePtr<tcu::TestCaseGroup>         opUndefTests             (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
6948         RGBA                                                            defaultColors[4];
6949         map<string, string>                                     fragments;
6950         getDefaultColors(defaultColors);
6951
6952         // First, simple cases that don't do anything with the OpUndef result.
6953         fragments["testfun"] =
6954                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6955                 "%param1 = OpFunctionParameter %v4f32\n"
6956                 "%label_testfun = OpLabel\n"
6957                 "%undef = OpUndef %type\n"
6958                 "OpReturnValue %param1\n"
6959                 "OpFunctionEnd\n"
6960                 ;
6961         struct NameCodePair { string name, code; };
6962         const NameCodePair tests[] =
6963         {
6964                 {"bool", "%type = OpTypeBool"},
6965                 {"vec2uint32", "%type = OpTypeVector %u32 2"},
6966                 {"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown"},
6967                 {"sampler", "%type = OpTypeSampler"},
6968                 {"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img"},
6969                 {"pointer", "%type = OpTypePointer Function %i32"},
6970                 {"runtimearray", "%type = OpTypeRuntimeArray %f32"},
6971                 {"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100"},
6972                 {"struct", "%type = OpTypeStruct %f32 %i32 %u32"}};
6973         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6974         {
6975                 fragments["pre_main"] = tests[testNdx].code;
6976                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
6977         }
6978         fragments.clear();
6979
6980         fragments["testfun"] =
6981                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6982                 "%param1 = OpFunctionParameter %v4f32\n"
6983                 "%label_testfun = OpLabel\n"
6984                 "%undef = OpUndef %f32\n"
6985                 "%zero = OpFMul %f32 %undef %c_f32_0\n"
6986                 "%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
6987                 "%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
6988                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
6989                 "%b = OpFAdd %f32 %a %actually_zero\n"
6990                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
6991                 "OpReturnValue %ret\n"
6992                 "OpFunctionEnd\n"
6993                 ;
6994         createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
6995
6996         fragments["testfun"] =
6997                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
6998                 "%param1 = OpFunctionParameter %v4f32\n"
6999                 "%label_testfun = OpLabel\n"
7000                 "%undef = OpUndef %i32\n"
7001                 "%zero = OpIMul %i32 %undef %c_i32_0\n"
7002                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7003                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7004                 "OpReturnValue %ret\n"
7005                 "OpFunctionEnd\n"
7006                 ;
7007         createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7008
7009         fragments["testfun"] =
7010                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7011                 "%param1 = OpFunctionParameter %v4f32\n"
7012                 "%label_testfun = OpLabel\n"
7013                 "%undef = OpUndef %u32\n"
7014                 "%zero = OpIMul %u32 %undef %c_i32_0\n"
7015                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7016                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7017                 "OpReturnValue %ret\n"
7018                 "OpFunctionEnd\n"
7019                 ;
7020         createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7021
7022         fragments["testfun"] =
7023                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7024                 "%param1 = OpFunctionParameter %v4f32\n"
7025                 "%label_testfun = OpLabel\n"
7026                 "%undef = OpUndef %v4f32\n"
7027                 "%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
7028                 "%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
7029                 "%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
7030                 "%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
7031                 "%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
7032                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7033                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7034                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7035                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7036                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7037                 "%actually_zero_1 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_1\n"
7038                 "%actually_zero_2 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_2\n"
7039                 "%actually_zero_3 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_3\n"
7040                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7041                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7042                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7043                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7044                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7045                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7046                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7047                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7048                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7049                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7050                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7051                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7052                 "OpReturnValue %ret\n"
7053                 "OpFunctionEnd\n"
7054                 ;
7055         createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7056
7057         fragments["pre_main"] =
7058                 "%v2f32 = OpTypeVector %f32 2\n"
7059                 "%m2x2f32 = OpTypeMatrix %v2f32 2\n";
7060         fragments["testfun"] =
7061                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7062                 "%param1 = OpFunctionParameter %v4f32\n"
7063                 "%label_testfun = OpLabel\n"
7064                 "%undef = OpUndef %m2x2f32\n"
7065                 "%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
7066                 "%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
7067                 "%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
7068                 "%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
7069                 "%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
7070                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7071                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7072                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7073                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7074                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7075                 "%actually_zero_1 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_1\n"
7076                 "%actually_zero_2 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_2\n"
7077                 "%actually_zero_3 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_3\n"
7078                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7079                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7080                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7081                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7082                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7083                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7084                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7085                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7086                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7087                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7088                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7089                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7090                 "OpReturnValue %ret\n"
7091                 "OpFunctionEnd\n"
7092                 ;
7093         createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
7094
7095         return opUndefTests.release();
7096 }
7097
7098 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
7099 {
7100         const RGBA              inputColors[4]          =
7101         {
7102                 RGBA(0,         0,              0,              255),
7103                 RGBA(0,         0,              255,    255),
7104                 RGBA(0,         255,    0,              255),
7105                 RGBA(0,         255,    255,    255)
7106         };
7107
7108         const RGBA              expectedColors[4]       =
7109         {
7110                 RGBA(255,        0,              0,              255),
7111                 RGBA(255,        0,              0,              255),
7112                 RGBA(255,        0,              0,              255),
7113                 RGBA(255,        0,              0,              255)
7114         };
7115
7116         const struct SingleFP16Possibility
7117         {
7118                 const char* name;
7119                 const char* constant;  // Value to assign to %test_constant.
7120                 float           valueAsFloat;
7121                 const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
7122         }                               tests[]                         =
7123         {
7124                 {
7125                         "negative",
7126                         "-0x1.3p1\n",
7127                         -constructNormalizedFloat(1, 0x300000),
7128                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7129                 }, // -19
7130                 {
7131                         "positive",
7132                         "0x1.0p7\n",
7133                         constructNormalizedFloat(7, 0x000000),
7134                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7135                 },  // +128
7136                 // SPIR-V requires that OpQuantizeToF16 flushes
7137                 // any numbers that would end up denormalized in F16 to zero.
7138                 {
7139                         "denorm",
7140                         "0x0.0006p-126\n",
7141                         std::ldexp(1.5f, -140),
7142                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7143                 },  // denorm
7144                 {
7145                         "negative_denorm",
7146                         "-0x0.0006p-126\n",
7147                         -std::ldexp(1.5f, -140),
7148                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7149                 }, // -denorm
7150                 {
7151                         "too_small",
7152                         "0x1.0p-16\n",
7153                         std::ldexp(1.0f, -16),
7154                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7155                 },     // too small positive
7156                 {
7157                         "negative_too_small",
7158                         "-0x1.0p-32\n",
7159                         -std::ldexp(1.0f, -32),
7160                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7161                 },      // too small negative
7162                 {
7163                         "negative_inf",
7164                         "-0x1.0p128\n",
7165                         -std::ldexp(1.0f, 128),
7166
7167                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7168                         "%inf = OpIsInf %bool %c\n"
7169                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7170                 },     // -inf to -inf
7171                 {
7172                         "inf",
7173                         "0x1.0p128\n",
7174                         std::ldexp(1.0f, 128),
7175
7176                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7177                         "%inf = OpIsInf %bool %c\n"
7178                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7179                 },     // +inf to +inf
7180                 {
7181                         "round_to_negative_inf",
7182                         "-0x1.0p32\n",
7183                         -std::ldexp(1.0f, 32),
7184
7185                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7186                         "%inf = OpIsInf %bool %c\n"
7187                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7188                 },     // round to -inf
7189                 {
7190                         "round_to_inf",
7191                         "0x1.0p16\n",
7192                         std::ldexp(1.0f, 16),
7193
7194                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7195                         "%inf = OpIsInf %bool %c\n"
7196                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7197                 },     // round to +inf
7198                 {
7199                         "nan",
7200                         "0x1.1p128\n",
7201                         std::numeric_limits<float>::quiet_NaN(),
7202
7203                         // Test for any NaN value, as NaNs are not preserved
7204                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7205                         "%cond = OpIsNan %bool %direct_quant\n"
7206                 }, // nan
7207                 {
7208                         "negative_nan",
7209                         "-0x1.0001p128\n",
7210                         std::numeric_limits<float>::quiet_NaN(),
7211
7212                         // Test for any NaN value, as NaNs are not preserved
7213                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7214                         "%cond = OpIsNan %bool %direct_quant\n"
7215                 } // -nan
7216         };
7217         const char*             constants                       =
7218                 "%test_constant = OpConstant %f32 ";  // The value will be test.constant.
7219
7220         StringTemplate  function                        (
7221                 "%test_code     = OpFunction %v4f32 None %v4f32_function\n"
7222                 "%param1        = OpFunctionParameter %v4f32\n"
7223                 "%label_testfun = OpLabel\n"
7224                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7225                 "%b             = OpFAdd %f32 %test_constant %a\n"
7226                 "%c             = OpQuantizeToF16 %f32 %b\n"
7227                 "${condition}\n"
7228                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7229                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7230                 "                 OpReturnValue %retval\n"
7231                 "OpFunctionEnd\n"
7232         );
7233
7234         const char*             specDecorations         = "OpDecorate %test_constant SpecId 0\n";
7235         const char*             specConstants           =
7236                         "%test_constant = OpSpecConstant %f32 0.\n"
7237                         "%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
7238
7239         StringTemplate  specConstantFunction(
7240                 "%test_code     = OpFunction %v4f32 None %v4f32_function\n"
7241                 "%param1        = OpFunctionParameter %v4f32\n"
7242                 "%label_testfun = OpLabel\n"
7243                 "${condition}\n"
7244                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7245                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7246                 "                 OpReturnValue %retval\n"
7247                 "OpFunctionEnd\n"
7248         );
7249
7250         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7251         {
7252                 map<string, string>                                                             codeSpecialization;
7253                 map<string, string>                                                             fragments;
7254                 codeSpecialization["condition"]                                 = tests[idx].condition;
7255                 fragments["testfun"]                                                    = function.specialize(codeSpecialization);
7256                 fragments["pre_main"]                                                   = string(constants) + tests[idx].constant + "\n";
7257                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
7258         }
7259
7260         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7261         {
7262                 map<string, string>                                                             codeSpecialization;
7263                 map<string, string>                                                             fragments;
7264                 vector<deInt32>                                                                 passConstants;
7265                 deInt32                                                                                 specConstant;
7266
7267                 codeSpecialization["condition"]                                 = tests[idx].condition;
7268                 fragments["testfun"]                                                    = specConstantFunction.specialize(codeSpecialization);
7269                 fragments["decoration"]                                                 = specDecorations;
7270                 fragments["pre_main"]                                                   = specConstants;
7271
7272                 memcpy(&specConstant, &tests[idx].valueAsFloat, sizeof(float));
7273                 passConstants.push_back(specConstant);
7274
7275                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
7276         }
7277 }
7278
7279 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
7280 {
7281         RGBA inputColors[4] =  {
7282                 RGBA(0,         0,              0,              255),
7283                 RGBA(0,         0,              255,    255),
7284                 RGBA(0,         255,    0,              255),
7285                 RGBA(0,         255,    255,    255)
7286         };
7287
7288         RGBA expectedColors[4] =
7289         {
7290                 RGBA(255,        0,              0,              255),
7291                 RGBA(255,        0,              0,              255),
7292                 RGBA(255,        0,              0,              255),
7293                 RGBA(255,        0,              0,              255)
7294         };
7295
7296         struct DualFP16Possibility
7297         {
7298                 const char* name;
7299                 const char* input;
7300                 float           inputAsFloat;
7301                 const char* possibleOutput1;
7302                 const char* possibleOutput2;
7303         } tests[] = {
7304                 {
7305                         "positive_round_up_or_round_down",
7306                         "0x1.3003p8",
7307                         constructNormalizedFloat(8, 0x300300),
7308                         "0x1.304p8",
7309                         "0x1.3p8"
7310                 },
7311                 {
7312                         "negative_round_up_or_round_down",
7313                         "-0x1.6008p-7",
7314                         -constructNormalizedFloat(-7, 0x600800),
7315                         "-0x1.6p-7",
7316                         "-0x1.604p-7"
7317                 },
7318                 {
7319                         "carry_bit",
7320                         "0x1.01ep2",
7321                         constructNormalizedFloat(2, 0x01e000),
7322                         "0x1.01cp2",
7323                         "0x1.02p2"
7324                 },
7325                 {
7326                         "carry_to_exponent",
7327                         "0x1.ffep1",
7328                         constructNormalizedFloat(1, 0xffe000),
7329                         "0x1.ffcp1",
7330                         "0x1.0p2"
7331                 },
7332         };
7333         StringTemplate constants (
7334                 "%input_const = OpConstant %f32 ${input}\n"
7335                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
7336                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
7337                 );
7338
7339         StringTemplate specConstants (
7340                 "%input_const = OpSpecConstant %f32 0.\n"
7341                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
7342                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
7343         );
7344
7345         const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
7346
7347         const char* function  =
7348                 "%test_code     = OpFunction %v4f32 None %v4f32_function\n"
7349                 "%param1        = OpFunctionParameter %v4f32\n"
7350                 "%label_testfun = OpLabel\n"
7351                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7352                 // For the purposes of this test we assume that 0.f will always get
7353                 // faithfully passed through the pipeline stages.
7354                 "%b             = OpFAdd %f32 %input_const %a\n"
7355                 "%c             = OpQuantizeToF16 %f32 %b\n"
7356                 "%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
7357                 "%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
7358                 "%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
7359                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7360                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
7361                 "                 OpReturnValue %retval\n"
7362                 "OpFunctionEnd\n";
7363
7364         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
7365                 map<string, string>                                                                     fragments;
7366                 map<string, string>                                                                     constantSpecialization;
7367
7368                 constantSpecialization["input"]                                         = tests[idx].input;
7369                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
7370                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
7371                 fragments["testfun"]                                                            = function;
7372                 fragments["pre_main"]                                                           = constants.specialize(constantSpecialization);
7373                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
7374         }
7375
7376         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
7377                 map<string, string>                                                                     fragments;
7378                 map<string, string>                                                                     constantSpecialization;
7379                 vector<deInt32>                                                                         passConstants;
7380                 deInt32                                                                                         specConstant;
7381
7382                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
7383                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
7384                 fragments["testfun"]                                                            = function;
7385                 fragments["decoration"]                                                         = specDecorations;
7386                 fragments["pre_main"]                                                           = specConstants.specialize(constantSpecialization);
7387
7388                 memcpy(&specConstant, &tests[idx].inputAsFloat, sizeof(float));
7389                 passConstants.push_back(specConstant);
7390
7391                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
7392         }
7393 }
7394
7395 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
7396 {
7397         de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
7398         createOpQuantizeSingleOptionTests(opQuantizeTests.get());
7399         createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
7400         return opQuantizeTests.release();
7401 }
7402
7403 struct ShaderPermutation
7404 {
7405         deUint8 vertexPermutation;
7406         deUint8 geometryPermutation;
7407         deUint8 tesscPermutation;
7408         deUint8 tessePermutation;
7409         deUint8 fragmentPermutation;
7410 };
7411
7412 ShaderPermutation getShaderPermutation(deUint8 inputValue)
7413 {
7414         ShaderPermutation       permutation =
7415         {
7416                 static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
7417                 static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
7418                 static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
7419                 static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
7420                 static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
7421         };
7422         return permutation;
7423 }
7424
7425 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
7426 {
7427         RGBA                                                            defaultColors[4];
7428         RGBA                                                            invertedColors[4];
7429         de::MovePtr<tcu::TestCaseGroup>         moduleTests                     (new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
7430
7431         const ShaderElement                                     combinedPipeline[]      =
7432         {
7433                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
7434                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
7435                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
7436                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
7437                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
7438         };
7439
7440         getDefaultColors(defaultColors);
7441         getInvertedDefaultColors(invertedColors);
7442         addFunctionCaseWithPrograms<InstanceContext>(moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline, createInstanceContext(combinedPipeline, map<string, string>()));
7443
7444         const char* numbers[] =
7445         {
7446                 "1", "2"
7447         };
7448
7449         for (deInt8 idx = 0; idx < 32; ++idx)
7450         {
7451                 ShaderPermutation                       permutation             = getShaderPermutation(idx);
7452                 string                                          name                    = string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
7453                 const ShaderElement                     pipeline[]              =
7454                 {
7455                         ShaderElement("vert",   string("vert") +        numbers[permutation.vertexPermutation],         VK_SHADER_STAGE_VERTEX_BIT),
7456                         ShaderElement("geom",   string("geom") +        numbers[permutation.geometryPermutation],       VK_SHADER_STAGE_GEOMETRY_BIT),
7457                         ShaderElement("tessc",  string("tessc") +       numbers[permutation.tesscPermutation],          VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
7458                         ShaderElement("tesse",  string("tesse") +       numbers[permutation.tessePermutation],          VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
7459                         ShaderElement("frag",   string("frag") +        numbers[permutation.fragmentPermutation],       VK_SHADER_STAGE_FRAGMENT_BIT)
7460                 };
7461
7462                 // If there are an even number of swaps, then it should be no-op.
7463                 // If there are an odd number, the color should be flipped.
7464                 if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
7465                 {
7466                         addFunctionCaseWithPrograms<InstanceContext>(moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline, createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
7467                 }
7468                 else
7469                 {
7470                         addFunctionCaseWithPrograms<InstanceContext>(moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline, createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
7471                 }
7472         }
7473         return moduleTests.release();
7474 }
7475
7476 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
7477 {
7478         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
7479         RGBA defaultColors[4];
7480         getDefaultColors(defaultColors);
7481         map<string, string> fragments;
7482         fragments["pre_main"] =
7483                 "%c_f32_5 = OpConstant %f32 5.\n";
7484
7485         // A loop with a single block. The Continue Target is the loop block
7486         // itself. In SPIR-V terms, the "loop construct" contains no blocks at all
7487         // -- the "continue construct" forms the entire loop.
7488         fragments["testfun"] =
7489                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7490                 "%param1 = OpFunctionParameter %v4f32\n"
7491
7492                 "%entry = OpLabel\n"
7493                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7494                 "OpBranch %loop\n"
7495
7496                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
7497                 "%loop = OpLabel\n"
7498                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
7499                 "%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
7500                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
7501                 "%val = OpFAdd %f32 %val1 %delta\n"
7502                 "%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
7503                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7504                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7505                 "OpLoopMerge %exit %loop None\n"
7506                 "OpBranchConditional %again %loop %exit\n"
7507
7508                 "%exit = OpLabel\n"
7509                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
7510                 "OpReturnValue %result\n"
7511
7512                 "OpFunctionEnd\n"
7513                 ;
7514         createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
7515
7516         // Body comprised of multiple basic blocks.
7517         const StringTemplate multiBlock(
7518                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7519                 "%param1 = OpFunctionParameter %v4f32\n"
7520
7521                 "%entry = OpLabel\n"
7522                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7523                 "OpBranch %loop\n"
7524
7525                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
7526                 "%loop = OpLabel\n"
7527                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
7528                 "%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
7529                 "%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
7530                 // There are several possibilities for the Continue Target below.  Each
7531                 // will be specialized into a separate test case.
7532                 "OpLoopMerge %exit ${continue_target} None\n"
7533                 "OpBranch %if\n"
7534
7535                 "%if = OpLabel\n"
7536                 ";delta_next = (delta > 0) ? -1 : 1;\n"
7537                 "%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
7538                 "OpSelectionMerge %gather DontFlatten\n"
7539                 "OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
7540
7541                 "%odd = OpLabel\n"
7542                 "OpBranch %gather\n"
7543
7544                 "%even = OpLabel\n"
7545                 "OpBranch %gather\n"
7546
7547                 "%gather = OpLabel\n"
7548                 "%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
7549                 "%val = OpFAdd %f32 %val1 %delta\n"
7550                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7551                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7552                 "OpBranchConditional %again %loop %exit\n"
7553
7554                 "%exit = OpLabel\n"
7555                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
7556                 "OpReturnValue %result\n"
7557
7558                 "OpFunctionEnd\n");
7559
7560         map<string, string> continue_target;
7561
7562         // The Continue Target is the loop block itself.
7563         continue_target["continue_target"] = "%loop";
7564         fragments["testfun"] = multiBlock.specialize(continue_target);
7565         createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
7566
7567         // The Continue Target is at the end of the loop.
7568         continue_target["continue_target"] = "%gather";
7569         fragments["testfun"] = multiBlock.specialize(continue_target);
7570         createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
7571
7572         // A loop with continue statement.
7573         fragments["testfun"] =
7574                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7575                 "%param1 = OpFunctionParameter %v4f32\n"
7576
7577                 "%entry = OpLabel\n"
7578                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7579                 "OpBranch %loop\n"
7580
7581                 ";adds 4, 3, and 1 to %val0 (skips 2)\n"
7582                 "%loop = OpLabel\n"
7583                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
7584                 "%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
7585                 "OpLoopMerge %exit %continue None\n"
7586                 "OpBranch %if\n"
7587
7588                 "%if = OpLabel\n"
7589                 ";skip if %count==2\n"
7590                 "%eq2 = OpIEqual %bool %count %c_i32_2\n"
7591                 "OpSelectionMerge %continue DontFlatten\n"
7592                 "OpBranchConditional %eq2 %continue %body\n"
7593
7594                 "%body = OpLabel\n"
7595                 "%fcount = OpConvertSToF %f32 %count\n"
7596                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
7597                 "OpBranch %continue\n"
7598
7599                 "%continue = OpLabel\n"
7600                 "%val = OpPhi %f32 %val2 %body %val1 %if\n"
7601                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7602                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7603                 "OpBranchConditional %again %loop %exit\n"
7604
7605                 "%exit = OpLabel\n"
7606                 "%same = OpFSub %f32 %val %c_f32_8\n"
7607                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
7608                 "OpReturnValue %result\n"
7609                 "OpFunctionEnd\n";
7610         createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
7611
7612         // A loop with break.
7613         fragments["testfun"] =
7614                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7615                 "%param1 = OpFunctionParameter %v4f32\n"
7616
7617                 "%entry = OpLabel\n"
7618                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
7619                 "%dot = OpDot %f32 %param1 %param1\n"
7620                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
7621                 "%zero = OpConvertFToU %u32 %div\n"
7622                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
7623                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7624                 "OpBranch %loop\n"
7625
7626                 ";adds 4 and 3 to %val0 (exits early)\n"
7627                 "%loop = OpLabel\n"
7628                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
7629                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
7630                 "OpLoopMerge %exit %continue None\n"
7631                 "OpBranch %if\n"
7632
7633                 "%if = OpLabel\n"
7634                 ";end loop if %count==%two\n"
7635                 "%above2 = OpSGreaterThan %bool %count %two\n"
7636                 "OpSelectionMerge %continue DontFlatten\n"
7637                 "OpBranchConditional %above2 %body %exit\n"
7638
7639                 "%body = OpLabel\n"
7640                 "%fcount = OpConvertSToF %f32 %count\n"
7641                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
7642                 "OpBranch %continue\n"
7643
7644                 "%continue = OpLabel\n"
7645                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7646                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7647                 "OpBranchConditional %again %loop %exit\n"
7648
7649                 "%exit = OpLabel\n"
7650                 "%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
7651                 "%same = OpFSub %f32 %val_post %c_f32_7\n"
7652                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
7653                 "OpReturnValue %result\n"
7654                 "OpFunctionEnd\n";
7655         createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
7656
7657         // A loop with return.
7658         fragments["testfun"] =
7659                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7660                 "%param1 = OpFunctionParameter %v4f32\n"
7661
7662                 "%entry = OpLabel\n"
7663                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
7664                 "%dot = OpDot %f32 %param1 %param1\n"
7665                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
7666                 "%zero = OpConvertFToU %u32 %div\n"
7667                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
7668                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7669                 "OpBranch %loop\n"
7670
7671                 ";returns early without modifying %param1\n"
7672                 "%loop = OpLabel\n"
7673                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
7674                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
7675                 "OpLoopMerge %exit %continue None\n"
7676                 "OpBranch %if\n"
7677
7678                 "%if = OpLabel\n"
7679                 ";return if %count==%two\n"
7680                 "%above2 = OpSGreaterThan %bool %count %two\n"
7681                 "OpSelectionMerge %continue DontFlatten\n"
7682                 "OpBranchConditional %above2 %body %early_exit\n"
7683
7684                 "%early_exit = OpLabel\n"
7685                 "OpReturnValue %param1\n"
7686
7687                 "%body = OpLabel\n"
7688                 "%fcount = OpConvertSToF %f32 %count\n"
7689                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
7690                 "OpBranch %continue\n"
7691
7692                 "%continue = OpLabel\n"
7693                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7694                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7695                 "OpBranchConditional %again %loop %exit\n"
7696
7697                 "%exit = OpLabel\n"
7698                 ";should never get here, so return an incorrect result\n"
7699                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
7700                 "OpReturnValue %result\n"
7701                 "OpFunctionEnd\n";
7702         createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
7703
7704         return testGroup.release();
7705 }
7706
7707 // Adds a new test to group using custom fragments for the tessellation-control
7708 // stage and passthrough fragments for all other stages.  Uses default colors
7709 // for input and expected output.
7710 void addTessCtrlTest(tcu::TestCaseGroup* group, const char* name, const map<string, string>& fragments)
7711 {
7712         RGBA defaultColors[4];
7713         getDefaultColors(defaultColors);
7714         const ShaderElement pipelineStages[] =
7715         {
7716                 ShaderElement("vert", "main", VK_SHADER_STAGE_VERTEX_BIT),
7717                 ShaderElement("tessc", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
7718                 ShaderElement("tesse", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
7719                 ShaderElement("frag", "main", VK_SHADER_STAGE_FRAGMENT_BIT),
7720         };
7721
7722         addFunctionCaseWithPrograms<InstanceContext>(group, name, "", addShaderCodeCustomTessControl,
7723                                                                                                  runAndVerifyDefaultPipeline, createInstanceContext(
7724                                                                                                          pipelineStages, defaultColors, defaultColors, fragments, StageToSpecConstantMap()));
7725 }
7726
7727 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
7728 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
7729 {
7730         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
7731         map<string, string> fragments;
7732
7733         // A barrier inside a function body.
7734         fragments["pre_main"] =
7735                 "%Workgroup = OpConstant %i32 2\n"
7736                 "%SequentiallyConsistent = OpConstant %i32 0x10\n";
7737         fragments["testfun"] =
7738                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7739                 "%param1 = OpFunctionParameter %v4f32\n"
7740                 "%label_testfun = OpLabel\n"
7741                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7742                 "OpReturnValue %param1\n"
7743                 "OpFunctionEnd\n";
7744         addTessCtrlTest(testGroup.get(), "in_function", fragments);
7745
7746         // Common setup code for the following tests.
7747         fragments["pre_main"] =
7748                 "%Workgroup = OpConstant %i32 2\n"
7749                 "%SequentiallyConsistent = OpConstant %i32 0x10\n"
7750                 "%c_f32_5 = OpConstant %f32 5.\n";
7751         const string setupPercentZero =  // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
7752                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7753                 "%param1 = OpFunctionParameter %v4f32\n"
7754                 "%entry = OpLabel\n"
7755                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
7756                 "%dot = OpDot %f32 %param1 %param1\n"
7757                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
7758                 "%zero = OpConvertFToU %u32 %div\n";
7759
7760         // Barriers inside OpSwitch branches.
7761         fragments["testfun"] =
7762                 setupPercentZero +
7763                 "OpSelectionMerge %switch_exit None\n"
7764                 "OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
7765
7766                 "%case1 = OpLabel\n"
7767                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
7768                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7769                 "%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
7770                 "OpBranch %switch_exit\n"
7771
7772                 "%switch_default = OpLabel\n"
7773                 "%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
7774                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
7775                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7776                 "OpBranch %switch_exit\n"
7777
7778                 "%case0 = OpLabel\n"
7779                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7780                 "OpBranch %switch_exit\n"
7781
7782                 "%switch_exit = OpLabel\n"
7783                 "%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
7784                 "OpReturnValue %ret\n"
7785                 "OpFunctionEnd\n";
7786         addTessCtrlTest(testGroup.get(), "in_switch", fragments);
7787
7788         // Barriers inside if-then-else.
7789         fragments["testfun"] =
7790                 setupPercentZero +
7791                 "%eq0 = OpIEqual %bool %zero %c_u32_0\n"
7792                 "OpSelectionMerge %exit DontFlatten\n"
7793                 "OpBranchConditional %eq0 %then %else\n"
7794
7795                 "%else = OpLabel\n"
7796                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
7797                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7798                 "%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
7799                 "OpBranch %exit\n"
7800
7801                 "%then = OpLabel\n"
7802                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7803                 "OpBranch %exit\n"
7804
7805                 "%exit = OpLabel\n"
7806                 "%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
7807                 "OpReturnValue %ret\n"
7808                 "OpFunctionEnd\n";
7809         addTessCtrlTest(testGroup.get(), "in_if", fragments);
7810
7811         // A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
7812         // http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
7813         fragments["testfun"] =
7814                 setupPercentZero +
7815                 "%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
7816                 "%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
7817                 "OpSelectionMerge %exit DontFlatten\n"
7818                 "OpBranchConditional %thread0 %then %else\n"
7819
7820                 "%else = OpLabel\n"
7821                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7822                 "OpBranch %exit\n"
7823
7824                 "%then = OpLabel\n"
7825                 "%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
7826                 "OpBranch %exit\n"
7827
7828                 "%exit = OpLabel\n"
7829                 "%val = OpPhi %f32 %val0 %else %val1 %then\n"
7830                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7831                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
7832                 "OpReturnValue %ret\n"
7833                 "OpFunctionEnd\n";
7834         addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
7835
7836         // A barrier inside a loop.
7837         fragments["pre_main"] =
7838                 "%Workgroup = OpConstant %i32 2\n"
7839                 "%SequentiallyConsistent = OpConstant %i32 0x10\n"
7840                 "%c_f32_10 = OpConstant %f32 10.\n";
7841         fragments["testfun"] =
7842                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7843                 "%param1 = OpFunctionParameter %v4f32\n"
7844                 "%entry = OpLabel\n"
7845                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7846                 "OpBranch %loop\n"
7847
7848                 ";adds 4, 3, 2, and 1 to %val0\n"
7849                 "%loop = OpLabel\n"
7850                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
7851                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
7852                 "OpControlBarrier %Workgroup %Workgroup %SequentiallyConsistent\n"
7853                 "%fcount = OpConvertSToF %f32 %count\n"
7854                 "%val = OpFAdd %f32 %val1 %fcount\n"
7855                 "%count__ = OpISub %i32 %count %c_i32_1\n"
7856                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
7857                 "OpLoopMerge %exit %loop None\n"
7858                 "OpBranchConditional %again %loop %exit\n"
7859
7860                 "%exit = OpLabel\n"
7861                 "%same = OpFSub %f32 %val %c_f32_10\n"
7862                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
7863                 "OpReturnValue %ret\n"
7864                 "OpFunctionEnd\n";
7865         addTessCtrlTest(testGroup.get(), "in_loop", fragments);
7866
7867         return testGroup.release();
7868 }
7869
7870 // Test for the OpFRem instruction.
7871 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
7872 {
7873         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
7874         map<string, string>                                     fragments;
7875         RGBA                                                            inputColors[4];
7876         RGBA                                                            outputColors[4];
7877
7878         fragments["pre_main"]                            =
7879                 "%c_f32_3 = OpConstant %f32 3.0\n"
7880                 "%c_f32_n3 = OpConstant %f32 -3.0\n"
7881                 "%c_f32_4 = OpConstant %f32 4.0\n"
7882                 "%c_f32_p75 = OpConstant %f32 0.75\n"
7883                 "%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
7884                 "%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
7885                 "%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
7886
7887         // The test does the following.
7888         // vec4 result = (param1 * 8.0) - 4.0;
7889         // return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
7890         fragments["testfun"]                             =
7891                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
7892                 "%param1 = OpFunctionParameter %v4f32\n"
7893                 "%label_testfun = OpLabel\n"
7894                 "%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
7895                 "%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
7896                 "%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
7897                 "%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
7898                 "%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
7899                 "%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
7900                 "OpReturnValue %xy_0_1\n"
7901                 "OpFunctionEnd\n";
7902
7903
7904         inputColors[0]          = RGBA(16,      16,             0, 255);
7905         inputColors[1]          = RGBA(232, 232,        0, 255);
7906         inputColors[2]          = RGBA(232, 16,         0, 255);
7907         inputColors[3]          = RGBA(16,      232,    0, 255);
7908
7909         outputColors[0]         = RGBA(64,      64,             0, 255);
7910         outputColors[1]         = RGBA(255, 255,        0, 255);
7911         outputColors[2]         = RGBA(255, 64,         0, 255);
7912         outputColors[3]         = RGBA(64,      255,    0, 255);
7913
7914         createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
7915         return testGroup.release();
7916 }
7917
7918 enum IntegerType
7919 {
7920         INTEGER_TYPE_SIGNED_16,
7921         INTEGER_TYPE_SIGNED_32,
7922         INTEGER_TYPE_SIGNED_64,
7923
7924         INTEGER_TYPE_UNSIGNED_16,
7925         INTEGER_TYPE_UNSIGNED_32,
7926         INTEGER_TYPE_UNSIGNED_64,
7927 };
7928
7929 const string getBitWidthStr (IntegerType type)
7930 {
7931         switch (type)
7932         {
7933                 case INTEGER_TYPE_SIGNED_16:
7934                 case INTEGER_TYPE_UNSIGNED_16:  return "16";
7935
7936                 case INTEGER_TYPE_SIGNED_32:
7937                 case INTEGER_TYPE_UNSIGNED_32:  return "32";
7938
7939                 case INTEGER_TYPE_SIGNED_64:
7940                 case INTEGER_TYPE_UNSIGNED_64:  return "64";
7941
7942                 default:                                                DE_ASSERT(false);
7943                                                                                 return "";
7944         }
7945 }
7946
7947 const string getByteWidthStr (IntegerType type)
7948 {
7949         switch (type)
7950         {
7951                 case INTEGER_TYPE_SIGNED_16:
7952                 case INTEGER_TYPE_UNSIGNED_16:  return "2";
7953
7954                 case INTEGER_TYPE_SIGNED_32:
7955                 case INTEGER_TYPE_UNSIGNED_32:  return "4";
7956
7957                 case INTEGER_TYPE_SIGNED_64:
7958                 case INTEGER_TYPE_UNSIGNED_64:  return "8";
7959
7960                 default:                                                DE_ASSERT(false);
7961                                                                                 return "";
7962         }
7963 }
7964
7965 bool isSigned (IntegerType type)
7966 {
7967         return (type <= INTEGER_TYPE_SIGNED_64);
7968 }
7969
7970 const string getTypeName (IntegerType type)
7971 {
7972         string prefix = isSigned(type) ? "" : "u";
7973         return prefix + "int" + getBitWidthStr(type);
7974 }
7975
7976 const string getTestName (IntegerType from, IntegerType to)
7977 {
7978         return getTypeName(from) + "_to_" + getTypeName(to);
7979 }
7980
7981 const string getAsmTypeDeclaration (IntegerType type)
7982 {
7983         string sign = isSigned(type) ? " 1" : " 0";
7984         return "OpTypeInt " + getBitWidthStr(type) + sign;
7985 }
7986
7987 template<typename T>
7988 BufferSp getSpecializedBuffer (deInt64 number)
7989 {
7990         return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
7991 }
7992
7993 BufferSp getBuffer (IntegerType type, deInt64 number)
7994 {
7995         switch (type)
7996         {
7997                 case INTEGER_TYPE_SIGNED_16:    return getSpecializedBuffer<deInt16>(number);
7998                 case INTEGER_TYPE_SIGNED_32:    return getSpecializedBuffer<deInt32>(number);
7999                 case INTEGER_TYPE_SIGNED_64:    return getSpecializedBuffer<deInt64>(number);
8000
8001                 case INTEGER_TYPE_UNSIGNED_16:  return getSpecializedBuffer<deUint16>(number);
8002                 case INTEGER_TYPE_UNSIGNED_32:  return getSpecializedBuffer<deUint32>(number);
8003                 case INTEGER_TYPE_UNSIGNED_64:  return getSpecializedBuffer<deUint64>(number);
8004
8005                 default:                                                DE_ASSERT(false);
8006                                                                                 return BufferSp(new Buffer<deInt32>(vector<deInt32>(1, 0)));
8007         }
8008 }
8009
8010 bool usesInt16 (IntegerType from, IntegerType to)
8011 {
8012         return (from == INTEGER_TYPE_SIGNED_16 || from == INTEGER_TYPE_UNSIGNED_16
8013                         || to == INTEGER_TYPE_SIGNED_16 || to == INTEGER_TYPE_UNSIGNED_16);
8014 }
8015
8016 bool usesInt64 (IntegerType from, IntegerType to)
8017 {
8018         return (from == INTEGER_TYPE_SIGNED_64 || from == INTEGER_TYPE_UNSIGNED_64
8019                         || to == INTEGER_TYPE_SIGNED_64 || to == INTEGER_TYPE_UNSIGNED_64);
8020 }
8021
8022 ConvertTestFeatures getUsedFeatures (IntegerType from, IntegerType to)
8023 {
8024         if (usesInt16(from, to))
8025         {
8026                 if (usesInt64(from, to))
8027                 {
8028                         return CONVERT_TEST_USES_INT16_INT64;
8029                 }
8030                 else
8031                 {
8032                         return CONVERT_TEST_USES_INT16;
8033                 }
8034         }
8035         else
8036         {
8037                 return CONVERT_TEST_USES_INT64;
8038         }
8039 }
8040
8041 struct ConvertCase
8042 {
8043         ConvertCase (IntegerType from, IntegerType to, deInt64 number)
8044         : m_fromType            (from)
8045         , m_toType                      (to)
8046         , m_features            (getUsedFeatures(from, to))
8047         , m_name                        (getTestName(from, to))
8048         , m_inputBuffer         (getBuffer(from, number))
8049         , m_outputBuffer        (getBuffer(to, number))
8050         {
8051                 m_asmTypes["inputType"]         = getAsmTypeDeclaration(from);
8052                 m_asmTypes["outputType"]        = getAsmTypeDeclaration(to);
8053
8054                 if (m_features == CONVERT_TEST_USES_INT16)
8055                 {
8056                         m_asmTypes["int_capabilities"] = "OpCapability Int16\n";
8057                 }
8058                 else if (m_features == CONVERT_TEST_USES_INT64)
8059                 {
8060                         m_asmTypes["int_capabilities"] = "OpCapability Int64\n";
8061                 }
8062                 else if (m_features == CONVERT_TEST_USES_INT16_INT64)
8063                 {
8064                         m_asmTypes["int_capabilities"] = string("OpCapability Int16\n") +
8065                                                                                                         "OpCapability Int64\n";
8066                 }
8067                 else
8068                 {
8069                         DE_ASSERT(false);
8070                 }
8071         }
8072
8073         IntegerType                             m_fromType;
8074         IntegerType                             m_toType;
8075         ConvertTestFeatures             m_features;
8076         string                                  m_name;
8077         map<string, string>             m_asmTypes;
8078         BufferSp                                m_inputBuffer;
8079         BufferSp                                m_outputBuffer;
8080 };
8081
8082 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
8083 {
8084         map<string, string> params = convertCase.m_asmTypes;
8085
8086         params["instruction"] = instruction;
8087
8088         params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
8089         params["outDecorator"] = getByteWidthStr(convertCase.m_toType);
8090
8091         const StringTemplate shader (
8092                 "OpCapability Shader\n"
8093                 "${int_capabilities}"
8094                 "OpMemoryModel Logical GLSL450\n"
8095                 "OpEntryPoint GLCompute %main \"main\" %id\n"
8096                 "OpExecutionMode %main LocalSize 1 1 1\n"
8097                 "OpSource GLSL 430\n"
8098                 "OpName %main           \"main\"\n"
8099                 "OpName %id             \"gl_GlobalInvocationID\"\n"
8100                 // Decorators
8101                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
8102                 "OpDecorate %indata DescriptorSet 0\n"
8103                 "OpDecorate %indata Binding 0\n"
8104                 "OpDecorate %outdata DescriptorSet 0\n"
8105                 "OpDecorate %outdata Binding 1\n"
8106                 "OpDecorate %in_arr ArrayStride ${inDecorator}\n"
8107                 "OpDecorate %out_arr ArrayStride ${outDecorator}\n"
8108                 "OpDecorate %in_buf BufferBlock\n"
8109                 "OpDecorate %out_buf BufferBlock\n"
8110                 "OpMemberDecorate %in_buf 0 Offset 0\n"
8111                 "OpMemberDecorate %out_buf 0 Offset 0\n"
8112                 // Base types
8113                 "%void       = OpTypeVoid\n"
8114                 "%voidf      = OpTypeFunction %void\n"
8115                 "%u32        = OpTypeInt 32 0\n"
8116                 "%i32        = OpTypeInt 32 1\n"
8117                 "%uvec3      = OpTypeVector %u32 3\n"
8118                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
8119                 // Custom types
8120                 "%in_type    = ${inputType}\n"
8121                 "%out_type   = ${outputType}\n"
8122                 // Derived types
8123                 "%in_ptr     = OpTypePointer Uniform %in_type\n"
8124                 "%out_ptr    = OpTypePointer Uniform %out_type\n"
8125                 "%in_arr     = OpTypeRuntimeArray %in_type\n"
8126                 "%out_arr    = OpTypeRuntimeArray %out_type\n"
8127                 "%in_buf     = OpTypeStruct %in_arr\n"
8128                 "%out_buf    = OpTypeStruct %out_arr\n"
8129                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
8130                 "%out_bufptr = OpTypePointer Uniform %out_buf\n"
8131                 "%indata     = OpVariable %in_bufptr Uniform\n"
8132                 "%outdata    = OpVariable %out_bufptr Uniform\n"
8133                 "%inputptr   = OpTypePointer Input %in_type\n"
8134                 "%id         = OpVariable %uvec3ptr Input\n"
8135                 // Constants
8136                 "%zero       = OpConstant %i32 0\n"
8137                 // Main function
8138                 "%main       = OpFunction %void None %voidf\n"
8139                 "%label      = OpLabel\n"
8140                 "%idval      = OpLoad %uvec3 %id\n"
8141                 "%x          = OpCompositeExtract %u32 %idval 0\n"
8142                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
8143                 "%outloc     = OpAccessChain %out_ptr %outdata %zero %x\n"
8144                 "%inval      = OpLoad %in_type %inloc\n"
8145                 "%conv       = ${instruction} %out_type %inval\n"
8146                 "              OpStore %outloc %conv\n"
8147                 "              OpReturn\n"
8148                 "              OpFunctionEnd\n"
8149         );
8150
8151         return shader.specialize(params);
8152 }
8153
8154 void createSConvertCases (vector<ConvertCase>& testCases)
8155 {
8156         // Convert int to int
8157         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_16, INTEGER_TYPE_SIGNED_32,         14669));
8158         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_16, INTEGER_TYPE_SIGNED_64,         3341));
8159
8160         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_32, INTEGER_TYPE_SIGNED_64,         973610259));
8161
8162         // Convert int to unsigned int
8163         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_16, INTEGER_TYPE_UNSIGNED_32,       9288));
8164         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_16, INTEGER_TYPE_UNSIGNED_64,       15460));
8165
8166         testCases.push_back(ConvertCase(INTEGER_TYPE_SIGNED_32, INTEGER_TYPE_UNSIGNED_64,       346213461));
8167 }
8168
8169 //  Test for the OpSConvert instruction.
8170 tcu::TestCaseGroup* createSConvertTests (tcu::TestContext& testCtx)
8171 {
8172         const string instruction                                ("OpSConvert");
8173         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "sconvert", "OpSConvert"));
8174         vector<ConvertCase>                             testCases;
8175         createSConvertCases(testCases);
8176
8177         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
8178         {
8179                 ComputeShaderSpec       spec;
8180
8181                 spec.assembly = getConvertCaseShaderStr(instruction, *test);
8182                 spec.inputs.push_back(test->m_inputBuffer);
8183                 spec.outputs.push_back(test->m_outputBuffer);
8184                 spec.numWorkGroups = IVec3(1, 1, 1);
8185
8186                 group->addChild(new ConvertTestCase(testCtx, test->m_name.c_str(), "Convert integers with OpSConvert.", spec, test->m_features));
8187         }
8188
8189         return group.release();
8190 }
8191
8192 void createUConvertCases (vector<ConvertCase>& testCases)
8193 {
8194         // Convert unsigned int to unsigned int
8195         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_16,       INTEGER_TYPE_UNSIGNED_32,       60653));
8196         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_16,       INTEGER_TYPE_UNSIGNED_64,       17991));
8197
8198         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_32,       INTEGER_TYPE_UNSIGNED_64,       904256275));
8199
8200         // Convert unsigned int to int
8201         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_16,       INTEGER_TYPE_SIGNED_32,         38002));
8202         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_16,       INTEGER_TYPE_SIGNED_64,         64921));
8203
8204         testCases.push_back(ConvertCase(INTEGER_TYPE_UNSIGNED_32,       INTEGER_TYPE_SIGNED_64,         4294956295ll));
8205 }
8206
8207 //  Test for the OpUConvert instruction.
8208 tcu::TestCaseGroup* createUConvertTests (tcu::TestContext& testCtx)
8209 {
8210         const string instruction                                ("OpUConvert");
8211         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "uconvert", "OpUConvert"));
8212         vector<ConvertCase>                             testCases;
8213         createUConvertCases(testCases);
8214
8215         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
8216         {
8217                 ComputeShaderSpec       spec;
8218
8219                 spec.assembly = getConvertCaseShaderStr(instruction, *test);
8220                 spec.inputs.push_back(test->m_inputBuffer);
8221                 spec.outputs.push_back(test->m_outputBuffer);
8222                 spec.numWorkGroups = IVec3(1, 1, 1);
8223
8224                 group->addChild(new ConvertTestCase(testCtx, test->m_name.c_str(), "Convert integers with OpUConvert.", spec, test->m_features));
8225         }
8226         return group.release();
8227 }
8228
8229 enum NumberType
8230 {
8231         TYPE_INT,
8232         TYPE_UINT,
8233         TYPE_FLOAT,
8234         TYPE_END,
8235 };
8236
8237 const string getNumberTypeName (const NumberType type)
8238 {
8239         if (type == TYPE_INT)
8240         {
8241                 return "int";
8242         }
8243         else if (type == TYPE_UINT)
8244         {
8245                 return "uint";
8246         }
8247         else if (type == TYPE_FLOAT)
8248         {
8249                 return "float";
8250         }
8251         else
8252         {
8253                 DE_ASSERT(false);
8254                 return "";
8255         }
8256 }
8257
8258 deInt32 getInt(de::Random& rnd)
8259 {
8260         return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
8261 }
8262
8263 template <typename T>
8264 const string numberToString (T number)
8265 {
8266         std::stringstream ss;
8267         ss << number;
8268         return ss.str();
8269 }
8270
8271 const string repeatString (const string& str, int times)
8272 {
8273         string filler;
8274         for (int i = 0; i < times; ++i)
8275         {
8276                 filler += str;
8277         }
8278         return filler;
8279 }
8280
8281 const string getRandomConstantString (const NumberType type, de::Random& rnd)
8282 {
8283         if (type == TYPE_INT)
8284         {
8285                 return numberToString<deInt32>(getInt(rnd));
8286         }
8287         else if (type == TYPE_UINT)
8288         {
8289                 return numberToString<deUint32>(rnd.getUint32());
8290         }
8291         else if (type == TYPE_FLOAT)
8292         {
8293                 return numberToString<float>(rnd.getFloat());
8294         }
8295         else
8296         {
8297                 DE_ASSERT(false);
8298                 return "";
8299         }
8300 }
8301
8302 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
8303 {
8304         map<string, string> params;
8305
8306         // Vec2 to Vec4
8307         for (int width = 2; width <= 4; ++width)
8308         {
8309                 string randomConst = numberToString(getInt(rnd));
8310                 string widthStr = numberToString(width);
8311                 int index = rnd.getInt(0, width-1);
8312
8313                 params["type"]                                  = "vec";
8314                 params["name"]                                  = params["type"] + "_" + widthStr;
8315                 params["compositeType"]                 = "%composite = OpTypeVector %custom " + widthStr +"\n";
8316                 params["filler"]                                = string("%filler    = OpConstant %custom ") + getRandomConstantString(type, rnd) + "\n";
8317                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
8318                 params["indexes"]                               = numberToString(index);
8319                 testCases.push_back(params);
8320         }
8321 }
8322
8323 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
8324 {
8325         const int limit = 10;
8326         map<string, string> params;
8327
8328         for (int width = 2; width <= limit; ++width)
8329         {
8330                 string randomConst = numberToString(getInt(rnd));
8331                 string widthStr = numberToString(width);
8332                 int index = rnd.getInt(0, width-1);
8333
8334                 params["type"]                                  = "array";
8335                 params["name"]                                  = params["type"] + "_" + widthStr;
8336                 params["compositeType"]                 = string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
8337                                                                                         +        "%composite = OpTypeArray %custom %arraywidth\n";
8338
8339                 params["filler"]                                = string("%filler    = OpConstant %custom ") + getRandomConstantString(type, rnd) + "\n";
8340                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
8341                 params["indexes"]                               = numberToString(index);
8342                 testCases.push_back(params);
8343         }
8344 }
8345
8346 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
8347 {
8348         const int limit = 10;
8349         map<string, string> params;
8350
8351         for (int width = 2; width <= limit; ++width)
8352         {
8353                 string randomConst = numberToString(getInt(rnd));
8354                 int index = rnd.getInt(0, width-1);
8355
8356                 params["type"]                                  = "struct";
8357                 params["name"]                                  = params["type"] + "_" + numberToString(width);
8358                 params["compositeType"]                 = "%composite = OpTypeStruct" + repeatString(" %custom", width) + "\n";
8359                 params["filler"]                                = string("%filler    = OpConstant %custom ") + getRandomConstantString(type, rnd) + "\n";
8360                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
8361                 params["indexes"]                               = numberToString(index);
8362                 testCases.push_back(params);
8363         }
8364 }
8365
8366 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
8367 {
8368         map<string, string> params;
8369
8370         // Vec2 to Vec4
8371         for (int width = 2; width <= 4; ++width)
8372         {
8373                 string widthStr = numberToString(width);
8374
8375                 for (int column = 2 ; column <= 4; ++column)
8376                 {
8377                         int index_0 = rnd.getInt(0, column-1);
8378                         int index_1 = rnd.getInt(0, width-1);
8379                         string columnStr = numberToString(column);
8380
8381                         params["type"]                                  = "matrix";
8382                         params["name"]                                  = params["type"] + "_" + widthStr + "x" + columnStr;
8383                         params["compositeType"]                 = string("%vectype   = OpTypeVector %custom " + widthStr + "\n")
8384                                                                                                 +        "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
8385
8386                         params["filler"]                                = string("%filler    = OpConstant %custom ") + getRandomConstantString(type, rnd) + "\n"
8387                                                                                                 +        "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
8388
8389                         params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
8390                         params["indexes"]                               = numberToString(index_0) + " " + numberToString(index_1);
8391                         testCases.push_back(params);
8392                 }
8393         }
8394 }
8395
8396 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
8397 {
8398         createVectorCompositeCases(testCases, rnd, type);
8399         createArrayCompositeCases(testCases, rnd, type);
8400         createStructCompositeCases(testCases, rnd, type);
8401         // Matrix only supports float types
8402         if (type == TYPE_FLOAT)
8403         {
8404                 createMatrixCompositeCases(testCases, rnd, type);
8405         }
8406 }
8407
8408 const string getAssemblyTypeDeclaration (const NumberType type)
8409 {
8410         switch (type)
8411         {
8412                 case TYPE_INT:          return "OpTypeInt 32 1";
8413                 case TYPE_UINT:         return "OpTypeInt 32 0";
8414                 case TYPE_FLOAT:        return "OpTypeFloat 32";
8415                 default:                        DE_ASSERT(false); return "";
8416         }
8417 }
8418
8419 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
8420 {
8421         map<string, string>     parameters(params);
8422
8423         parameters["typeDeclaration"] = getAssemblyTypeDeclaration(type);
8424
8425         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
8426
8427         return StringTemplate (
8428                 "OpCapability Shader\n"
8429                 "OpCapability Matrix\n"
8430                 "OpMemoryModel Logical GLSL450\n"
8431                 "OpEntryPoint GLCompute %main \"main\" %id\n"
8432                 "OpExecutionMode %main LocalSize 1 1 1\n"
8433
8434                 "OpSource GLSL 430\n"
8435                 "OpName %main           \"main\"\n"
8436                 "OpName %id             \"gl_GlobalInvocationID\"\n"
8437
8438                 // Decorators
8439                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
8440                 "OpDecorate %buf BufferBlock\n"
8441                 "OpDecorate %indata DescriptorSet 0\n"
8442                 "OpDecorate %indata Binding 0\n"
8443                 "OpDecorate %outdata DescriptorSet 0\n"
8444                 "OpDecorate %outdata Binding 1\n"
8445                 "OpDecorate %customarr ArrayStride 4\n"
8446                 "${compositeDecorator}"
8447                 "OpMemberDecorate %buf 0 Offset 0\n"
8448
8449                 // General types
8450                 "%void      = OpTypeVoid\n"
8451                 "%voidf     = OpTypeFunction %void\n"
8452                 "%u32       = OpTypeInt 32 0\n"
8453                 "%i32       = OpTypeInt 32 1\n"
8454                 "%uvec3     = OpTypeVector %u32 3\n"
8455                 "%uvec3ptr  = OpTypePointer Input %uvec3\n"
8456
8457                 // Custom type
8458                 "%custom    = ${typeDeclaration}\n"
8459                 "${compositeType}"
8460
8461                 // Constants
8462                 "${filler}"
8463
8464                 // Inherited from custom
8465                 "%customptr = OpTypePointer Uniform %custom\n"
8466                 "%customarr = OpTypeRuntimeArray %custom\n"
8467                 "%buf       = OpTypeStruct %customarr\n"
8468                 "%bufptr    = OpTypePointer Uniform %buf\n"
8469
8470                 "%indata    = OpVariable %bufptr Uniform\n"
8471                 "%outdata   = OpVariable %bufptr Uniform\n"
8472
8473                 "%id        = OpVariable %uvec3ptr Input\n"
8474                 "%zero      = OpConstant %i32 0\n"
8475
8476                 "%main      = OpFunction %void None %voidf\n"
8477                 "%label     = OpLabel\n"
8478                 "%idval     = OpLoad %uvec3 %id\n"
8479                 "%x         = OpCompositeExtract %u32 %idval 0\n"
8480
8481                 "%inloc     = OpAccessChain %customptr %indata %zero %x\n"
8482                 "%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
8483                 // Read the input value
8484                 "%inval     = OpLoad %custom %inloc\n"
8485                 // Create the composite and fill it
8486                 "${compositeConstruct}"
8487                 // Insert the input value to a place
8488                 "%instance2 = OpCompositeInsert %composite %inval %instance ${indexes}\n"
8489                 // Read back the value from the position
8490                 "%out_val   = OpCompositeExtract %custom %instance2 ${indexes}\n"
8491                 // Store it in the output position
8492                 "             OpStore %outloc %out_val\n"
8493                 "             OpReturn\n"
8494                 "             OpFunctionEnd\n"
8495         ).specialize(parameters);
8496 }
8497
8498 template<typename T>
8499 BufferSp createCompositeBuffer(T number)
8500 {
8501         return BufferSp(new Buffer<T>(vector<T>(1, number)));
8502 }
8503
8504 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
8505 {
8506         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
8507         de::Random                                              rnd             (deStringHash(group->getName()));
8508
8509         for (int type = TYPE_INT; type != TYPE_END; ++type)
8510         {
8511                 NumberType                                              numberType              = NumberType(type);
8512                 const string                                    typeName                = getNumberTypeName(numberType);
8513                 const string                                    description             = "Test the OpCompositeInsert instruction with " + typeName + "s";
8514                 de::MovePtr<tcu::TestCaseGroup> subGroup                (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
8515                 vector<map<string, string> >    testCases;
8516
8517                 createCompositeCases(testCases, rnd, numberType);
8518
8519                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
8520                 {
8521                         ComputeShaderSpec       spec;
8522
8523                         spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
8524
8525                         switch (numberType)
8526                         {
8527                                 case TYPE_INT:
8528                                 {
8529                                         deInt32 number = getInt(rnd);
8530                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
8531                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
8532                                         break;
8533                                 }
8534                                 case TYPE_UINT:
8535                                 {
8536                                         deUint32 number = rnd.getUint32();
8537                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
8538                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
8539                                         break;
8540                                 }
8541                                 case TYPE_FLOAT:
8542                                 {
8543                                         float number = rnd.getFloat();
8544                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
8545                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
8546                                         break;
8547                                 }
8548                                 default:
8549                                         DE_ASSERT(false);
8550                         }
8551
8552                         spec.numWorkGroups = IVec3(1, 1, 1);
8553                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
8554                 }
8555                 group->addChild(subGroup.release());
8556         }
8557         return group.release();
8558 }
8559
8560 struct AssemblyStructInfo
8561 {
8562         AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
8563         : components    (comp)
8564         , index                 (idx)
8565         {}
8566
8567         deUint32 components;
8568         deUint32 index;
8569 };
8570
8571 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
8572 {
8573         // Create the full index string
8574         string                          fullIndex       = numberToString(structInfo.index) + " " + params.at("indexes");
8575         // Convert it to list of indexes
8576         vector<string>          indexes         = de::splitString(fullIndex, ' ');
8577
8578         map<string, string>     parameters      (params);
8579         parameters["typeDeclaration"]   = getAssemblyTypeDeclaration(type);
8580         parameters["structType"]                = repeatString(" %composite", structInfo.components);
8581         parameters["structConstruct"]   = repeatString(" %instance", structInfo.components);
8582         parameters["insertIndexes"]             = fullIndex;
8583
8584         // In matrix cases the last two index is the CompositeExtract indexes
8585         const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
8586
8587         // Construct the extractIndex
8588         for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
8589         {
8590                 parameters["extractIndexes"] += " " + *index;
8591         }
8592
8593         // Remove the last 1 or 2 element depends on matrix case or not
8594         indexes.erase(indexes.end() - extractIndexes, indexes.end());
8595
8596         deUint32 id = 0;
8597         // Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
8598         for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
8599         {
8600                 string indexId = "%index_" + numberToString(id++);
8601                 parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
8602                 parameters["accessChainIndexes"] += " " + indexId;
8603         }
8604
8605         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
8606
8607         return StringTemplate (
8608                 "OpCapability Shader\n"
8609                 "OpCapability Matrix\n"
8610                 "OpMemoryModel Logical GLSL450\n"
8611                 "OpEntryPoint GLCompute %main \"main\" %id\n"
8612                 "OpExecutionMode %main LocalSize 1 1 1\n"
8613
8614                 "OpSource GLSL 430\n"
8615                 "OpName %main           \"main\"\n"
8616                 "OpName %id             \"gl_GlobalInvocationID\"\n"
8617                 // Decorators
8618                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
8619                 "OpDecorate %buf BufferBlock\n"
8620                 "OpDecorate %indata DescriptorSet 0\n"
8621                 "OpDecorate %indata Binding 0\n"
8622                 "OpDecorate %outdata DescriptorSet 0\n"
8623                 "OpDecorate %outdata Binding 1\n"
8624                 "OpDecorate %customarr ArrayStride 4\n"
8625                 "${compositeDecorator}"
8626                 "OpMemberDecorate %buf 0 Offset 0\n"
8627                 // General types
8628                 "%void      = OpTypeVoid\n"
8629                 "%voidf     = OpTypeFunction %void\n"
8630                 "%u32       = OpTypeInt 32 0\n"
8631                 "%uvec3     = OpTypeVector %u32 3\n"
8632                 "%uvec3ptr  = OpTypePointer Input %uvec3\n"
8633                 // Custom type
8634                 "%custom    = ${typeDeclaration}\n"
8635                 // Custom types
8636                 "${compositeType}"
8637                 // Inherited from composite
8638                 "%composite_p = OpTypePointer Function %composite\n"
8639                 "%struct_t  = OpTypeStruct${structType}\n"
8640                 "%struct_p  = OpTypePointer Function %struct_t\n"
8641                 // Constants
8642                 "${filler}"
8643                 "${accessChainConstDeclaration}"
8644                 // Inherited from custom
8645                 "%customptr = OpTypePointer Uniform %custom\n"
8646                 "%customarr = OpTypeRuntimeArray %custom\n"
8647                 "%buf       = OpTypeStruct %customarr\n"
8648                 "%bufptr    = OpTypePointer Uniform %buf\n"
8649                 "%indata    = OpVariable %bufptr Uniform\n"
8650                 "%outdata   = OpVariable %bufptr Uniform\n"
8651
8652                 "%id        = OpVariable %uvec3ptr Input\n"
8653                 "%zero      = OpConstant %u32 0\n"
8654                 "%main      = OpFunction %void None %voidf\n"
8655                 "%label     = OpLabel\n"
8656                 "%struct_v  = OpVariable %struct_p Function\n"
8657                 "%idval     = OpLoad %uvec3 %id\n"
8658                 "%x         = OpCompositeExtract %u32 %idval 0\n"
8659                 // Create the input/output type
8660                 "%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
8661                 "%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
8662                 // Read the input value
8663                 "%inval     = OpLoad %custom %inloc\n"
8664                 // Create the composite and fill it
8665                 "${compositeConstruct}"
8666                 // Create the struct and fill it with the composite
8667                 "%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
8668                 // Insert the value
8669                 "%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
8670                 // Store the object
8671                 "             OpStore %struct_v %comp_obj\n"
8672                 // Get deepest possible composite pointer
8673                 "%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
8674                 "%read_obj  = OpLoad %composite %inner_ptr\n"
8675                 // Read back the stored value
8676                 "%read_val  = OpCompositeExtract %custom %read_obj${extractIndexes}\n"
8677                 "             OpStore %outloc %read_val\n"
8678                 "             OpReturn\n"
8679                 "             OpFunctionEnd\n").specialize(parameters);
8680 }
8681
8682 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
8683 {
8684         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
8685         de::Random                                              rnd                             (deStringHash(group->getName()));
8686
8687         for (int type = TYPE_INT; type != TYPE_END; ++type)
8688         {
8689                 NumberType                                              numberType      = NumberType(type);
8690                 const string                                    typeName        = getNumberTypeName(numberType);
8691                 const string                                    description     = "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
8692                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
8693
8694                 vector<map<string, string> >    testCases;
8695                 createCompositeCases(testCases, rnd, numberType);
8696
8697                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
8698                 {
8699                         ComputeShaderSpec       spec;
8700
8701                         // Number of components inside of a struct
8702                         deUint32 structComponents = rnd.getInt(2, 8);
8703                         // Component index value
8704                         deUint32 structIndex = rnd.getInt(0, structComponents - 1);
8705                         AssemblyStructInfo structInfo(structComponents, structIndex);
8706
8707                         spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
8708
8709                         switch (numberType)
8710                         {
8711                                 case TYPE_INT:
8712                                 {
8713                                         deInt32 number = getInt(rnd);
8714                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
8715                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
8716                                         break;
8717                                 }
8718                                 case TYPE_UINT:
8719                                 {
8720                                         deUint32 number = rnd.getUint32();
8721                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
8722                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
8723                                         break;
8724                                 }
8725                                 case TYPE_FLOAT:
8726                                 {
8727                                         float number = rnd.getFloat();
8728                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
8729                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
8730                                         break;
8731                                 }
8732                                 default:
8733                                         DE_ASSERT(false);
8734                         }
8735                         spec.numWorkGroups = IVec3(1, 1, 1);
8736                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
8737                 }
8738                 group->addChild(subGroup.release());
8739         }
8740         return group.release();
8741 }
8742
8743 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
8744 {
8745         de::MovePtr<tcu::TestCaseGroup> instructionTests        (new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
8746         de::MovePtr<tcu::TestCaseGroup> computeTests            (new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
8747         de::MovePtr<tcu::TestCaseGroup> graphicsTests           (new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
8748
8749         computeTests->addChild(createOpNopGroup(testCtx));
8750         computeTests->addChild(createOpFUnordGroup(testCtx));
8751         computeTests->addChild(createOpAtomicGroup(testCtx));
8752         computeTests->addChild(createOpLineGroup(testCtx));
8753         computeTests->addChild(createOpNoLineGroup(testCtx));
8754         computeTests->addChild(createOpConstantNullGroup(testCtx));
8755         computeTests->addChild(createOpConstantCompositeGroup(testCtx));
8756         computeTests->addChild(createOpConstantUsageGroup(testCtx));
8757         computeTests->addChild(createSpecConstantGroup(testCtx));
8758         computeTests->addChild(createOpSourceGroup(testCtx));
8759         computeTests->addChild(createOpSourceExtensionGroup(testCtx));
8760         computeTests->addChild(createDecorationGroupGroup(testCtx));
8761         computeTests->addChild(createOpPhiGroup(testCtx));
8762         computeTests->addChild(createLoopControlGroup(testCtx));
8763         computeTests->addChild(createFunctionControlGroup(testCtx));
8764         computeTests->addChild(createSelectionControlGroup(testCtx));
8765         computeTests->addChild(createBlockOrderGroup(testCtx));
8766         computeTests->addChild(createMultipleShaderGroup(testCtx));
8767         computeTests->addChild(createMemoryAccessGroup(testCtx));
8768         computeTests->addChild(createOpCopyMemoryGroup(testCtx));
8769         computeTests->addChild(createOpCopyObjectGroup(testCtx));
8770         computeTests->addChild(createNoContractionGroup(testCtx));
8771         computeTests->addChild(createOpUndefGroup(testCtx));
8772         computeTests->addChild(createOpUnreachableGroup(testCtx));
8773         computeTests ->addChild(createOpQuantizeToF16Group(testCtx));
8774         computeTests ->addChild(createOpFRemGroup(testCtx));
8775         computeTests->addChild(createSConvertTests(testCtx));
8776         computeTests->addChild(createUConvertTests(testCtx));
8777         computeTests->addChild(createOpCompositeInsertGroup(testCtx));
8778         computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
8779
8780         RGBA defaultColors[4];
8781         getDefaultColors(defaultColors);
8782
8783         de::MovePtr<tcu::TestCaseGroup> opnopTests (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
8784         map<string, string> opNopFragments;
8785         opNopFragments["testfun"] =
8786                 "%test_code = OpFunction %v4f32 None %v4f32_function\n"
8787                 "%param1 = OpFunctionParameter %v4f32\n"
8788                 "%label_testfun = OpLabel\n"
8789                 "OpNop\n"
8790                 "OpNop\n"
8791                 "OpNop\n"
8792                 "OpNop\n"
8793                 "OpNop\n"
8794                 "OpNop\n"
8795                 "OpNop\n"
8796                 "OpNop\n"
8797                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8798                 "%b = OpFAdd %f32 %a %a\n"
8799                 "OpNop\n"
8800                 "%c = OpFSub %f32 %b %a\n"
8801                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
8802                 "OpNop\n"
8803                 "OpNop\n"
8804                 "OpReturnValue %ret\n"
8805                 "OpFunctionEnd\n"
8806                 ;
8807         createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, opnopTests.get());
8808
8809
8810         graphicsTests->addChild(opnopTests.release());
8811         graphicsTests->addChild(createOpSourceTests(testCtx));
8812         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
8813         graphicsTests->addChild(createOpLineTests(testCtx));
8814         graphicsTests->addChild(createOpNoLineTests(testCtx));
8815         graphicsTests->addChild(createOpConstantNullTests(testCtx));
8816         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
8817         graphicsTests->addChild(createMemoryAccessTests(testCtx));
8818         graphicsTests->addChild(createOpUndefTests(testCtx));
8819         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
8820         graphicsTests->addChild(createModuleTests(testCtx));
8821         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
8822         graphicsTests->addChild(createOpPhiTests(testCtx));
8823         graphicsTests->addChild(createNoContractionTests(testCtx));
8824         graphicsTests->addChild(createOpQuantizeTests(testCtx));
8825         graphicsTests->addChild(createLoopTests(testCtx));
8826         graphicsTests->addChild(createSpecConstantTests(testCtx));
8827         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
8828         graphicsTests->addChild(createBarrierTests(testCtx));
8829         graphicsTests->addChild(createDecorationGroupTests(testCtx));
8830         graphicsTests->addChild(createFRemTests(testCtx));
8831
8832         instructionTests->addChild(computeTests.release());
8833         instructionTests->addChild(graphicsTests.release());
8834
8835         return instructionTests.release();
8836 }
8837
8838 } // SpirVAssembly
8839 } // vkt