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