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