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