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