Merge vk-gl-cts/opengl-cts-4.6.0 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 "tcuFloatFormat.hpp"
31 #include "tcuRGBA.hpp"
32 #include "tcuStringTemplate.hpp"
33 #include "tcuTestLog.hpp"
34 #include "tcuVectorUtil.hpp"
35 #include "tcuInterval.hpp"
36
37 #include "vkDefs.hpp"
38 #include "vkDeviceUtil.hpp"
39 #include "vkMemUtil.hpp"
40 #include "vkPlatform.hpp"
41 #include "vkPrograms.hpp"
42 #include "vkQueryUtil.hpp"
43 #include "vkRef.hpp"
44 #include "vkRefUtil.hpp"
45 #include "vkStrUtil.hpp"
46 #include "vkTypeUtil.hpp"
47
48 #include "deStringUtil.hpp"
49 #include "deUniquePtr.hpp"
50 #include "deMath.h"
51 #include "tcuStringTemplate.hpp"
52
53 #include "vktSpvAsmCrossStageInterfaceTests.hpp"
54 #include "vktSpvAsm8bitStorageTests.hpp"
55 #include "vktSpvAsm16bitStorageTests.hpp"
56 #include "vktSpvAsmUboMatrixPaddingTests.hpp"
57 #include "vktSpvAsmConditionalBranchTests.hpp"
58 #include "vktSpvAsmIndexingTests.hpp"
59 #include "vktSpvAsmImageSamplerTests.hpp"
60 #include "vktSpvAsmComputeShaderCase.hpp"
61 #include "vktSpvAsmComputeShaderTestUtil.hpp"
62 #include "vktSpvAsmFloatControlsTests.hpp"
63 #include "vktSpvAsmGraphicsShaderTestUtil.hpp"
64 #include "vktSpvAsmVariablePointersTests.hpp"
65 #include "vktSpvAsmVariableInitTests.hpp"
66 #include "vktSpvAsmPointerParameterTests.hpp"
67 #include "vktSpvAsmSpirvVersionTests.hpp"
68 #include "vktTestCaseUtil.hpp"
69 #include "vktSpvAsmLoopDepLenTests.hpp"
70 #include "vktSpvAsmLoopDepInfTests.hpp"
71 #include "vktSpvAsmCompositeInsertTests.hpp"
72 #include "vktSpvAsmVaryingNameTests.hpp"
73 #include "vktSpvAsmWorkgroupMemoryTests.hpp"
74
75 #include <cmath>
76 #include <limits>
77 #include <map>
78 #include <string>
79 #include <sstream>
80 #include <utility>
81 #include <stack>
82
83 namespace vkt
84 {
85 namespace SpirVAssembly
86 {
87
88 namespace
89 {
90
91 using namespace vk;
92 using std::map;
93 using std::string;
94 using std::vector;
95 using tcu::IVec3;
96 using tcu::IVec4;
97 using tcu::RGBA;
98 using tcu::TestLog;
99 using tcu::TestStatus;
100 using tcu::Vec4;
101 using de::UniquePtr;
102 using tcu::StringTemplate;
103 using tcu::Vec4;
104
105 const bool TEST_WITH_NAN        = true;
106 const bool TEST_WITHOUT_NAN     = false;
107
108 template<typename T>
109 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, int offset = 0)
110 {
111         T* const typedPtr = (T*)dst;
112         for (int ndx = 0; ndx < numValues; ndx++)
113                 typedPtr[offset + ndx] = randomScalar<T>(rnd, minValue, maxValue);
114 }
115
116 // Filter is a function that returns true if a value should pass, false otherwise.
117 template<typename T, typename FilterT>
118 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, FilterT filter, int offset = 0)
119 {
120         T* const typedPtr = (T*)dst;
121         T value;
122         for (int ndx = 0; ndx < numValues; ndx++)
123         {
124                 do
125                         value = randomScalar<T>(rnd, minValue, maxValue);
126                 while (!filter(value));
127
128                 typedPtr[offset + ndx] = value;
129         }
130 }
131
132 // Gets a 64-bit integer with a more logarithmic distribution
133 deInt64 randomInt64LogDistributed (de::Random& rnd)
134 {
135         deInt64 val = rnd.getUint64();
136         val &= (1ull << rnd.getInt(1, 63)) - 1;
137         if (rnd.getBool())
138                 val = -val;
139         return val;
140 }
141
142 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues)
143 {
144         for (int ndx = 0; ndx < numValues; ndx++)
145                 dst[ndx] = randomInt64LogDistributed(rnd);
146 }
147
148 template<typename FilterT>
149 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues, FilterT filter)
150 {
151         for (int ndx = 0; ndx < numValues; ndx++)
152         {
153                 deInt64 value;
154                 do {
155                         value = randomInt64LogDistributed(rnd);
156                 } while (!filter(value));
157                 dst[ndx] = value;
158         }
159 }
160
161 inline bool filterNonNegative (const deInt64 value)
162 {
163         return value >= 0;
164 }
165
166 inline bool filterPositive (const deInt64 value)
167 {
168         return value > 0;
169 }
170
171 inline bool filterNotZero (const deInt64 value)
172 {
173         return value != 0;
174 }
175
176 static void floorAll (vector<float>& values)
177 {
178         for (size_t i = 0; i < values.size(); i++)
179                 values[i] = deFloatFloor(values[i]);
180 }
181
182 static void floorAll (vector<Vec4>& values)
183 {
184         for (size_t i = 0; i < values.size(); i++)
185                 values[i] = floor(values[i]);
186 }
187
188 struct CaseParameter
189 {
190         const char*             name;
191         string                  param;
192
193         CaseParameter   (const char* case_, const string& param_) : name(case_), param(param_) {}
194 };
195
196 // Assembly code used for testing LocalSize, OpNop, OpConstant{Null|Composite}, Op[No]Line, OpSource[Continued], OpSourceExtension, OpUndef is based on GLSL source code:
197 //
198 // #version 430
199 //
200 // layout(std140, set = 0, binding = 0) readonly buffer Input {
201 //   float elements[];
202 // } input_data;
203 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
204 //   float elements[];
205 // } output_data;
206 //
207 // layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
208 //
209 // void main() {
210 //   uint x = gl_GlobalInvocationID.x;
211 //   output_data.elements[x] = -input_data.elements[x];
212 // }
213
214 static string getAsmForLocalSizeTest(bool useLiteralLocalSize, bool useSpecConstantWorkgroupSize, IVec3 workGroupSize, deUint32 ndx)
215 {
216         std::ostringstream out;
217         out << getComputeAsmShaderPreambleWithoutLocalSize();
218
219         if (useLiteralLocalSize)
220         {
221                 out << "OpExecutionMode %main LocalSize "
222                         << workGroupSize.x() << " " << workGroupSize.y() << " " << workGroupSize.z() << "\n";
223         }
224
225         out << "OpSource GLSL 430\n"
226                 "OpName %main           \"main\"\n"
227                 "OpName %id             \"gl_GlobalInvocationID\"\n"
228                 "OpDecorate %id BuiltIn GlobalInvocationId\n";
229
230         if (useSpecConstantWorkgroupSize)
231         {
232                 out << "OpDecorate %spec_0 SpecId 100\n"
233                         << "OpDecorate %spec_1 SpecId 101\n"
234                         << "OpDecorate %spec_2 SpecId 102\n"
235                         << "OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize\n";
236         }
237
238         out << getComputeAsmInputOutputBufferTraits()
239                 << getComputeAsmCommonTypes()
240                 << getComputeAsmInputOutputBuffer()
241                 << "%id        = OpVariable %uvec3ptr Input\n"
242                 << "%zero      = OpConstant %i32 0 \n";
243
244         if (useSpecConstantWorkgroupSize)
245         {
246                 out     << "%spec_0   = OpSpecConstant %u32 "<< workGroupSize.x() << "\n"
247                         << "%spec_1   = OpSpecConstant %u32 "<< workGroupSize.y() << "\n"
248                         << "%spec_2   = OpSpecConstant %u32 "<< workGroupSize.z() << "\n"
249                         << "%gl_WorkGroupSize = OpSpecConstantComposite %uvec3 %spec_0 %spec_1 %spec_2\n";
250         }
251
252         out << "%main      = OpFunction %void None %voidf\n"
253                 << "%label     = OpLabel\n"
254                 << "%idval     = OpLoad %uvec3 %id\n"
255                 << "%ndx         = OpCompositeExtract %u32 %idval " << ndx << "\n"
256
257                         "%inloc     = OpAccessChain %f32ptr %indata %zero %ndx\n"
258                         "%inval     = OpLoad %f32 %inloc\n"
259                         "%neg       = OpFNegate %f32 %inval\n"
260                         "%outloc    = OpAccessChain %f32ptr %outdata %zero %ndx\n"
261                         "             OpStore %outloc %neg\n"
262                         "             OpReturn\n"
263                         "             OpFunctionEnd\n";
264         return out.str();
265 }
266
267 tcu::TestCaseGroup* createLocalSizeGroup (tcu::TestContext& testCtx)
268 {
269         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "localsize", ""));
270         ComputeShaderSpec                               spec;
271         de::Random                                              rnd                             (deStringHash(group->getName()));
272         const deUint32                                  numElements             = 64u;
273         vector<float>                                   positiveFloats  (numElements, 0);
274         vector<float>                                   negativeFloats  (numElements, 0);
275
276         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
277
278         for (size_t ndx = 0; ndx < numElements; ++ndx)
279                 negativeFloats[ndx] = -positiveFloats[ndx];
280
281         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
282         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
283
284         spec.numWorkGroups = IVec3(numElements, 1, 1);
285
286         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, 1), 0u);
287         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize", "", spec));
288
289         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, 1), 0u);
290         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize", "", spec));
291
292         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, 1), 0u);
293         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize", "", spec));
294
295         spec.numWorkGroups = IVec3(1, 1, 1);
296
297         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(numElements, 1, 1), 0u);
298         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_x", "", spec));
299
300         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(numElements, 1, 1), 0u);
301         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_x", "", spec));
302
303         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(numElements, 1, 1), 0u);
304         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_x", "", spec));
305
306         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, numElements, 1), 1u);
307         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_y", "", spec));
308
309         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, numElements, 1), 1u);
310         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_y", "", spec));
311
312         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, numElements, 1), 1u);
313         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_y", "", spec));
314
315         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, numElements), 2u);
316         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_z", "", spec));
317
318         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, numElements), 2u);
319         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_z", "", spec));
320
321         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, numElements), 2u);
322         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_z", "", spec));
323
324         return group.release();
325 }
326
327 tcu::TestCaseGroup* createOpNopGroup (tcu::TestContext& testCtx)
328 {
329         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnop", "Test the OpNop instruction"));
330         ComputeShaderSpec                               spec;
331         de::Random                                              rnd                             (deStringHash(group->getName()));
332         const int                                               numElements             = 100;
333         vector<float>                                   positiveFloats  (numElements, 0);
334         vector<float>                                   negativeFloats  (numElements, 0);
335
336         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
337
338         for (size_t ndx = 0; ndx < numElements; ++ndx)
339                 negativeFloats[ndx] = -positiveFloats[ndx];
340
341         spec.assembly =
342                 string(getComputeAsmShaderPreamble()) +
343
344                 "OpSource GLSL 430\n"
345                 "OpName %main           \"main\"\n"
346                 "OpName %id             \"gl_GlobalInvocationID\"\n"
347
348                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
349
350                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
351
352                 + string(getComputeAsmInputOutputBuffer()) +
353
354                 "%id        = OpVariable %uvec3ptr Input\n"
355                 "%zero      = OpConstant %i32 0\n"
356
357                 "%main      = OpFunction %void None %voidf\n"
358                 "%label     = OpLabel\n"
359                 "%idval     = OpLoad %uvec3 %id\n"
360                 "%x         = OpCompositeExtract %u32 %idval 0\n"
361
362                 "             OpNop\n" // Inside a function body
363
364                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
365                 "%inval     = OpLoad %f32 %inloc\n"
366                 "%neg       = OpFNegate %f32 %inval\n"
367                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
368                 "             OpStore %outloc %neg\n"
369                 "             OpReturn\n"
370                 "             OpFunctionEnd\n";
371         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
372         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
373         spec.numWorkGroups = IVec3(numElements, 1, 1);
374
375         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNop appearing at different places", spec));
376
377         return group.release();
378 }
379
380 template<bool nanSupported>
381 bool compareFUnord (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
382 {
383         if (outputAllocs.size() != 1)
384                 return false;
385
386         vector<deUint8> input1Bytes;
387         vector<deUint8> input2Bytes;
388         vector<deUint8> expectedBytes;
389
390         inputs[0].getBytes(input1Bytes);
391         inputs[1].getBytes(input2Bytes);
392         expectedOutputs[0].getBytes(expectedBytes);
393
394         const deInt32* const    expectedOutputAsInt             = reinterpret_cast<const deInt32*>(&expectedBytes.front());
395         const deInt32* const    outputAsInt                             = static_cast<const deInt32*>(outputAllocs[0]->getHostPtr());
396         const float* const              input1AsFloat                   = reinterpret_cast<const float*>(&input1Bytes.front());
397         const float* const              input2AsFloat                   = reinterpret_cast<const float*>(&input2Bytes.front());
398         bool returnValue                                                                = true;
399
400         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(deInt32); ++idx)
401         {
402                 if (!nanSupported && (tcu::Float32(input1AsFloat[idx]).isNaN() || tcu::Float32(input2AsFloat[idx]).isNaN()))
403                         continue;
404
405                 if (outputAsInt[idx] != expectedOutputAsInt[idx])
406                 {
407                         log << TestLog::Message << "ERROR: Sub-case failed. inputs: " << input1AsFloat[idx] << "," << input2AsFloat[idx] << " output: " << outputAsInt[idx]<< " expected output: " << expectedOutputAsInt[idx] << TestLog::EndMessage;
408                         returnValue = false;
409                 }
410         }
411         return returnValue;
412 }
413
414 typedef VkBool32 (*compareFuncType) (float, float);
415
416 struct OpFUnordCase
417 {
418         const char*             name;
419         const char*             opCode;
420         compareFuncType compareFunc;
421
422                                         OpFUnordCase                    (const char* _name, const char* _opCode, compareFuncType _compareFunc)
423                                                 : name                          (_name)
424                                                 , opCode                        (_opCode)
425                                                 , compareFunc           (_compareFunc) {}
426 };
427
428 #define ADD_OPFUNORD_CASE(NAME, OPCODE, OPERATOR) \
429 do { \
430         struct compare_##NAME { static VkBool32 compare(float x, float y) { return (x OPERATOR y) ? VK_TRUE : VK_FALSE; } }; \
431         cases.push_back(OpFUnordCase(#NAME, OPCODE, compare_##NAME::compare)); \
432 } while (deGetFalse())
433
434 tcu::TestCaseGroup* createOpFUnordGroup (tcu::TestContext& testCtx, const bool nanSupported)
435 {
436         const string                                    nan                             = nanSupported ? "_nan" : "";
437         const string                                    groupName               = "opfunord" + nan;
438         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpFUnord* opcodes"));
439         de::Random                                              rnd                             (deStringHash(group->getName()));
440         const int                                               numElements             = 100;
441         vector<OpFUnordCase>                    cases;
442         string                                                  extensions              = nanSupported ? "OpExtension \"SPV_KHR_float_controls\"\n" : "";
443         string                                                  capabilities    = nanSupported ? "OpCapability SignedZeroInfNanPreserve\n" : "";
444         string                          exeModes        = nanSupported ? "OpExecutionMode %main SignedZeroInfNanPreserve 32\n" : "";
445         const StringTemplate                    shaderTemplate  (
446                 string(getComputeAsmShaderPreamble(capabilities, extensions, exeModes)) +
447                 "OpSource GLSL 430\n"
448                 "OpName %main           \"main\"\n"
449                 "OpName %id             \"gl_GlobalInvocationID\"\n"
450
451                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
452
453                 "OpDecorate %buf BufferBlock\n"
454                 "OpDecorate %buf2 BufferBlock\n"
455                 "OpDecorate %indata1 DescriptorSet 0\n"
456                 "OpDecorate %indata1 Binding 0\n"
457                 "OpDecorate %indata2 DescriptorSet 0\n"
458                 "OpDecorate %indata2 Binding 1\n"
459                 "OpDecorate %outdata DescriptorSet 0\n"
460                 "OpDecorate %outdata Binding 2\n"
461                 "OpDecorate %f32arr ArrayStride 4\n"
462                 "OpDecorate %i32arr ArrayStride 4\n"
463                 "OpMemberDecorate %buf 0 Offset 0\n"
464                 "OpMemberDecorate %buf2 0 Offset 0\n"
465
466                 + string(getComputeAsmCommonTypes()) +
467
468                 "%buf        = OpTypeStruct %f32arr\n"
469                 "%bufptr     = OpTypePointer Uniform %buf\n"
470                 "%indata1    = OpVariable %bufptr Uniform\n"
471                 "%indata2    = OpVariable %bufptr Uniform\n"
472
473                 "%buf2       = OpTypeStruct %i32arr\n"
474                 "%buf2ptr    = OpTypePointer Uniform %buf2\n"
475                 "%outdata    = OpVariable %buf2ptr Uniform\n"
476
477                 "%id        = OpVariable %uvec3ptr Input\n"
478                 "%zero      = OpConstant %i32 0\n"
479                 "%consti1   = OpConstant %i32 1\n"
480                 "%constf1   = OpConstant %f32 1.0\n"
481
482                 "%main      = OpFunction %void None %voidf\n"
483                 "%label     = OpLabel\n"
484                 "%idval     = OpLoad %uvec3 %id\n"
485                 "%x         = OpCompositeExtract %u32 %idval 0\n"
486
487                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
488                 "%inval1    = OpLoad %f32 %inloc1\n"
489                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
490                 "%inval2    = OpLoad %f32 %inloc2\n"
491                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
492
493                 "%result    = ${OPCODE} %bool %inval1 %inval2\n"
494                 "%int_res   = OpSelect %i32 %result %consti1 %zero\n"
495                 "             OpStore %outloc %int_res\n"
496
497                 "             OpReturn\n"
498                 "             OpFunctionEnd\n");
499
500         ADD_OPFUNORD_CASE(equal, "OpFUnordEqual", ==);
501         ADD_OPFUNORD_CASE(less, "OpFUnordLessThan", <);
502         ADD_OPFUNORD_CASE(lessequal, "OpFUnordLessThanEqual", <=);
503         ADD_OPFUNORD_CASE(greater, "OpFUnordGreaterThan", >);
504         ADD_OPFUNORD_CASE(greaterequal, "OpFUnordGreaterThanEqual", >=);
505         ADD_OPFUNORD_CASE(notequal, "OpFUnordNotEqual", !=);
506
507         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
508         {
509                 map<string, string>                     specializations;
510                 ComputeShaderSpec                       spec;
511                 const float                                     NaN                             = std::numeric_limits<float>::quiet_NaN();
512                 vector<float>                           inputFloats1    (numElements, 0);
513                 vector<float>                           inputFloats2    (numElements, 0);
514                 vector<deInt32>                         expectedInts    (numElements, 0);
515
516                 specializations["OPCODE"]       = cases[caseNdx].opCode;
517                 spec.assembly                           = shaderTemplate.specialize(specializations);
518
519                 fillRandomScalars(rnd, 1.f, 100.f, &inputFloats1[0], numElements);
520                 for (size_t ndx = 0; ndx < numElements; ++ndx)
521                 {
522                         switch (ndx % 6)
523                         {
524                                 case 0:         inputFloats2[ndx] = inputFloats1[ndx] + 1.0f; break;
525                                 case 1:         inputFloats2[ndx] = inputFloats1[ndx] - 1.0f; break;
526                                 case 2:         inputFloats2[ndx] = inputFloats1[ndx]; break;
527                                 case 3:         inputFloats2[ndx] = NaN; break;
528                                 case 4:         inputFloats2[ndx] = inputFloats1[ndx];  inputFloats1[ndx] = NaN; break;
529                                 case 5:         inputFloats2[ndx] = NaN;                                inputFloats1[ndx] = NaN; break;
530                         }
531                         expectedInts[ndx] = tcu::Float32(inputFloats1[ndx]).isNaN() || tcu::Float32(inputFloats2[ndx]).isNaN() || cases[caseNdx].compareFunc(inputFloats1[ndx], inputFloats2[ndx]);
532                 }
533
534                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
535                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
536                 spec.outputs.push_back(BufferSp(new Int32Buffer(expectedInts)));
537                 spec.numWorkGroups = IVec3(numElements, 1, 1);
538                 spec.verifyIO = nanSupported ? &compareFUnord<true> : &compareFUnord<false>;
539                 if (nanSupported)
540                 {
541                         spec.extensions.push_back("VK_KHR_shader_float_controls");
542                         spec.requestedVulkanFeatures.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat32 = DE_TRUE;
543                 }
544                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
545         }
546
547         return group.release();
548 }
549
550 struct OpAtomicCase
551 {
552         const char*             name;
553         const char*             assembly;
554         const char*             retValAssembly;
555         OpAtomicType    opAtomic;
556         deInt32                 numOutputElements;
557
558                                         OpAtomicCase(const char* _name, const char* _assembly, const char* _retValAssembly, OpAtomicType _opAtomic, deInt32 _numOutputElements)
559                                                 : name                          (_name)
560                                                 , assembly                      (_assembly)
561                                                 , retValAssembly        (_retValAssembly)
562                                                 , opAtomic                      (_opAtomic)
563                                                 , numOutputElements     (_numOutputElements) {}
564 };
565
566 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx, bool useStorageBuffer, int numElements = 65535, bool verifyReturnValues = false)
567 {
568         std::string                                             groupName                       ("opatomic");
569         if (useStorageBuffer)
570                 groupName += "_storage_buffer";
571         if (verifyReturnValues)
572                 groupName += "_return_values";
573         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpAtomic* opcodes"));
574         vector<OpAtomicCase>                    cases;
575
576         const StringTemplate                    shaderTemplate  (
577
578                 string("OpCapability Shader\n") +
579                 (useStorageBuffer ? "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n" : "") +
580                 "OpMemoryModel Logical GLSL450\n"
581                 "OpEntryPoint GLCompute %main \"main\" %id\n"
582                 "OpExecutionMode %main LocalSize 1 1 1\n" +
583
584                 "OpSource GLSL 430\n"
585                 "OpName %main           \"main\"\n"
586                 "OpName %id             \"gl_GlobalInvocationID\"\n"
587
588                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
589
590                 "OpDecorate %buf ${BLOCK_DECORATION}\n"
591                 "OpDecorate %indata DescriptorSet 0\n"
592                 "OpDecorate %indata Binding 0\n"
593                 "OpDecorate %i32arr ArrayStride 4\n"
594                 "OpMemberDecorate %buf 0 Offset 0\n"
595
596                 "OpDecorate %sumbuf ${BLOCK_DECORATION}\n"
597                 "OpDecorate %sum DescriptorSet 0\n"
598                 "OpDecorate %sum Binding 1\n"
599                 "OpMemberDecorate %sumbuf 0 Coherent\n"
600                 "OpMemberDecorate %sumbuf 0 Offset 0\n"
601
602                 "${RETVAL_BUF_DECORATE}"
603
604                 + getComputeAsmCommonTypes("${BLOCK_POINTER_TYPE}") +
605
606                 "%buf       = OpTypeStruct %i32arr\n"
607                 "%bufptr    = OpTypePointer ${BLOCK_POINTER_TYPE} %buf\n"
608                 "%indata    = OpVariable %bufptr ${BLOCK_POINTER_TYPE}\n"
609
610                 "%sumbuf    = OpTypeStruct %i32arr\n"
611                 "%sumbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %sumbuf\n"
612                 "%sum       = OpVariable %sumbufptr ${BLOCK_POINTER_TYPE}\n"
613
614                 "${RETVAL_BUF_DECL}"
615
616                 "%id        = OpVariable %uvec3ptr Input\n"
617                 "%minusone  = OpConstant %i32 -1\n"
618                 "%zero      = OpConstant %i32 0\n"
619                 "%one       = OpConstant %u32 1\n"
620                 "%two       = OpConstant %i32 2\n"
621
622                 "%main      = OpFunction %void None %voidf\n"
623                 "%label     = OpLabel\n"
624                 "%idval     = OpLoad %uvec3 %id\n"
625                 "%x         = OpCompositeExtract %u32 %idval 0\n"
626
627                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
628                 "%inval     = OpLoad %i32 %inloc\n"
629
630                 "%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
631                 "${INSTRUCTION}"
632                 "${RETVAL_ASSEMBLY}"
633
634                 "             OpReturn\n"
635                 "             OpFunctionEnd\n");
636
637         #define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS) \
638         do { \
639                 DE_ASSERT((NUM_OUTPUT_ELEMENTS) == 1 || (NUM_OUTPUT_ELEMENTS) == numElements); \
640                 cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS)); \
641         } while (deGetFalse())
642         #define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, 1)
643         #define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, numElements)
644
645         ADD_OPATOMIC_CASE_1(iadd,       "%retv      = OpAtomicIAdd %i32 %outloc %one %zero %inval\n",
646                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IADD );
647         ADD_OPATOMIC_CASE_1(isub,       "%retv      = OpAtomicISub %i32 %outloc %one %zero %inval\n",
648                                                                 "             OpStore %retloc %retv\n", OPATOMIC_ISUB );
649         ADD_OPATOMIC_CASE_1(iinc,       "%retv      = OpAtomicIIncrement %i32 %outloc %one %zero\n",
650                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IINC );
651         ADD_OPATOMIC_CASE_1(idec,       "%retv      = OpAtomicIDecrement %i32 %outloc %one %zero\n",
652                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IDEC );
653         if (!verifyReturnValues)
654         {
655                 ADD_OPATOMIC_CASE_N(load,       "%inval2    = OpAtomicLoad %i32 %inloc %one %zero\n"
656                                                                         "             OpStore %outloc %inval2\n", "", OPATOMIC_LOAD );
657                 ADD_OPATOMIC_CASE_N(store,      "             OpAtomicStore %outloc %one %zero %inval\n", "", OPATOMIC_STORE );
658         }
659
660         ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
661                                                                 "             OpStore %outloc %even\n"
662                                                                 "%retv      = OpAtomicCompareExchange %i32 %outloc %one %zero %zero %minusone %zero\n",
663                                                                 "                         OpStore %retloc %retv\n", OPATOMIC_COMPEX );
664
665
666         #undef ADD_OPATOMIC_CASE
667         #undef ADD_OPATOMIC_CASE_1
668         #undef ADD_OPATOMIC_CASE_N
669
670         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
671         {
672                 map<string, string>                     specializations;
673                 ComputeShaderSpec                       spec;
674                 vector<deInt32>                         inputInts               (numElements, 0);
675                 vector<deInt32>                         expected                (cases[caseNdx].numOutputElements, -1);
676
677                 specializations["INDEX"]                                = (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
678                 specializations["INSTRUCTION"]                  = cases[caseNdx].assembly;
679                 specializations["BLOCK_DECORATION"]             = useStorageBuffer ? "Block" : "BufferBlock";
680                 specializations["BLOCK_POINTER_TYPE"]   = useStorageBuffer ? "StorageBuffer" : "Uniform";
681
682                 if (verifyReturnValues)
683                 {
684                         const StringTemplate blockDecoration    (
685                                 "\n"
686                                 "OpDecorate %retbuf ${BLOCK_DECORATION}\n"
687                                 "OpDecorate %ret DescriptorSet 0\n"
688                                 "OpDecorate %ret Binding 2\n"
689                                 "OpMemberDecorate %retbuf 0 Offset 0\n\n");
690
691                         const StringTemplate blockDeclaration   (
692                                 "\n"
693                                 "%retbuf    = OpTypeStruct %i32arr\n"
694                                 "%retbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %retbuf\n"
695                                 "%ret       = OpVariable %retbufptr ${BLOCK_POINTER_TYPE}\n\n");
696
697                         specializations["RETVAL_ASSEMBLY"] =
698                                 "%retloc    = OpAccessChain %i32ptr %ret %zero %x\n"
699                                 + std::string(cases[caseNdx].retValAssembly);
700
701                         specializations["RETVAL_BUF_DECORATE"]  = blockDecoration.specialize(specializations);
702                         specializations["RETVAL_BUF_DECL"]              = blockDeclaration.specialize(specializations);
703                 }
704                 else
705                 {
706                         specializations["RETVAL_ASSEMBLY"]              = "";
707                         specializations["RETVAL_BUF_DECORATE"]  = "";
708                         specializations["RETVAL_BUF_DECL"]              = "";
709                 }
710
711                 spec.assembly                                                   = shaderTemplate.specialize(specializations);
712
713                 if (useStorageBuffer)
714                         spec.extensions.push_back("VK_KHR_storage_buffer_storage_class");
715
716                 spec.inputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_INPUT)));
717                 spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_EXPECTED)));
718                 if (verifyReturnValues)
719                         spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_ATOMIC_RET)));
720                 spec.numWorkGroups = IVec3(numElements, 1, 1);
721
722                 if (verifyReturnValues)
723                 {
724                         switch (cases[caseNdx].opAtomic)
725                         {
726                                 case OPATOMIC_IADD:
727                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IADD>;
728                                         break;
729                                 case OPATOMIC_ISUB:
730                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_ISUB>;
731                                         break;
732                                 case OPATOMIC_IINC:
733                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IINC>;
734                                         break;
735                                 case OPATOMIC_IDEC:
736                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IDEC>;
737                                         break;
738                                 case OPATOMIC_COMPEX:
739                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_COMPEX>;
740                                         break;
741                                 default:
742                                         DE_FATAL("Unsupported OpAtomic type for return value verification");
743                         }
744                 }
745                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
746         }
747
748         return group.release();
749 }
750
751 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
752 {
753         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
754         ComputeShaderSpec                               spec;
755         de::Random                                              rnd                             (deStringHash(group->getName()));
756         const int                                               numElements             = 100;
757         vector<float>                                   positiveFloats  (numElements, 0);
758         vector<float>                                   negativeFloats  (numElements, 0);
759
760         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
761
762         for (size_t ndx = 0; ndx < numElements; ++ndx)
763                 negativeFloats[ndx] = -positiveFloats[ndx];
764
765         spec.assembly =
766                 string(getComputeAsmShaderPreamble()) +
767
768                 "%fname1 = OpString \"negateInputs.comp\"\n"
769                 "%fname2 = OpString \"negateInputs\"\n"
770
771                 "OpSource GLSL 430\n"
772                 "OpName %main           \"main\"\n"
773                 "OpName %id             \"gl_GlobalInvocationID\"\n"
774
775                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
776
777                 + string(getComputeAsmInputOutputBufferTraits()) +
778
779                 "OpLine %fname1 0 0\n" // At the earliest possible position
780
781                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
782
783                 "OpLine %fname1 0 1\n" // Multiple OpLines in sequence
784                 "OpLine %fname2 1 0\n" // Different filenames
785                 "OpLine %fname1 1000 100000\n"
786
787                 "%id        = OpVariable %uvec3ptr Input\n"
788                 "%zero      = OpConstant %i32 0\n"
789
790                 "OpLine %fname1 1 1\n" // Before a function
791
792                 "%main      = OpFunction %void None %voidf\n"
793                 "%label     = OpLabel\n"
794
795                 "OpLine %fname1 1 1\n" // In a function
796
797                 "%idval     = OpLoad %uvec3 %id\n"
798                 "%x         = OpCompositeExtract %u32 %idval 0\n"
799                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
800                 "%inval     = OpLoad %f32 %inloc\n"
801                 "%neg       = OpFNegate %f32 %inval\n"
802                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
803                 "             OpStore %outloc %neg\n"
804                 "             OpReturn\n"
805                 "             OpFunctionEnd\n";
806         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
807         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
808         spec.numWorkGroups = IVec3(numElements, 1, 1);
809
810         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
811
812         return group.release();
813 }
814
815 bool veryfiBinaryShader (const ProgramBinary& binary)
816 {
817         const size_t    paternCount                     = 3u;
818         bool paternsCheck[paternCount]          =
819         {
820                 false, false, false
821         };
822         const string patersns[paternCount]      =
823         {
824                 "VULKAN CTS",
825                 "Negative values",
826                 "Date: 2017/09/21"
827         };
828         size_t                  paternNdx               = 0u;
829
830         for (size_t ndx = 0u; ndx < binary.getSize(); ++ndx)
831         {
832                 if (false == paternsCheck[paternNdx] &&
833                         patersns[paternNdx][0] == static_cast<char>(binary.getBinary()[ndx]) &&
834                         deMemoryEqual((const char*)&binary.getBinary()[ndx], &patersns[paternNdx][0], patersns[paternNdx].length()))
835                 {
836                         paternsCheck[paternNdx]= true;
837                         paternNdx++;
838                         if (paternNdx == paternCount)
839                                 break;
840                 }
841         }
842
843         for (size_t ndx = 0u; ndx < paternCount; ++ndx)
844         {
845                 if (!paternsCheck[ndx])
846                         return false;
847         }
848
849         return true;
850 }
851
852 tcu::TestCaseGroup* createOpModuleProcessedGroup (tcu::TestContext& testCtx)
853 {
854         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "Test the OpModuleProcessed instruction"));
855         ComputeShaderSpec                               spec;
856         de::Random                                              rnd                             (deStringHash(group->getName()));
857         const int                                               numElements             = 10;
858         vector<float>                                   positiveFloats  (numElements, 0);
859         vector<float>                                   negativeFloats  (numElements, 0);
860
861         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
862
863         for (size_t ndx = 0; ndx < numElements; ++ndx)
864                 negativeFloats[ndx] = -positiveFloats[ndx];
865
866         spec.assembly =
867                 string(getComputeAsmShaderPreamble()) +
868                 "%fname = OpString \"negateInputs.comp\"\n"
869
870                 "OpSource GLSL 430\n"
871                 "OpName %main           \"main\"\n"
872                 "OpName %id             \"gl_GlobalInvocationID\"\n"
873                 "OpModuleProcessed \"VULKAN CTS\"\n"                                    //OpModuleProcessed;
874                 "OpModuleProcessed \"Negative values\"\n"
875                 "OpModuleProcessed \"Date: 2017/09/21\"\n"
876                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
877
878                 + string(getComputeAsmInputOutputBufferTraits())
879
880                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
881
882                 "OpLine %fname 0 1\n"
883
884                 "OpLine %fname 1000 1\n"
885
886                 "%id        = OpVariable %uvec3ptr Input\n"
887                 "%zero      = OpConstant %i32 0\n"
888                 "%main      = OpFunction %void None %voidf\n"
889
890                 "%label     = OpLabel\n"
891                 "%idval     = OpLoad %uvec3 %id\n"
892                 "%x         = OpCompositeExtract %u32 %idval 0\n"
893
894                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
895                 "%inval     = OpLoad %f32 %inloc\n"
896                 "%neg       = OpFNegate %f32 %inval\n"
897                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
898                 "             OpStore %outloc %neg\n"
899                 "             OpReturn\n"
900                 "             OpFunctionEnd\n";
901         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
902         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
903         spec.numWorkGroups = IVec3(numElements, 1, 1);
904         spec.verifyBinary = veryfiBinaryShader;
905         spec.spirvVersion = SPIRV_VERSION_1_3;
906
907         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpModuleProcessed Tests", spec));
908
909         return group.release();
910 }
911
912 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
913 {
914         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
915         ComputeShaderSpec                               spec;
916         de::Random                                              rnd                             (deStringHash(group->getName()));
917         const int                                               numElements             = 100;
918         vector<float>                                   positiveFloats  (numElements, 0);
919         vector<float>                                   negativeFloats  (numElements, 0);
920
921         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
922
923         for (size_t ndx = 0; ndx < numElements; ++ndx)
924                 negativeFloats[ndx] = -positiveFloats[ndx];
925
926         spec.assembly =
927                 string(getComputeAsmShaderPreamble()) +
928
929                 "%fname = OpString \"negateInputs.comp\"\n"
930
931                 "OpSource GLSL 430\n"
932                 "OpName %main           \"main\"\n"
933                 "OpName %id             \"gl_GlobalInvocationID\"\n"
934
935                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
936
937                 + string(getComputeAsmInputOutputBufferTraits()) +
938
939                 "OpNoLine\n" // At the earliest possible position, without preceding OpLine
940
941                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
942
943                 "OpLine %fname 0 1\n"
944                 "OpNoLine\n" // Immediately following a preceding OpLine
945
946                 "OpLine %fname 1000 1\n"
947
948                 "%id        = OpVariable %uvec3ptr Input\n"
949                 "%zero      = OpConstant %i32 0\n"
950
951                 "OpNoLine\n" // Contents after the previous OpLine
952
953                 "%main      = OpFunction %void None %voidf\n"
954                 "%label     = OpLabel\n"
955                 "%idval     = OpLoad %uvec3 %id\n"
956                 "%x         = OpCompositeExtract %u32 %idval 0\n"
957
958                 "OpNoLine\n" // Multiple OpNoLine
959                 "OpNoLine\n"
960                 "OpNoLine\n"
961
962                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
963                 "%inval     = OpLoad %f32 %inloc\n"
964                 "%neg       = OpFNegate %f32 %inval\n"
965                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
966                 "             OpStore %outloc %neg\n"
967                 "             OpReturn\n"
968                 "             OpFunctionEnd\n";
969         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
970         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
971         spec.numWorkGroups = IVec3(numElements, 1, 1);
972
973         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
974
975         return group.release();
976 }
977
978 // Compare instruction for the contraction compute case.
979 // Returns true if the output is what is expected from the test case.
980 bool compareNoContractCase(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
981 {
982         if (outputAllocs.size() != 1)
983                 return false;
984
985         // Only size is needed because we are not comparing the exact values.
986         size_t byteSize = expectedOutputs[0].getByteSize();
987
988         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
989
990         for(size_t i = 0; i < byteSize / sizeof(float); ++i) {
991                 if (outputAsFloat[i] != 0.f &&
992                         outputAsFloat[i] != -ldexp(1, -24)) {
993                         return false;
994                 }
995         }
996
997         return true;
998 }
999
1000 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
1001 {
1002         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
1003         vector<CaseParameter>                   cases;
1004         const int                                               numElements             = 100;
1005         vector<float>                                   inputFloats1    (numElements, 0);
1006         vector<float>                                   inputFloats2    (numElements, 0);
1007         vector<float>                                   outputFloats    (numElements, 0);
1008         const StringTemplate                    shaderTemplate  (
1009                 string(getComputeAsmShaderPreamble()) +
1010
1011                 "OpName %main           \"main\"\n"
1012                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1013
1014                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1015
1016                 "${DECORATION}\n"
1017
1018                 "OpDecorate %buf BufferBlock\n"
1019                 "OpDecorate %indata1 DescriptorSet 0\n"
1020                 "OpDecorate %indata1 Binding 0\n"
1021                 "OpDecorate %indata2 DescriptorSet 0\n"
1022                 "OpDecorate %indata2 Binding 1\n"
1023                 "OpDecorate %outdata DescriptorSet 0\n"
1024                 "OpDecorate %outdata Binding 2\n"
1025                 "OpDecorate %f32arr ArrayStride 4\n"
1026                 "OpMemberDecorate %buf 0 Offset 0\n"
1027
1028                 + string(getComputeAsmCommonTypes()) +
1029
1030                 "%buf        = OpTypeStruct %f32arr\n"
1031                 "%bufptr     = OpTypePointer Uniform %buf\n"
1032                 "%indata1    = OpVariable %bufptr Uniform\n"
1033                 "%indata2    = OpVariable %bufptr Uniform\n"
1034                 "%outdata    = OpVariable %bufptr Uniform\n"
1035
1036                 "%id         = OpVariable %uvec3ptr Input\n"
1037                 "%zero       = OpConstant %i32 0\n"
1038                 "%c_f_m1     = OpConstant %f32 -1.\n"
1039
1040                 "%main       = OpFunction %void None %voidf\n"
1041                 "%label      = OpLabel\n"
1042                 "%idval      = OpLoad %uvec3 %id\n"
1043                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1044                 "%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
1045                 "%inval1     = OpLoad %f32 %inloc1\n"
1046                 "%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
1047                 "%inval2     = OpLoad %f32 %inloc2\n"
1048                 "%mul        = OpFMul %f32 %inval1 %inval2\n"
1049                 "%add        = OpFAdd %f32 %mul %c_f_m1\n"
1050                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
1051                 "              OpStore %outloc %add\n"
1052                 "              OpReturn\n"
1053                 "              OpFunctionEnd\n");
1054
1055         cases.push_back(CaseParameter("multiplication", "OpDecorate %mul NoContraction"));
1056         cases.push_back(CaseParameter("addition",               "OpDecorate %add NoContraction"));
1057         cases.push_back(CaseParameter("both",                   "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
1058
1059         for (size_t ndx = 0; ndx < numElements; ++ndx)
1060         {
1061                 inputFloats1[ndx]       = 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
1062                 inputFloats2[ndx]       = 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
1063                 // Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
1064                 // conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
1065                 // So the final result will be 0.f or 0x1p-24.
1066                 // If the operation is combined into a precise fused multiply-add, then the result would be
1067                 // 2^-46 (0xa8800000).
1068                 outputFloats[ndx]       = 0.f;
1069         }
1070
1071         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
1072         {
1073                 map<string, string>             specializations;
1074                 ComputeShaderSpec               spec;
1075
1076                 specializations["DECORATION"] = cases[caseNdx].param;
1077                 spec.assembly = shaderTemplate.specialize(specializations);
1078                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1079                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1080                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1081                 spec.numWorkGroups = IVec3(numElements, 1, 1);
1082                 // Check against the two possible answers based on rounding mode.
1083                 spec.verifyIO = &compareNoContractCase;
1084
1085                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
1086         }
1087         return group.release();
1088 }
1089
1090 bool compareFRem(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1091 {
1092         if (outputAllocs.size() != 1)
1093                 return false;
1094
1095         vector<deUint8> expectedBytes;
1096         expectedOutputs[0].getBytes(expectedBytes);
1097
1098         const float*    expectedOutputAsFloat   = reinterpret_cast<const float*>(&expectedBytes.front());
1099         const float*    outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1100
1101         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(float); ++idx)
1102         {
1103                 const float f0 = expectedOutputAsFloat[idx];
1104                 const float f1 = outputAsFloat[idx];
1105                 // \todo relative error needs to be fairly high because FRem may be implemented as
1106                 // (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
1107                 if (deFloatAbs((f1 - f0) / f0) > 0.02)
1108                         return false;
1109         }
1110
1111         return true;
1112 }
1113
1114 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
1115 {
1116         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
1117         ComputeShaderSpec                               spec;
1118         de::Random                                              rnd                             (deStringHash(group->getName()));
1119         const int                                               numElements             = 200;
1120         vector<float>                                   inputFloats1    (numElements, 0);
1121         vector<float>                                   inputFloats2    (numElements, 0);
1122         vector<float>                                   outputFloats    (numElements, 0);
1123
1124         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1125         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
1126
1127         for (size_t ndx = 0; ndx < numElements; ++ndx)
1128         {
1129                 // Guard against divisors near zero.
1130                 if (std::fabs(inputFloats2[ndx]) < 1e-3)
1131                         inputFloats2[ndx] = 8.f;
1132
1133                 // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1134                 outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
1135         }
1136
1137         spec.assembly =
1138                 string(getComputeAsmShaderPreamble()) +
1139
1140                 "OpName %main           \"main\"\n"
1141                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1142
1143                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1144
1145                 "OpDecorate %buf BufferBlock\n"
1146                 "OpDecorate %indata1 DescriptorSet 0\n"
1147                 "OpDecorate %indata1 Binding 0\n"
1148                 "OpDecorate %indata2 DescriptorSet 0\n"
1149                 "OpDecorate %indata2 Binding 1\n"
1150                 "OpDecorate %outdata DescriptorSet 0\n"
1151                 "OpDecorate %outdata Binding 2\n"
1152                 "OpDecorate %f32arr ArrayStride 4\n"
1153                 "OpMemberDecorate %buf 0 Offset 0\n"
1154
1155                 + string(getComputeAsmCommonTypes()) +
1156
1157                 "%buf        = OpTypeStruct %f32arr\n"
1158                 "%bufptr     = OpTypePointer Uniform %buf\n"
1159                 "%indata1    = OpVariable %bufptr Uniform\n"
1160                 "%indata2    = OpVariable %bufptr Uniform\n"
1161                 "%outdata    = OpVariable %bufptr Uniform\n"
1162
1163                 "%id        = OpVariable %uvec3ptr Input\n"
1164                 "%zero      = OpConstant %i32 0\n"
1165
1166                 "%main      = OpFunction %void None %voidf\n"
1167                 "%label     = OpLabel\n"
1168                 "%idval     = OpLoad %uvec3 %id\n"
1169                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1170                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1171                 "%inval1    = OpLoad %f32 %inloc1\n"
1172                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1173                 "%inval2    = OpLoad %f32 %inloc2\n"
1174                 "%rem       = OpFRem %f32 %inval1 %inval2\n"
1175                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1176                 "             OpStore %outloc %rem\n"
1177                 "             OpReturn\n"
1178                 "             OpFunctionEnd\n";
1179
1180         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1181         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1182         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1183         spec.numWorkGroups = IVec3(numElements, 1, 1);
1184         spec.verifyIO = &compareFRem;
1185
1186         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1187
1188         return group.release();
1189 }
1190
1191 bool compareNMin (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1192 {
1193         if (outputAllocs.size() != 1)
1194                 return false;
1195
1196         const BufferSp&                 expectedOutput                  (expectedOutputs[0].getBuffer());
1197         std::vector<deUint8>    data;
1198         expectedOutput->getBytes(data);
1199
1200         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1201         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1202
1203         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1204         {
1205                 const float f0 = expectedOutputAsFloat[idx];
1206                 const float f1 = outputAsFloat[idx];
1207
1208                 // For NMin, we accept NaN as output if both inputs were NaN.
1209                 // Otherwise the NaN is the wrong choise, as on architectures that
1210                 // do not handle NaN, those are huge values.
1211                 if (!(tcu::Float32(f1).isNaN() && tcu::Float32(f0).isNaN()) && deFloatAbs(f1 - f0) > 0.00001f)
1212                         return false;
1213         }
1214
1215         return true;
1216 }
1217
1218 tcu::TestCaseGroup* createOpNMinGroup (tcu::TestContext& testCtx)
1219 {
1220         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnmin", "Test the OpNMin instruction"));
1221         ComputeShaderSpec                               spec;
1222         de::Random                                              rnd                             (deStringHash(group->getName()));
1223         const int                                               numElements             = 200;
1224         vector<float>                                   inputFloats1    (numElements, 0);
1225         vector<float>                                   inputFloats2    (numElements, 0);
1226         vector<float>                                   outputFloats    (numElements, 0);
1227
1228         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1229         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1230
1231         // Make the first case a full-NAN case.
1232         inputFloats1[0] = TCU_NAN;
1233         inputFloats2[0] = TCU_NAN;
1234
1235         for (size_t ndx = 0; ndx < numElements; ++ndx)
1236         {
1237                 // By default, pick the smallest
1238                 outputFloats[ndx] = std::min(inputFloats1[ndx], inputFloats2[ndx]);
1239
1240                 // Make half of the cases NaN cases
1241                 if ((ndx & 1) == 0)
1242                 {
1243                         // Alternate between the NaN operand
1244                         if ((ndx & 2) == 0)
1245                         {
1246                                 outputFloats[ndx] = inputFloats2[ndx];
1247                                 inputFloats1[ndx] = TCU_NAN;
1248                         }
1249                         else
1250                         {
1251                                 outputFloats[ndx] = inputFloats1[ndx];
1252                                 inputFloats2[ndx] = TCU_NAN;
1253                         }
1254                 }
1255         }
1256
1257         spec.assembly =
1258                 "OpCapability Shader\n"
1259                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1260                 "OpMemoryModel Logical GLSL450\n"
1261                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1262                 "OpExecutionMode %main LocalSize 1 1 1\n"
1263
1264                 "OpName %main           \"main\"\n"
1265                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1266
1267                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1268
1269                 "OpDecorate %buf BufferBlock\n"
1270                 "OpDecorate %indata1 DescriptorSet 0\n"
1271                 "OpDecorate %indata1 Binding 0\n"
1272                 "OpDecorate %indata2 DescriptorSet 0\n"
1273                 "OpDecorate %indata2 Binding 1\n"
1274                 "OpDecorate %outdata DescriptorSet 0\n"
1275                 "OpDecorate %outdata Binding 2\n"
1276                 "OpDecorate %f32arr ArrayStride 4\n"
1277                 "OpMemberDecorate %buf 0 Offset 0\n"
1278
1279                 + string(getComputeAsmCommonTypes()) +
1280
1281                 "%buf        = OpTypeStruct %f32arr\n"
1282                 "%bufptr     = OpTypePointer Uniform %buf\n"
1283                 "%indata1    = OpVariable %bufptr Uniform\n"
1284                 "%indata2    = OpVariable %bufptr Uniform\n"
1285                 "%outdata    = OpVariable %bufptr Uniform\n"
1286
1287                 "%id        = OpVariable %uvec3ptr Input\n"
1288                 "%zero      = OpConstant %i32 0\n"
1289
1290                 "%main      = OpFunction %void None %voidf\n"
1291                 "%label     = OpLabel\n"
1292                 "%idval     = OpLoad %uvec3 %id\n"
1293                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1294                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1295                 "%inval1    = OpLoad %f32 %inloc1\n"
1296                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1297                 "%inval2    = OpLoad %f32 %inloc2\n"
1298                 "%rem       = OpExtInst %f32 %std450 NMin %inval1 %inval2\n"
1299                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1300                 "             OpStore %outloc %rem\n"
1301                 "             OpReturn\n"
1302                 "             OpFunctionEnd\n";
1303
1304         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1305         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1306         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1307         spec.numWorkGroups = IVec3(numElements, 1, 1);
1308         spec.verifyIO = &compareNMin;
1309
1310         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1311
1312         return group.release();
1313 }
1314
1315 bool compareNMax (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1316 {
1317         if (outputAllocs.size() != 1)
1318                 return false;
1319
1320         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1321         std::vector<deUint8>    data;
1322         expectedOutput->getBytes(data);
1323
1324         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1325         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1326
1327         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1328         {
1329                 const float f0 = expectedOutputAsFloat[idx];
1330                 const float f1 = outputAsFloat[idx];
1331
1332                 // For NMax, NaN is considered acceptable result, since in
1333                 // architectures that do not handle NaNs, those are huge values.
1334                 if (!tcu::Float32(f1).isNaN() && deFloatAbs(f1 - f0) > 0.00001f)
1335                         return false;
1336         }
1337
1338         return true;
1339 }
1340
1341 tcu::TestCaseGroup* createOpNMaxGroup (tcu::TestContext& testCtx)
1342 {
1343         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opnmax", "Test the OpNMax instruction"));
1344         ComputeShaderSpec                               spec;
1345         de::Random                                              rnd                             (deStringHash(group->getName()));
1346         const int                                               numElements             = 200;
1347         vector<float>                                   inputFloats1    (numElements, 0);
1348         vector<float>                                   inputFloats2    (numElements, 0);
1349         vector<float>                                   outputFloats    (numElements, 0);
1350
1351         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1352         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1353
1354         // Make the first case a full-NAN case.
1355         inputFloats1[0] = TCU_NAN;
1356         inputFloats2[0] = TCU_NAN;
1357
1358         for (size_t ndx = 0; ndx < numElements; ++ndx)
1359         {
1360                 // By default, pick the biggest
1361                 outputFloats[ndx] = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1362
1363                 // Make half of the cases NaN cases
1364                 if ((ndx & 1) == 0)
1365                 {
1366                         // Alternate between the NaN operand
1367                         if ((ndx & 2) == 0)
1368                         {
1369                                 outputFloats[ndx] = inputFloats2[ndx];
1370                                 inputFloats1[ndx] = TCU_NAN;
1371                         }
1372                         else
1373                         {
1374                                 outputFloats[ndx] = inputFloats1[ndx];
1375                                 inputFloats2[ndx] = TCU_NAN;
1376                         }
1377                 }
1378         }
1379
1380         spec.assembly =
1381                 "OpCapability Shader\n"
1382                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1383                 "OpMemoryModel Logical GLSL450\n"
1384                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1385                 "OpExecutionMode %main LocalSize 1 1 1\n"
1386
1387                 "OpName %main           \"main\"\n"
1388                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1389
1390                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1391
1392                 "OpDecorate %buf BufferBlock\n"
1393                 "OpDecorate %indata1 DescriptorSet 0\n"
1394                 "OpDecorate %indata1 Binding 0\n"
1395                 "OpDecorate %indata2 DescriptorSet 0\n"
1396                 "OpDecorate %indata2 Binding 1\n"
1397                 "OpDecorate %outdata DescriptorSet 0\n"
1398                 "OpDecorate %outdata Binding 2\n"
1399                 "OpDecorate %f32arr ArrayStride 4\n"
1400                 "OpMemberDecorate %buf 0 Offset 0\n"
1401
1402                 + string(getComputeAsmCommonTypes()) +
1403
1404                 "%buf        = OpTypeStruct %f32arr\n"
1405                 "%bufptr     = OpTypePointer Uniform %buf\n"
1406                 "%indata1    = OpVariable %bufptr Uniform\n"
1407                 "%indata2    = OpVariable %bufptr Uniform\n"
1408                 "%outdata    = OpVariable %bufptr Uniform\n"
1409
1410                 "%id        = OpVariable %uvec3ptr Input\n"
1411                 "%zero      = OpConstant %i32 0\n"
1412
1413                 "%main      = OpFunction %void None %voidf\n"
1414                 "%label     = OpLabel\n"
1415                 "%idval     = OpLoad %uvec3 %id\n"
1416                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1417                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1418                 "%inval1    = OpLoad %f32 %inloc1\n"
1419                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1420                 "%inval2    = OpLoad %f32 %inloc2\n"
1421                 "%rem       = OpExtInst %f32 %std450 NMax %inval1 %inval2\n"
1422                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1423                 "             OpStore %outloc %rem\n"
1424                 "             OpReturn\n"
1425                 "             OpFunctionEnd\n";
1426
1427         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1428         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1429         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1430         spec.numWorkGroups = IVec3(numElements, 1, 1);
1431         spec.verifyIO = &compareNMax;
1432
1433         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1434
1435         return group.release();
1436 }
1437
1438 bool compareNClamp (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1439 {
1440         if (outputAllocs.size() != 1)
1441                 return false;
1442
1443         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1444         std::vector<deUint8>    data;
1445         expectedOutput->getBytes(data);
1446
1447         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1448         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1449
1450         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float) / 2; ++idx)
1451         {
1452                 const float e0 = expectedOutputAsFloat[idx * 2];
1453                 const float e1 = expectedOutputAsFloat[idx * 2 + 1];
1454                 const float res = outputAsFloat[idx];
1455
1456                 // For NClamp, we have two possible outcomes based on
1457                 // whether NaNs are handled or not.
1458                 // If either min or max value is NaN, the result is undefined,
1459                 // so this test doesn't stress those. If the clamped value is
1460                 // NaN, and NaNs are handled, the result is min; if NaNs are not
1461                 // handled, they are big values that result in max.
1462                 // If all three parameters are NaN, the result should be NaN.
1463                 if (!((tcu::Float32(e0).isNaN() && tcu::Float32(res).isNaN()) ||
1464                          (deFloatAbs(e0 - res) < 0.00001f) ||
1465                          (deFloatAbs(e1 - res) < 0.00001f)))
1466                         return false;
1467         }
1468
1469         return true;
1470 }
1471
1472 tcu::TestCaseGroup* createOpNClampGroup (tcu::TestContext& testCtx)
1473 {
1474         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnclamp", "Test the OpNClamp instruction"));
1475         ComputeShaderSpec                               spec;
1476         de::Random                                              rnd                             (deStringHash(group->getName()));
1477         const int                                               numElements             = 200;
1478         vector<float>                                   inputFloats1    (numElements, 0);
1479         vector<float>                                   inputFloats2    (numElements, 0);
1480         vector<float>                                   inputFloats3    (numElements, 0);
1481         vector<float>                                   outputFloats    (numElements * 2, 0);
1482
1483         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1484         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1485         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats3[0], numElements);
1486
1487         for (size_t ndx = 0; ndx < numElements; ++ndx)
1488         {
1489                 // Results are only defined if max value is bigger than min value.
1490                 if (inputFloats2[ndx] > inputFloats3[ndx])
1491                 {
1492                         float t = inputFloats2[ndx];
1493                         inputFloats2[ndx] = inputFloats3[ndx];
1494                         inputFloats3[ndx] = t;
1495                 }
1496
1497                 // By default, do the clamp, setting both possible answers
1498                 float defaultRes = std::min(std::max(inputFloats1[ndx], inputFloats2[ndx]), inputFloats3[ndx]);
1499
1500                 float maxResA = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1501                 float maxResB = maxResA;
1502
1503                 // Alternate between the NaN cases
1504                 if (ndx & 1)
1505                 {
1506                         inputFloats1[ndx] = TCU_NAN;
1507                         // If NaN is handled, the result should be same as the clamp minimum.
1508                         // If NaN is not handled, the result should clamp to the clamp maximum.
1509                         maxResA = inputFloats2[ndx];
1510                         maxResB = inputFloats3[ndx];
1511                 }
1512                 else
1513                 {
1514                         // Not a NaN case - only one legal result.
1515                         maxResA = defaultRes;
1516                         maxResB = defaultRes;
1517                 }
1518
1519                 outputFloats[ndx * 2] = maxResA;
1520                 outputFloats[ndx * 2 + 1] = maxResB;
1521         }
1522
1523         // Make the first case a full-NAN case.
1524         inputFloats1[0] = TCU_NAN;
1525         inputFloats2[0] = TCU_NAN;
1526         inputFloats3[0] = TCU_NAN;
1527         outputFloats[0] = TCU_NAN;
1528         outputFloats[1] = TCU_NAN;
1529
1530         spec.assembly =
1531                 "OpCapability Shader\n"
1532                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1533                 "OpMemoryModel Logical GLSL450\n"
1534                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1535                 "OpExecutionMode %main LocalSize 1 1 1\n"
1536
1537                 "OpName %main           \"main\"\n"
1538                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1539
1540                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1541
1542                 "OpDecorate %buf BufferBlock\n"
1543                 "OpDecorate %indata1 DescriptorSet 0\n"
1544                 "OpDecorate %indata1 Binding 0\n"
1545                 "OpDecorate %indata2 DescriptorSet 0\n"
1546                 "OpDecorate %indata2 Binding 1\n"
1547                 "OpDecorate %indata3 DescriptorSet 0\n"
1548                 "OpDecorate %indata3 Binding 2\n"
1549                 "OpDecorate %outdata DescriptorSet 0\n"
1550                 "OpDecorate %outdata Binding 3\n"
1551                 "OpDecorate %f32arr ArrayStride 4\n"
1552                 "OpMemberDecorate %buf 0 Offset 0\n"
1553
1554                 + string(getComputeAsmCommonTypes()) +
1555
1556                 "%buf        = OpTypeStruct %f32arr\n"
1557                 "%bufptr     = OpTypePointer Uniform %buf\n"
1558                 "%indata1    = OpVariable %bufptr Uniform\n"
1559                 "%indata2    = OpVariable %bufptr Uniform\n"
1560                 "%indata3    = OpVariable %bufptr Uniform\n"
1561                 "%outdata    = OpVariable %bufptr Uniform\n"
1562
1563                 "%id        = OpVariable %uvec3ptr Input\n"
1564                 "%zero      = OpConstant %i32 0\n"
1565
1566                 "%main      = OpFunction %void None %voidf\n"
1567                 "%label     = OpLabel\n"
1568                 "%idval     = OpLoad %uvec3 %id\n"
1569                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1570                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1571                 "%inval1    = OpLoad %f32 %inloc1\n"
1572                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1573                 "%inval2    = OpLoad %f32 %inloc2\n"
1574                 "%inloc3    = OpAccessChain %f32ptr %indata3 %zero %x\n"
1575                 "%inval3    = OpLoad %f32 %inloc3\n"
1576                 "%rem       = OpExtInst %f32 %std450 NClamp %inval1 %inval2 %inval3\n"
1577                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1578                 "             OpStore %outloc %rem\n"
1579                 "             OpReturn\n"
1580                 "             OpFunctionEnd\n";
1581
1582         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1583         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1584         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1585         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1586         spec.numWorkGroups = IVec3(numElements, 1, 1);
1587         spec.verifyIO = &compareNClamp;
1588
1589         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1590
1591         return group.release();
1592 }
1593
1594 tcu::TestCaseGroup* createOpSRemComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1595 {
1596         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem", "Test the OpSRem instruction"));
1597         de::Random                                              rnd                             (deStringHash(group->getName()));
1598         const int                                               numElements             = 200;
1599
1600         const struct CaseParams
1601         {
1602                 const char*             name;
1603                 const char*             failMessage;            // customized status message
1604                 qpTestResult    failResult;                     // override status on failure
1605                 int                             op1Min, op1Max;         // operand ranges
1606                 int                             op2Min, op2Max;
1607         } cases[] =
1608         {
1609                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1610                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1611         };
1612         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1613
1614         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1615         {
1616                 const CaseParams&       params          = cases[caseNdx];
1617                 ComputeShaderSpec       spec;
1618                 vector<deInt32>         inputInts1      (numElements, 0);
1619                 vector<deInt32>         inputInts2      (numElements, 0);
1620                 vector<deInt32>         outputInts      (numElements, 0);
1621
1622                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1623                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1624
1625                 for (int ndx = 0; ndx < numElements; ++ndx)
1626                 {
1627                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1628                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1629                 }
1630
1631                 spec.assembly =
1632                         string(getComputeAsmShaderPreamble()) +
1633
1634                         "OpName %main           \"main\"\n"
1635                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1636
1637                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1638
1639                         "OpDecorate %buf BufferBlock\n"
1640                         "OpDecorate %indata1 DescriptorSet 0\n"
1641                         "OpDecorate %indata1 Binding 0\n"
1642                         "OpDecorate %indata2 DescriptorSet 0\n"
1643                         "OpDecorate %indata2 Binding 1\n"
1644                         "OpDecorate %outdata DescriptorSet 0\n"
1645                         "OpDecorate %outdata Binding 2\n"
1646                         "OpDecorate %i32arr ArrayStride 4\n"
1647                         "OpMemberDecorate %buf 0 Offset 0\n"
1648
1649                         + string(getComputeAsmCommonTypes()) +
1650
1651                         "%buf        = OpTypeStruct %i32arr\n"
1652                         "%bufptr     = OpTypePointer Uniform %buf\n"
1653                         "%indata1    = OpVariable %bufptr Uniform\n"
1654                         "%indata2    = OpVariable %bufptr Uniform\n"
1655                         "%outdata    = OpVariable %bufptr Uniform\n"
1656
1657                         "%id        = OpVariable %uvec3ptr Input\n"
1658                         "%zero      = OpConstant %i32 0\n"
1659
1660                         "%main      = OpFunction %void None %voidf\n"
1661                         "%label     = OpLabel\n"
1662                         "%idval     = OpLoad %uvec3 %id\n"
1663                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1664                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1665                         "%inval1    = OpLoad %i32 %inloc1\n"
1666                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1667                         "%inval2    = OpLoad %i32 %inloc2\n"
1668                         "%rem       = OpSRem %i32 %inval1 %inval2\n"
1669                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1670                         "             OpStore %outloc %rem\n"
1671                         "             OpReturn\n"
1672                         "             OpFunctionEnd\n";
1673
1674                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1675                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1676                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1677                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1678                 spec.failResult                 = params.failResult;
1679                 spec.failMessage                = params.failMessage;
1680
1681                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1682         }
1683
1684         return group.release();
1685 }
1686
1687 tcu::TestCaseGroup* createOpSRemComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1688 {
1689         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem64", "Test the 64-bit OpSRem instruction"));
1690         de::Random                                              rnd                             (deStringHash(group->getName()));
1691         const int                                               numElements             = 200;
1692
1693         const struct CaseParams
1694         {
1695                 const char*             name;
1696                 const char*             failMessage;            // customized status message
1697                 qpTestResult    failResult;                     // override status on failure
1698                 bool                    positive;
1699         } cases[] =
1700         {
1701                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1702                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1703         };
1704         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1705
1706         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1707         {
1708                 const CaseParams&       params          = cases[caseNdx];
1709                 ComputeShaderSpec       spec;
1710                 vector<deInt64>         inputInts1      (numElements, 0);
1711                 vector<deInt64>         inputInts2      (numElements, 0);
1712                 vector<deInt64>         outputInts      (numElements, 0);
1713
1714                 if (params.positive)
1715                 {
1716                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1717                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1718                 }
1719                 else
1720                 {
1721                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1722                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1723                 }
1724
1725                 for (int ndx = 0; ndx < numElements; ++ndx)
1726                 {
1727                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1728                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1729                 }
1730
1731                 spec.assembly =
1732                         "OpCapability Int64\n"
1733
1734                         + string(getComputeAsmShaderPreamble()) +
1735
1736                         "OpName %main           \"main\"\n"
1737                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1738
1739                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1740
1741                         "OpDecorate %buf BufferBlock\n"
1742                         "OpDecorate %indata1 DescriptorSet 0\n"
1743                         "OpDecorate %indata1 Binding 0\n"
1744                         "OpDecorate %indata2 DescriptorSet 0\n"
1745                         "OpDecorate %indata2 Binding 1\n"
1746                         "OpDecorate %outdata DescriptorSet 0\n"
1747                         "OpDecorate %outdata Binding 2\n"
1748                         "OpDecorate %i64arr ArrayStride 8\n"
1749                         "OpMemberDecorate %buf 0 Offset 0\n"
1750
1751                         + string(getComputeAsmCommonTypes())
1752                         + string(getComputeAsmCommonInt64Types()) +
1753
1754                         "%buf        = OpTypeStruct %i64arr\n"
1755                         "%bufptr     = OpTypePointer Uniform %buf\n"
1756                         "%indata1    = OpVariable %bufptr Uniform\n"
1757                         "%indata2    = OpVariable %bufptr Uniform\n"
1758                         "%outdata    = OpVariable %bufptr Uniform\n"
1759
1760                         "%id        = OpVariable %uvec3ptr Input\n"
1761                         "%zero      = OpConstant %i64 0\n"
1762
1763                         "%main      = OpFunction %void None %voidf\n"
1764                         "%label     = OpLabel\n"
1765                         "%idval     = OpLoad %uvec3 %id\n"
1766                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1767                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1768                         "%inval1    = OpLoad %i64 %inloc1\n"
1769                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1770                         "%inval2    = OpLoad %i64 %inloc2\n"
1771                         "%rem       = OpSRem %i64 %inval1 %inval2\n"
1772                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1773                         "             OpStore %outloc %rem\n"
1774                         "             OpReturn\n"
1775                         "             OpFunctionEnd\n";
1776
1777                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1778                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1779                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1780                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1781                 spec.failResult                 = params.failResult;
1782                 spec.failMessage                = params.failMessage;
1783
1784                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
1785
1786                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1787         }
1788
1789         return group.release();
1790 }
1791
1792 tcu::TestCaseGroup* createOpSModComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1793 {
1794         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod", "Test the OpSMod instruction"));
1795         de::Random                                              rnd                             (deStringHash(group->getName()));
1796         const int                                               numElements             = 200;
1797
1798         const struct CaseParams
1799         {
1800                 const char*             name;
1801                 const char*             failMessage;            // customized status message
1802                 qpTestResult    failResult;                     // override status on failure
1803                 int                             op1Min, op1Max;         // operand ranges
1804                 int                             op2Min, op2Max;
1805         } cases[] =
1806         {
1807                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1808                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1809         };
1810         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1811
1812         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1813         {
1814                 const CaseParams&       params          = cases[caseNdx];
1815
1816                 ComputeShaderSpec       spec;
1817                 vector<deInt32>         inputInts1      (numElements, 0);
1818                 vector<deInt32>         inputInts2      (numElements, 0);
1819                 vector<deInt32>         outputInts      (numElements, 0);
1820
1821                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1822                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1823
1824                 for (int ndx = 0; ndx < numElements; ++ndx)
1825                 {
1826                         deInt32 rem = inputInts1[ndx] % inputInts2[ndx];
1827                         if (rem == 0)
1828                         {
1829                                 outputInts[ndx] = 0;
1830                         }
1831                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1832                         {
1833                                 // They have the same sign
1834                                 outputInts[ndx] = rem;
1835                         }
1836                         else
1837                         {
1838                                 // They have opposite sign.  The remainder operation takes the
1839                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1840                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1841                                 // the result has the correct sign and that it is still
1842                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1843                                 //
1844                                 // See also http://mathforum.org/library/drmath/view/52343.html
1845                                 outputInts[ndx] = rem + inputInts2[ndx];
1846                         }
1847                 }
1848
1849                 spec.assembly =
1850                         string(getComputeAsmShaderPreamble()) +
1851
1852                         "OpName %main           \"main\"\n"
1853                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1854
1855                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1856
1857                         "OpDecorate %buf BufferBlock\n"
1858                         "OpDecorate %indata1 DescriptorSet 0\n"
1859                         "OpDecorate %indata1 Binding 0\n"
1860                         "OpDecorate %indata2 DescriptorSet 0\n"
1861                         "OpDecorate %indata2 Binding 1\n"
1862                         "OpDecorate %outdata DescriptorSet 0\n"
1863                         "OpDecorate %outdata Binding 2\n"
1864                         "OpDecorate %i32arr ArrayStride 4\n"
1865                         "OpMemberDecorate %buf 0 Offset 0\n"
1866
1867                         + string(getComputeAsmCommonTypes()) +
1868
1869                         "%buf        = OpTypeStruct %i32arr\n"
1870                         "%bufptr     = OpTypePointer Uniform %buf\n"
1871                         "%indata1    = OpVariable %bufptr Uniform\n"
1872                         "%indata2    = OpVariable %bufptr Uniform\n"
1873                         "%outdata    = OpVariable %bufptr Uniform\n"
1874
1875                         "%id        = OpVariable %uvec3ptr Input\n"
1876                         "%zero      = OpConstant %i32 0\n"
1877
1878                         "%main      = OpFunction %void None %voidf\n"
1879                         "%label     = OpLabel\n"
1880                         "%idval     = OpLoad %uvec3 %id\n"
1881                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1882                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1883                         "%inval1    = OpLoad %i32 %inloc1\n"
1884                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1885                         "%inval2    = OpLoad %i32 %inloc2\n"
1886                         "%rem       = OpSMod %i32 %inval1 %inval2\n"
1887                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1888                         "             OpStore %outloc %rem\n"
1889                         "             OpReturn\n"
1890                         "             OpFunctionEnd\n";
1891
1892                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1893                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1894                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1895                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1896                 spec.failResult                 = params.failResult;
1897                 spec.failMessage                = params.failMessage;
1898
1899                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1900         }
1901
1902         return group.release();
1903 }
1904
1905 tcu::TestCaseGroup* createOpSModComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1906 {
1907         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod64", "Test the OpSMod instruction"));
1908         de::Random                                              rnd                             (deStringHash(group->getName()));
1909         const int                                               numElements             = 200;
1910
1911         const struct CaseParams
1912         {
1913                 const char*             name;
1914                 const char*             failMessage;            // customized status message
1915                 qpTestResult    failResult;                     // override status on failure
1916                 bool                    positive;
1917         } cases[] =
1918         {
1919                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1920                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1921         };
1922         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1923
1924         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1925         {
1926                 const CaseParams&       params          = cases[caseNdx];
1927
1928                 ComputeShaderSpec       spec;
1929                 vector<deInt64>         inputInts1      (numElements, 0);
1930                 vector<deInt64>         inputInts2      (numElements, 0);
1931                 vector<deInt64>         outputInts      (numElements, 0);
1932
1933
1934                 if (params.positive)
1935                 {
1936                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1937                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1938                 }
1939                 else
1940                 {
1941                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1942                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1943                 }
1944
1945                 for (int ndx = 0; ndx < numElements; ++ndx)
1946                 {
1947                         deInt64 rem = inputInts1[ndx] % inputInts2[ndx];
1948                         if (rem == 0)
1949                         {
1950                                 outputInts[ndx] = 0;
1951                         }
1952                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1953                         {
1954                                 // They have the same sign
1955                                 outputInts[ndx] = rem;
1956                         }
1957                         else
1958                         {
1959                                 // They have opposite sign.  The remainder operation takes the
1960                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1961                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1962                                 // the result has the correct sign and that it is still
1963                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1964                                 //
1965                                 // See also http://mathforum.org/library/drmath/view/52343.html
1966                                 outputInts[ndx] = rem + inputInts2[ndx];
1967                         }
1968                 }
1969
1970                 spec.assembly =
1971                         "OpCapability Int64\n"
1972
1973                         + string(getComputeAsmShaderPreamble()) +
1974
1975                         "OpName %main           \"main\"\n"
1976                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1977
1978                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1979
1980                         "OpDecorate %buf BufferBlock\n"
1981                         "OpDecorate %indata1 DescriptorSet 0\n"
1982                         "OpDecorate %indata1 Binding 0\n"
1983                         "OpDecorate %indata2 DescriptorSet 0\n"
1984                         "OpDecorate %indata2 Binding 1\n"
1985                         "OpDecorate %outdata DescriptorSet 0\n"
1986                         "OpDecorate %outdata Binding 2\n"
1987                         "OpDecorate %i64arr ArrayStride 8\n"
1988                         "OpMemberDecorate %buf 0 Offset 0\n"
1989
1990                         + string(getComputeAsmCommonTypes())
1991                         + string(getComputeAsmCommonInt64Types()) +
1992
1993                         "%buf        = OpTypeStruct %i64arr\n"
1994                         "%bufptr     = OpTypePointer Uniform %buf\n"
1995                         "%indata1    = OpVariable %bufptr Uniform\n"
1996                         "%indata2    = OpVariable %bufptr Uniform\n"
1997                         "%outdata    = OpVariable %bufptr Uniform\n"
1998
1999                         "%id        = OpVariable %uvec3ptr Input\n"
2000                         "%zero      = OpConstant %i64 0\n"
2001
2002                         "%main      = OpFunction %void None %voidf\n"
2003                         "%label     = OpLabel\n"
2004                         "%idval     = OpLoad %uvec3 %id\n"
2005                         "%x         = OpCompositeExtract %u32 %idval 0\n"
2006                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
2007                         "%inval1    = OpLoad %i64 %inloc1\n"
2008                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
2009                         "%inval2    = OpLoad %i64 %inloc2\n"
2010                         "%rem       = OpSMod %i64 %inval1 %inval2\n"
2011                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
2012                         "             OpStore %outloc %rem\n"
2013                         "             OpReturn\n"
2014                         "             OpFunctionEnd\n";
2015
2016                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
2017                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
2018                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
2019                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
2020                 spec.failResult                 = params.failResult;
2021                 spec.failMessage                = params.failMessage;
2022
2023                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
2024
2025                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2026         }
2027
2028         return group.release();
2029 }
2030
2031 // Copy contents in the input buffer to the output buffer.
2032 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
2033 {
2034         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
2035         de::Random                                              rnd                             (deStringHash(group->getName()));
2036         const int                                               numElements             = 100;
2037
2038         // 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.
2039         ComputeShaderSpec                               spec1;
2040         vector<Vec4>                                    inputFloats1    (numElements);
2041         vector<Vec4>                                    outputFloats1   (numElements);
2042
2043         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
2044
2045         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2046         floorAll(inputFloats1);
2047
2048         for (size_t ndx = 0; ndx < numElements; ++ndx)
2049                 outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
2050
2051         spec1.assembly =
2052                 string(getComputeAsmShaderPreamble()) +
2053
2054                 "OpName %main           \"main\"\n"
2055                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2056
2057                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2058                 "OpDecorate %vec4arr ArrayStride 16\n"
2059
2060                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2061
2062                 "%vec4       = OpTypeVector %f32 4\n"
2063                 "%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
2064                 "%vec4ptr_f  = OpTypePointer Function %vec4\n"
2065                 "%vec4arr    = OpTypeRuntimeArray %vec4\n"
2066                 "%buf        = OpTypeStruct %vec4arr\n"
2067                 "%bufptr     = OpTypePointer Uniform %buf\n"
2068                 "%indata     = OpVariable %bufptr Uniform\n"
2069                 "%outdata    = OpVariable %bufptr Uniform\n"
2070
2071                 "%id         = OpVariable %uvec3ptr Input\n"
2072                 "%zero       = OpConstant %i32 0\n"
2073                 "%c_f_0      = OpConstant %f32 0.\n"
2074                 "%c_f_0_5    = OpConstant %f32 0.5\n"
2075                 "%c_f_1_5    = OpConstant %f32 1.5\n"
2076                 "%c_f_2_5    = OpConstant %f32 2.5\n"
2077                 "%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
2078
2079                 "%main       = OpFunction %void None %voidf\n"
2080                 "%label      = OpLabel\n"
2081                 "%v_vec4     = OpVariable %vec4ptr_f Function\n"
2082                 "%idval      = OpLoad %uvec3 %id\n"
2083                 "%x          = OpCompositeExtract %u32 %idval 0\n"
2084                 "%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
2085                 "%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
2086                 "              OpCopyMemory %v_vec4 %inloc\n"
2087                 "%v_vec4_val = OpLoad %vec4 %v_vec4\n"
2088                 "%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
2089                 "              OpStore %outloc %add\n"
2090                 "              OpReturn\n"
2091                 "              OpFunctionEnd\n";
2092
2093         spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
2094         spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
2095         spec1.numWorkGroups = IVec3(numElements, 1, 1);
2096
2097         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
2098
2099         // The following case copies a float[100] variable from the input buffer to the output buffer.
2100         ComputeShaderSpec                               spec2;
2101         vector<float>                                   inputFloats2    (numElements);
2102         vector<float>                                   outputFloats2   (numElements);
2103
2104         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
2105
2106         for (size_t ndx = 0; ndx < numElements; ++ndx)
2107                 outputFloats2[ndx] = inputFloats2[ndx];
2108
2109         spec2.assembly =
2110                 string(getComputeAsmShaderPreamble()) +
2111
2112                 "OpName %main           \"main\"\n"
2113                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2114
2115                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2116                 "OpDecorate %f32arr100 ArrayStride 4\n"
2117
2118                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2119
2120                 "%hundred        = OpConstant %u32 100\n"
2121                 "%f32arr100      = OpTypeArray %f32 %hundred\n"
2122                 "%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
2123                 "%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
2124                 "%buf            = OpTypeStruct %f32arr100\n"
2125                 "%bufptr         = OpTypePointer Uniform %buf\n"
2126                 "%indata         = OpVariable %bufptr Uniform\n"
2127                 "%outdata        = OpVariable %bufptr Uniform\n"
2128
2129                 "%id             = OpVariable %uvec3ptr Input\n"
2130                 "%zero           = OpConstant %i32 0\n"
2131
2132                 "%main           = OpFunction %void None %voidf\n"
2133                 "%label          = OpLabel\n"
2134                 "%var            = OpVariable %f32arr100ptr_f Function\n"
2135                 "%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
2136                 "%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
2137                 "                  OpCopyMemory %var %inarr\n"
2138                 "                  OpCopyMemory %outarr %var\n"
2139                 "                  OpReturn\n"
2140                 "                  OpFunctionEnd\n";
2141
2142         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2143         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2144         spec2.numWorkGroups = IVec3(1, 1, 1);
2145
2146         group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
2147
2148         // The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
2149         ComputeShaderSpec                               spec3;
2150         vector<float>                                   inputFloats3    (16);
2151         vector<float>                                   outputFloats3   (16);
2152
2153         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
2154
2155         for (size_t ndx = 0; ndx < 16; ++ndx)
2156                 outputFloats3[ndx] = inputFloats3[ndx];
2157
2158         spec3.assembly =
2159                 string(getComputeAsmShaderPreamble()) +
2160
2161                 "OpName %main           \"main\"\n"
2162                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2163
2164                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2165                 //"OpMemberDecorate %buf 0 Offset 0\n"  - exists in getComputeAsmInputOutputBufferTraits
2166                 "OpMemberDecorate %buf 1 Offset 16\n"
2167                 "OpMemberDecorate %buf 2 Offset 32\n"
2168                 "OpMemberDecorate %buf 3 Offset 48\n"
2169
2170                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2171
2172                 "%vec4      = OpTypeVector %f32 4\n"
2173                 "%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
2174                 "%bufptr    = OpTypePointer Uniform %buf\n"
2175                 "%indata    = OpVariable %bufptr Uniform\n"
2176                 "%outdata   = OpVariable %bufptr Uniform\n"
2177                 "%vec4stptr = OpTypePointer Function %buf\n"
2178
2179                 "%id        = OpVariable %uvec3ptr Input\n"
2180                 "%zero      = OpConstant %i32 0\n"
2181
2182                 "%main      = OpFunction %void None %voidf\n"
2183                 "%label     = OpLabel\n"
2184                 "%var       = OpVariable %vec4stptr Function\n"
2185                 "             OpCopyMemory %var %indata\n"
2186                 "             OpCopyMemory %outdata %var\n"
2187                 "             OpReturn\n"
2188                 "             OpFunctionEnd\n";
2189
2190         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2191         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
2192         spec3.numWorkGroups = IVec3(1, 1, 1);
2193
2194         group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
2195
2196         // The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
2197         ComputeShaderSpec                               spec4;
2198         vector<float>                                   inputFloats4    (numElements);
2199         vector<float>                                   outputFloats4   (numElements);
2200
2201         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
2202
2203         for (size_t ndx = 0; ndx < numElements; ++ndx)
2204                 outputFloats4[ndx] = -inputFloats4[ndx];
2205
2206         spec4.assembly =
2207                 string(getComputeAsmShaderPreamble()) +
2208
2209                 "OpName %main           \"main\"\n"
2210                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2211
2212                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2213
2214                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2215
2216                 "%f32ptr_f  = OpTypePointer Function %f32\n"
2217                 "%id        = OpVariable %uvec3ptr Input\n"
2218                 "%zero      = OpConstant %i32 0\n"
2219
2220                 "%main      = OpFunction %void None %voidf\n"
2221                 "%label     = OpLabel\n"
2222                 "%var       = OpVariable %f32ptr_f Function\n"
2223                 "%idval     = OpLoad %uvec3 %id\n"
2224                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2225                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2226                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2227                 "             OpCopyMemory %var %inloc\n"
2228                 "%val       = OpLoad %f32 %var\n"
2229                 "%neg       = OpFNegate %f32 %val\n"
2230                 "             OpStore %outloc %neg\n"
2231                 "             OpReturn\n"
2232                 "             OpFunctionEnd\n";
2233
2234         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2235         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
2236         spec4.numWorkGroups = IVec3(numElements, 1, 1);
2237
2238         group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
2239
2240         return group.release();
2241 }
2242
2243 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
2244 {
2245         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
2246         ComputeShaderSpec                               spec;
2247         de::Random                                              rnd                             (deStringHash(group->getName()));
2248         const int                                               numElements             = 100;
2249         vector<float>                                   inputFloats             (numElements, 0);
2250         vector<float>                                   outputFloats    (numElements, 0);
2251
2252         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2253
2254         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2255         floorAll(inputFloats);
2256
2257         for (size_t ndx = 0; ndx < numElements; ++ndx)
2258                 outputFloats[ndx] = inputFloats[ndx] + 7.5f;
2259
2260         spec.assembly =
2261                 string(getComputeAsmShaderPreamble()) +
2262
2263                 "OpName %main           \"main\"\n"
2264                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2265
2266                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2267
2268                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2269
2270                 "%fmat     = OpTypeMatrix %fvec3 3\n"
2271                 "%three    = OpConstant %u32 3\n"
2272                 "%farr     = OpTypeArray %f32 %three\n"
2273                 "%fst      = OpTypeStruct %f32 %f32\n"
2274
2275                 + string(getComputeAsmInputOutputBuffer()) +
2276
2277                 "%id            = OpVariable %uvec3ptr Input\n"
2278                 "%zero          = OpConstant %i32 0\n"
2279                 "%c_f           = OpConstant %f32 1.5\n"
2280                 "%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
2281                 "%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
2282                 "%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
2283                 "%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
2284
2285                 "%main          = OpFunction %void None %voidf\n"
2286                 "%label         = OpLabel\n"
2287                 "%c_f_copy      = OpCopyObject %f32   %c_f\n"
2288                 "%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
2289                 "%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
2290                 "%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
2291                 "%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
2292                 "%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
2293                 "%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
2294                 "%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
2295                 "%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
2296                 // Add up. 1.5 * 5 = 7.5.
2297                 "%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
2298                 "%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
2299                 "%add3          = OpFAdd %f32 %add2     %farr_elem\n"
2300                 "%add4          = OpFAdd %f32 %add3     %fst_elem\n"
2301
2302                 "%idval         = OpLoad %uvec3 %id\n"
2303                 "%x             = OpCompositeExtract %u32 %idval 0\n"
2304                 "%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
2305                 "%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
2306                 "%inval         = OpLoad %f32 %inloc\n"
2307                 "%add           = OpFAdd %f32 %add4 %inval\n"
2308                 "                 OpStore %outloc %add\n"
2309                 "                 OpReturn\n"
2310                 "                 OpFunctionEnd\n";
2311         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2312         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2313         spec.numWorkGroups = IVec3(numElements, 1, 1);
2314
2315         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
2316
2317         return group.release();
2318 }
2319 // Assembly code used for testing OpUnreachable is based on GLSL source code:
2320 //
2321 // #version 430
2322 //
2323 // layout(std140, set = 0, binding = 0) readonly buffer Input {
2324 //   float elements[];
2325 // } input_data;
2326 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
2327 //   float elements[];
2328 // } output_data;
2329 //
2330 // void not_called_func() {
2331 //   // place OpUnreachable here
2332 // }
2333 //
2334 // uint modulo4(uint val) {
2335 //   switch (val % uint(4)) {
2336 //     case 0:  return 3;
2337 //     case 1:  return 2;
2338 //     case 2:  return 1;
2339 //     case 3:  return 0;
2340 //     default: return 100; // place OpUnreachable here
2341 //   }
2342 // }
2343 //
2344 // uint const5() {
2345 //   return 5;
2346 //   // place OpUnreachable here
2347 // }
2348 //
2349 // void main() {
2350 //   uint x = gl_GlobalInvocationID.x;
2351 //   if (const5() > modulo4(1000)) {
2352 //     output_data.elements[x] = -input_data.elements[x];
2353 //   } else {
2354 //     // place OpUnreachable here
2355 //     output_data.elements[x] = input_data.elements[x];
2356 //   }
2357 // }
2358
2359 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
2360 {
2361         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
2362         ComputeShaderSpec                               spec;
2363         de::Random                                              rnd                             (deStringHash(group->getName()));
2364         const int                                               numElements             = 100;
2365         vector<float>                                   positiveFloats  (numElements, 0);
2366         vector<float>                                   negativeFloats  (numElements, 0);
2367
2368         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2369
2370         for (size_t ndx = 0; ndx < numElements; ++ndx)
2371                 negativeFloats[ndx] = -positiveFloats[ndx];
2372
2373         spec.assembly =
2374                 string(getComputeAsmShaderPreamble()) +
2375
2376                 "OpSource GLSL 430\n"
2377                 "OpName %main            \"main\"\n"
2378                 "OpName %func_not_called_func \"not_called_func(\"\n"
2379                 "OpName %func_modulo4         \"modulo4(u1;\"\n"
2380                 "OpName %func_const5          \"const5(\"\n"
2381                 "OpName %id                   \"gl_GlobalInvocationID\"\n"
2382
2383                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2384
2385                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2386
2387                 "%u32ptr    = OpTypePointer Function %u32\n"
2388                 "%uintfuint = OpTypeFunction %u32 %u32ptr\n"
2389                 "%unitf     = OpTypeFunction %u32\n"
2390
2391                 "%id        = OpVariable %uvec3ptr Input\n"
2392                 "%zero      = OpConstant %u32 0\n"
2393                 "%one       = OpConstant %u32 1\n"
2394                 "%two       = OpConstant %u32 2\n"
2395                 "%three     = OpConstant %u32 3\n"
2396                 "%four      = OpConstant %u32 4\n"
2397                 "%five      = OpConstant %u32 5\n"
2398                 "%hundred   = OpConstant %u32 100\n"
2399                 "%thousand  = OpConstant %u32 1000\n"
2400
2401                 + string(getComputeAsmInputOutputBuffer()) +
2402
2403                 // Main()
2404                 "%main   = OpFunction %void None %voidf\n"
2405                 "%main_entry  = OpLabel\n"
2406                 "%v_thousand  = OpVariable %u32ptr Function %thousand\n"
2407                 "%idval       = OpLoad %uvec3 %id\n"
2408                 "%x           = OpCompositeExtract %u32 %idval 0\n"
2409                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
2410                 "%inval       = OpLoad %f32 %inloc\n"
2411                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
2412                 "%ret_const5  = OpFunctionCall %u32 %func_const5\n"
2413                 "%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
2414                 "%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
2415                 "               OpSelectionMerge %if_end None\n"
2416                 "               OpBranchConditional %cmp_gt %if_true %if_false\n"
2417                 "%if_true     = OpLabel\n"
2418                 "%negate      = OpFNegate %f32 %inval\n"
2419                 "               OpStore %outloc %negate\n"
2420                 "               OpBranch %if_end\n"
2421                 "%if_false    = OpLabel\n"
2422                 "               OpUnreachable\n" // Unreachable else branch for if statement
2423                 "%if_end      = OpLabel\n"
2424                 "               OpReturn\n"
2425                 "               OpFunctionEnd\n"
2426
2427                 // not_called_function()
2428                 "%func_not_called_func  = OpFunction %void None %voidf\n"
2429                 "%not_called_func_entry = OpLabel\n"
2430                 "                         OpUnreachable\n" // Unreachable entry block in not called static function
2431                 "                         OpFunctionEnd\n"
2432
2433                 // modulo4()
2434                 "%func_modulo4  = OpFunction %u32 None %uintfuint\n"
2435                 "%valptr        = OpFunctionParameter %u32ptr\n"
2436                 "%modulo4_entry = OpLabel\n"
2437                 "%val           = OpLoad %u32 %valptr\n"
2438                 "%modulo        = OpUMod %u32 %val %four\n"
2439                 "                 OpSelectionMerge %switch_merge None\n"
2440                 "                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
2441                 "%case0         = OpLabel\n"
2442                 "                 OpReturnValue %three\n"
2443                 "%case1         = OpLabel\n"
2444                 "                 OpReturnValue %two\n"
2445                 "%case2         = OpLabel\n"
2446                 "                 OpReturnValue %one\n"
2447                 "%case3         = OpLabel\n"
2448                 "                 OpReturnValue %zero\n"
2449                 "%default       = OpLabel\n"
2450                 "                 OpUnreachable\n" // Unreachable default case for switch statement
2451                 "%switch_merge  = OpLabel\n"
2452                 "                 OpUnreachable\n" // Unreachable merge block for switch statement
2453                 "                 OpFunctionEnd\n"
2454
2455                 // const5()
2456                 "%func_const5  = OpFunction %u32 None %unitf\n"
2457                 "%const5_entry = OpLabel\n"
2458                 "                OpReturnValue %five\n"
2459                 "%unreachable  = OpLabel\n"
2460                 "                OpUnreachable\n" // Unreachable block in function
2461                 "                OpFunctionEnd\n";
2462         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2463         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2464         spec.numWorkGroups = IVec3(numElements, 1, 1);
2465
2466         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
2467
2468         return group.release();
2469 }
2470
2471 // Assembly code used for testing decoration group is based on GLSL source code:
2472 //
2473 // #version 430
2474 //
2475 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
2476 //   float elements[];
2477 // } input_data0;
2478 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
2479 //   float elements[];
2480 // } input_data1;
2481 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
2482 //   float elements[];
2483 // } input_data2;
2484 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
2485 //   float elements[];
2486 // } input_data3;
2487 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
2488 //   float elements[];
2489 // } input_data4;
2490 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
2491 //   float elements[];
2492 // } output_data;
2493 //
2494 // void main() {
2495 //   uint x = gl_GlobalInvocationID.x;
2496 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
2497 // }
2498 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
2499 {
2500         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
2501         ComputeShaderSpec                               spec;
2502         de::Random                                              rnd                             (deStringHash(group->getName()));
2503         const int                                               numElements             = 100;
2504         vector<float>                                   inputFloats0    (numElements, 0);
2505         vector<float>                                   inputFloats1    (numElements, 0);
2506         vector<float>                                   inputFloats2    (numElements, 0);
2507         vector<float>                                   inputFloats3    (numElements, 0);
2508         vector<float>                                   inputFloats4    (numElements, 0);
2509         vector<float>                                   outputFloats    (numElements, 0);
2510
2511         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
2512         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
2513         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
2514         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
2515         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
2516
2517         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2518         floorAll(inputFloats0);
2519         floorAll(inputFloats1);
2520         floorAll(inputFloats2);
2521         floorAll(inputFloats3);
2522         floorAll(inputFloats4);
2523
2524         for (size_t ndx = 0; ndx < numElements; ++ndx)
2525                 outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
2526
2527         spec.assembly =
2528                 string(getComputeAsmShaderPreamble()) +
2529
2530                 "OpSource GLSL 430\n"
2531                 "OpName %main \"main\"\n"
2532                 "OpName %id \"gl_GlobalInvocationID\"\n"
2533
2534                 // Not using group decoration on variable.
2535                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2536                 // Not using group decoration on type.
2537                 "OpDecorate %f32arr ArrayStride 4\n"
2538
2539                 "OpDecorate %groups BufferBlock\n"
2540                 "OpDecorate %groupm Offset 0\n"
2541                 "%groups = OpDecorationGroup\n"
2542                 "%groupm = OpDecorationGroup\n"
2543
2544                 // Group decoration on multiple structs.
2545                 "OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
2546                 // Group decoration on multiple struct members.
2547                 "OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
2548
2549                 "OpDecorate %group1 DescriptorSet 0\n"
2550                 "OpDecorate %group3 DescriptorSet 0\n"
2551                 "OpDecorate %group3 NonWritable\n"
2552                 "OpDecorate %group3 Restrict\n"
2553                 "%group0 = OpDecorationGroup\n"
2554                 "%group1 = OpDecorationGroup\n"
2555                 "%group3 = OpDecorationGroup\n"
2556
2557                 // Applying the same decoration group multiple times.
2558                 "OpGroupDecorate %group1 %outdata\n"
2559                 "OpGroupDecorate %group1 %outdata\n"
2560                 "OpGroupDecorate %group1 %outdata\n"
2561                 "OpDecorate %outdata DescriptorSet 0\n"
2562                 "OpDecorate %outdata Binding 5\n"
2563                 // Applying decoration group containing nothing.
2564                 "OpGroupDecorate %group0 %indata0\n"
2565                 "OpDecorate %indata0 DescriptorSet 0\n"
2566                 "OpDecorate %indata0 Binding 0\n"
2567                 // Applying decoration group containing one decoration.
2568                 "OpGroupDecorate %group1 %indata1\n"
2569                 "OpDecorate %indata1 Binding 1\n"
2570                 // Applying decoration group containing multiple decorations.
2571                 "OpGroupDecorate %group3 %indata2 %indata3\n"
2572                 "OpDecorate %indata2 Binding 2\n"
2573                 "OpDecorate %indata3 Binding 3\n"
2574                 // Applying multiple decoration groups (with overlapping).
2575                 "OpGroupDecorate %group0 %indata4\n"
2576                 "OpGroupDecorate %group1 %indata4\n"
2577                 "OpGroupDecorate %group3 %indata4\n"
2578                 "OpDecorate %indata4 Binding 4\n"
2579
2580                 + string(getComputeAsmCommonTypes()) +
2581
2582                 "%id   = OpVariable %uvec3ptr Input\n"
2583                 "%zero = OpConstant %i32 0\n"
2584
2585                 "%outbuf    = OpTypeStruct %f32arr\n"
2586                 "%outbufptr = OpTypePointer Uniform %outbuf\n"
2587                 "%outdata   = OpVariable %outbufptr Uniform\n"
2588                 "%inbuf0    = OpTypeStruct %f32arr\n"
2589                 "%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
2590                 "%indata0   = OpVariable %inbuf0ptr Uniform\n"
2591                 "%inbuf1    = OpTypeStruct %f32arr\n"
2592                 "%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
2593                 "%indata1   = OpVariable %inbuf1ptr Uniform\n"
2594                 "%inbuf2    = OpTypeStruct %f32arr\n"
2595                 "%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
2596                 "%indata2   = OpVariable %inbuf2ptr Uniform\n"
2597                 "%inbuf3    = OpTypeStruct %f32arr\n"
2598                 "%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
2599                 "%indata3   = OpVariable %inbuf3ptr Uniform\n"
2600                 "%inbuf4    = OpTypeStruct %f32arr\n"
2601                 "%inbufptr  = OpTypePointer Uniform %inbuf4\n"
2602                 "%indata4   = OpVariable %inbufptr Uniform\n"
2603
2604                 "%main   = OpFunction %void None %voidf\n"
2605                 "%label  = OpLabel\n"
2606                 "%idval  = OpLoad %uvec3 %id\n"
2607                 "%x      = OpCompositeExtract %u32 %idval 0\n"
2608                 "%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
2609                 "%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
2610                 "%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
2611                 "%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
2612                 "%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
2613                 "%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
2614                 "%inval0 = OpLoad %f32 %inloc0\n"
2615                 "%inval1 = OpLoad %f32 %inloc1\n"
2616                 "%inval2 = OpLoad %f32 %inloc2\n"
2617                 "%inval3 = OpLoad %f32 %inloc3\n"
2618                 "%inval4 = OpLoad %f32 %inloc4\n"
2619                 "%add0   = OpFAdd %f32 %inval0 %inval1\n"
2620                 "%add1   = OpFAdd %f32 %add0 %inval2\n"
2621                 "%add2   = OpFAdd %f32 %add1 %inval3\n"
2622                 "%add    = OpFAdd %f32 %add2 %inval4\n"
2623                 "          OpStore %outloc %add\n"
2624                 "          OpReturn\n"
2625                 "          OpFunctionEnd\n";
2626         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
2627         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
2628         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2629         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2630         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2631         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2632         spec.numWorkGroups = IVec3(numElements, 1, 1);
2633
2634         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
2635
2636         return group.release();
2637 }
2638
2639 struct SpecConstantTwoIntCase
2640 {
2641         const char*             caseName;
2642         const char*             scDefinition0;
2643         const char*             scDefinition1;
2644         const char*             scResultType;
2645         const char*             scOperation;
2646         deInt32                 scActualValue0;
2647         deInt32                 scActualValue1;
2648         const char*             resultOperation;
2649         vector<deInt32> expectedOutput;
2650         deInt32                 scActualValueLength;
2651
2652                                         SpecConstantTwoIntCase (const char* name,
2653                                                                                         const char* definition0,
2654                                                                                         const char* definition1,
2655                                                                                         const char* resultType,
2656                                                                                         const char* operation,
2657                                                                                         deInt32 value0,
2658                                                                                         deInt32 value1,
2659                                                                                         const char* resultOp,
2660                                                                                         const vector<deInt32>& output,
2661                                                                                         const deInt32   valueLength = sizeof(deInt32))
2662                                                 : caseName                              (name)
2663                                                 , scDefinition0                 (definition0)
2664                                                 , scDefinition1                 (definition1)
2665                                                 , scResultType                  (resultType)
2666                                                 , scOperation                   (operation)
2667                                                 , scActualValue0                (value0)
2668                                                 , scActualValue1                (value1)
2669                                                 , resultOperation               (resultOp)
2670                                                 , expectedOutput                (output)
2671                                                 , scActualValueLength   (valueLength)
2672                                                 {}
2673 };
2674
2675 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
2676 {
2677         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
2678         vector<SpecConstantTwoIntCase>  cases;
2679         de::Random                                              rnd                             (deStringHash(group->getName()));
2680         const int                                               numElements             = 100;
2681         const deInt32                                   p1AsFloat16             = 0x3c00; // +1(fp16) == 0 01111 0000000000 == 0011 1100 0000 0000
2682         vector<deInt32>                                 inputInts               (numElements, 0);
2683         vector<deInt32>                                 outputInts1             (numElements, 0);
2684         vector<deInt32>                                 outputInts2             (numElements, 0);
2685         vector<deInt32>                                 outputInts3             (numElements, 0);
2686         vector<deInt32>                                 outputInts4             (numElements, 0);
2687         const StringTemplate                    shaderTemplate  (
2688                 "${CAPABILITIES:opt}"
2689                 + string(getComputeAsmShaderPreamble()) +
2690
2691                 "OpName %main           \"main\"\n"
2692                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2693
2694                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2695                 "OpDecorate %sc_0  SpecId 0\n"
2696                 "OpDecorate %sc_1  SpecId 1\n"
2697                 "OpDecorate %i32arr ArrayStride 4\n"
2698
2699                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2700
2701                 "${OPTYPE_DEFINITIONS:opt}"
2702                 "%buf     = OpTypeStruct %i32arr\n"
2703                 "%bufptr  = OpTypePointer Uniform %buf\n"
2704                 "%indata    = OpVariable %bufptr Uniform\n"
2705                 "%outdata   = OpVariable %bufptr Uniform\n"
2706
2707                 "%id        = OpVariable %uvec3ptr Input\n"
2708                 "%zero      = OpConstant %i32 0\n"
2709
2710                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
2711                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
2712                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2713
2714                 "%main      = OpFunction %void None %voidf\n"
2715                 "%label     = OpLabel\n"
2716                 "${TYPE_CONVERT:opt}"
2717                 "%idval     = OpLoad %uvec3 %id\n"
2718                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2719                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2720                 "%inval     = OpLoad %i32 %inloc\n"
2721                 "%final     = ${GEN_RESULT}\n"
2722                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2723                 "             OpStore %outloc %final\n"
2724                 "             OpReturn\n"
2725                 "             OpFunctionEnd\n");
2726
2727         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2728
2729         for (size_t ndx = 0; ndx < numElements; ++ndx)
2730         {
2731                 outputInts1[ndx] = inputInts[ndx] + 42;
2732                 outputInts2[ndx] = inputInts[ndx];
2733                 outputInts3[ndx] = inputInts[ndx] - 11200;
2734                 outputInts4[ndx] = inputInts[ndx] + 1;
2735         }
2736
2737         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
2738         const char addSc32ToInput[]             = "OpIAdd %i32 %inval %sc_final32";
2739         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
2740         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
2741
2742         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
2743         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
2744         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
2745         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
2746         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
2747         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2748         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2749         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
2750         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
2751         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
2752         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
2753         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2754         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2755         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
2756         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
2757         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
2758         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2759         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
2760         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
2761         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
2762         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2763         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
2764         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
2765         cases.push_back(SpecConstantTwoIntCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                     42,             24,             selectTrueUsingSc,      outputInts2));
2766         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2767         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2768         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2769         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2770         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
2771         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
2772         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
2773         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
2774         cases.push_back(SpecConstantTwoIntCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                           -11200, 0,              addSc32ToInput,         outputInts3));
2775         // -969998336 stored as 32-bit two's complement is the binary representation of -11200 as IEEE-754 Float
2776         cases.push_back(SpecConstantTwoIntCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                           -969998336, 0,  addSc32ToInput,         outputInts3));
2777         cases.push_back(SpecConstantTwoIntCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                           p1AsFloat16, 0, addSc32ToInput,         outputInts4, sizeof(deFloat16)));
2778
2779         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2780         {
2781                 map<string, string>             specializations;
2782                 ComputeShaderSpec               spec;
2783
2784                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
2785                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
2786                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
2787                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
2788                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
2789
2790                 // Special SPIR-V code for SConvert-case
2791                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
2792                 {
2793                         spec.requestedVulkanFeatures.coreFeatures.shaderInt16   = VK_TRUE;
2794                         specializations["CAPABILITIES"]                                                 = "OpCapability Int16\n";                                                       // Adds 16-bit integer capability
2795                         specializations["OPTYPE_DEFINITIONS"]                                   = "%i16 = OpTypeInt 16 1\n";                                            // Adds 16-bit integer type
2796                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpSConvert %i32 %sc_final\n";          // Converts 16-bit integer to 32-bit integer
2797                 }
2798
2799                 // Special SPIR-V code for FConvert-case
2800                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
2801                 {
2802                         spec.requestedVulkanFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
2803                         specializations["CAPABILITIES"]                                                 = "OpCapability Float64\n";                                                     // Adds 64-bit float capability
2804                         specializations["OPTYPE_DEFINITIONS"]                                   = "%f64 = OpTypeFloat 64\n";                                            // Adds 64-bit float type
2805                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 64-bit float to 32-bit integer
2806                 }
2807
2808                 // Special SPIR-V code for FConvert-case for 16-bit floats
2809                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
2810                 {
2811                         spec.extensions.push_back("VK_KHR_shader_float16_int8");
2812                         spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
2813                         specializations["CAPABILITIES"]                 = "OpCapability Float16\n";                                                     // Adds 16-bit float capability
2814                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                                            // Adds 16-bit float type
2815                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 16-bit float to 32-bit integer
2816                 }
2817
2818                 spec.assembly = shaderTemplate.specialize(specializations);
2819                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2820                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2821                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2822                 spec.specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
2823                 spec.specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
2824
2825                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec));
2826         }
2827
2828         ComputeShaderSpec                               spec;
2829
2830         spec.assembly =
2831                 string(getComputeAsmShaderPreamble()) +
2832
2833                 "OpName %main           \"main\"\n"
2834                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2835
2836                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2837                 "OpDecorate %sc_0  SpecId 0\n"
2838                 "OpDecorate %sc_1  SpecId 1\n"
2839                 "OpDecorate %sc_2  SpecId 2\n"
2840                 "OpDecorate %i32arr ArrayStride 4\n"
2841
2842                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2843
2844                 "%ivec3       = OpTypeVector %i32 3\n"
2845                 "%buf         = OpTypeStruct %i32arr\n"
2846                 "%bufptr      = OpTypePointer Uniform %buf\n"
2847                 "%indata      = OpVariable %bufptr Uniform\n"
2848                 "%outdata     = OpVariable %bufptr Uniform\n"
2849
2850                 "%id          = OpVariable %uvec3ptr Input\n"
2851                 "%zero        = OpConstant %i32 0\n"
2852                 "%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
2853                 "%vec3_undef  = OpUndef %ivec3\n"
2854
2855                 "%sc_0        = OpSpecConstant %i32 0\n"
2856                 "%sc_1        = OpSpecConstant %i32 0\n"
2857                 "%sc_2        = OpSpecConstant %i32 0\n"
2858                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"                                                 // (sc_0, 0, 0)
2859                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"                                                 // (0, sc_1, 0)
2860                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"                                                 // (0, 0, sc_2)
2861                 "%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
2862                 "%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
2863                 "%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
2864                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
2865                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
2866                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
2867                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
2868                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
2869                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
2870                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"                                                              // (sc_2 - sc_0) * sc_1
2871
2872                 "%main      = OpFunction %void None %voidf\n"
2873                 "%label     = OpLabel\n"
2874                 "%idval     = OpLoad %uvec3 %id\n"
2875                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2876                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2877                 "%inval     = OpLoad %i32 %inloc\n"
2878                 "%final     = OpIAdd %i32 %inval %sc_final\n"
2879                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2880                 "             OpStore %outloc %final\n"
2881                 "             OpReturn\n"
2882                 "             OpFunctionEnd\n";
2883         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2884         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
2885         spec.numWorkGroups = IVec3(numElements, 1, 1);
2886         spec.specConstants.append<deInt32>(123);
2887         spec.specConstants.append<deInt32>(56);
2888         spec.specConstants.append<deInt32>(-77);
2889
2890         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
2891
2892         return group.release();
2893 }
2894
2895 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
2896 {
2897         ComputeShaderSpec       specInt;
2898         ComputeShaderSpec       specFloat;
2899         ComputeShaderSpec       specFloat16;
2900         ComputeShaderSpec       specVec3;
2901         ComputeShaderSpec       specMat4;
2902         ComputeShaderSpec       specArray;
2903         ComputeShaderSpec       specStruct;
2904         de::Random                      rnd                             (deStringHash(group->getName()));
2905         const int                       numElements             = 100;
2906         vector<float>           inputFloats             (numElements, 0);
2907         vector<float>           outputFloats    (numElements, 0);
2908         vector<deFloat16>       inputFloats16   (numElements, 0);
2909         vector<deFloat16>       outputFloats16  (numElements, 0);
2910
2911         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
2912
2913         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2914         floorAll(inputFloats);
2915
2916         for (size_t ndx = 0; ndx < numElements; ++ndx)
2917         {
2918                 // Just check if the value is positive or not
2919                 outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
2920         }
2921
2922         for (size_t ndx = 0; ndx < numElements; ++ndx)
2923         {
2924                 inputFloats16[ndx] = tcu::Float16(inputFloats[ndx]).bits();
2925                 outputFloats16[ndx] = tcu::Float16(outputFloats[ndx]).bits();
2926         }
2927
2928         // All of the tests are of the form:
2929         //
2930         // testtype r
2931         //
2932         // if (inputdata > 0)
2933         //   r = 1
2934         // else
2935         //   r = -1
2936         //
2937         // return (float)r
2938
2939         specFloat.assembly =
2940                 string(getComputeAsmShaderPreamble()) +
2941
2942                 "OpSource GLSL 430\n"
2943                 "OpName %main \"main\"\n"
2944                 "OpName %id \"gl_GlobalInvocationID\"\n"
2945
2946                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2947
2948                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2949
2950                 "%id = OpVariable %uvec3ptr Input\n"
2951                 "%zero       = OpConstant %i32 0\n"
2952                 "%float_0    = OpConstant %f32 0.0\n"
2953                 "%float_1    = OpConstant %f32 1.0\n"
2954                 "%float_n1   = OpConstant %f32 -1.0\n"
2955
2956                 "%main     = OpFunction %void None %voidf\n"
2957                 "%entry    = OpLabel\n"
2958                 "%idval    = OpLoad %uvec3 %id\n"
2959                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2960                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2961                 "%inval    = OpLoad %f32 %inloc\n"
2962
2963                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2964                 "            OpSelectionMerge %cm None\n"
2965                 "            OpBranchConditional %comp %tb %fb\n"
2966                 "%tb       = OpLabel\n"
2967                 "            OpBranch %cm\n"
2968                 "%fb       = OpLabel\n"
2969                 "            OpBranch %cm\n"
2970                 "%cm       = OpLabel\n"
2971                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
2972
2973                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2974                 "            OpStore %outloc %res\n"
2975                 "            OpReturn\n"
2976
2977                 "            OpFunctionEnd\n";
2978         specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2979         specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2980         specFloat.numWorkGroups = IVec3(numElements, 1, 1);
2981
2982         specFloat16.assembly =
2983                 "OpCapability Shader\n"
2984                 "OpCapability StorageUniformBufferBlock16\n"
2985                 "OpExtension \"SPV_KHR_16bit_storage\"\n"
2986                 "OpMemoryModel Logical GLSL450\n"
2987                 "OpEntryPoint GLCompute %main \"main\" %id\n"
2988                 "OpExecutionMode %main LocalSize 1 1 1\n"
2989
2990                 "OpSource GLSL 430\n"
2991                 "OpName %main \"main\"\n"
2992                 "OpName %id \"gl_GlobalInvocationID\"\n"
2993
2994                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2995
2996                 "OpDecorate %buf BufferBlock\n"
2997                 "OpDecorate %indata DescriptorSet 0\n"
2998                 "OpDecorate %indata Binding 0\n"
2999                 "OpDecorate %outdata DescriptorSet 0\n"
3000                 "OpDecorate %outdata Binding 1\n"
3001                 "OpDecorate %f16arr ArrayStride 2\n"
3002                 "OpMemberDecorate %buf 0 Offset 0\n"
3003
3004                 "%f16      = OpTypeFloat 16\n"
3005                 "%f16ptr   = OpTypePointer Uniform %f16\n"
3006                 "%f16arr   = OpTypeRuntimeArray %f16\n"
3007
3008                 + string(getComputeAsmCommonTypes()) +
3009
3010                 "%buf      = OpTypeStruct %f16arr\n"
3011                 "%bufptr   = OpTypePointer Uniform %buf\n"
3012                 "%indata   = OpVariable %bufptr Uniform\n"
3013                 "%outdata  = OpVariable %bufptr Uniform\n"
3014
3015                 "%id       = OpVariable %uvec3ptr Input\n"
3016                 "%zero     = OpConstant %i32 0\n"
3017                 "%float_0  = OpConstant %f16 0.0\n"
3018                 "%float_1  = OpConstant %f16 1.0\n"
3019                 "%float_n1 = OpConstant %f16 -1.0\n"
3020
3021                 "%main     = OpFunction %void None %voidf\n"
3022                 "%entry    = OpLabel\n"
3023                 "%idval    = OpLoad %uvec3 %id\n"
3024                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3025                 "%inloc    = OpAccessChain %f16ptr %indata %zero %x\n"
3026                 "%inval    = OpLoad %f16 %inloc\n"
3027
3028                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3029                 "            OpSelectionMerge %cm None\n"
3030                 "            OpBranchConditional %comp %tb %fb\n"
3031                 "%tb       = OpLabel\n"
3032                 "            OpBranch %cm\n"
3033                 "%fb       = OpLabel\n"
3034                 "            OpBranch %cm\n"
3035                 "%cm       = OpLabel\n"
3036                 "%res      = OpPhi %f16 %float_1 %tb %float_n1 %fb\n"
3037
3038                 "%outloc   = OpAccessChain %f16ptr %outdata %zero %x\n"
3039                 "            OpStore %outloc %res\n"
3040                 "            OpReturn\n"
3041
3042                 "            OpFunctionEnd\n";
3043         specFloat16.inputs.push_back(BufferSp(new Float16Buffer(inputFloats16)));
3044         specFloat16.outputs.push_back(BufferSp(new Float16Buffer(outputFloats16)));
3045         specFloat16.numWorkGroups = IVec3(numElements, 1, 1);
3046         specFloat16.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
3047         specFloat16.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
3048
3049         specMat4.assembly =
3050                 string(getComputeAsmShaderPreamble()) +
3051
3052                 "OpSource GLSL 430\n"
3053                 "OpName %main \"main\"\n"
3054                 "OpName %id \"gl_GlobalInvocationID\"\n"
3055
3056                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3057
3058                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3059
3060                 "%id = OpVariable %uvec3ptr Input\n"
3061                 "%v4f32      = OpTypeVector %f32 4\n"
3062                 "%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
3063                 "%zero       = OpConstant %i32 0\n"
3064                 "%float_0    = OpConstant %f32 0.0\n"
3065                 "%float_1    = OpConstant %f32 1.0\n"
3066                 "%float_n1   = OpConstant %f32 -1.0\n"
3067                 "%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
3068                 "%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
3069                 "%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
3070                 "%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
3071                 "%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
3072                 "%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
3073                 "%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
3074                 "%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
3075                 "%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
3076                 "%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
3077
3078                 "%main     = OpFunction %void None %voidf\n"
3079                 "%entry    = OpLabel\n"
3080                 "%idval    = OpLoad %uvec3 %id\n"
3081                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3082                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3083                 "%inval    = OpLoad %f32 %inloc\n"
3084
3085                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3086                 "            OpSelectionMerge %cm None\n"
3087                 "            OpBranchConditional %comp %tb %fb\n"
3088                 "%tb       = OpLabel\n"
3089                 "            OpBranch %cm\n"
3090                 "%fb       = OpLabel\n"
3091                 "            OpBranch %cm\n"
3092                 "%cm       = OpLabel\n"
3093                 "%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
3094                 "%res      = OpCompositeExtract %f32 %mres 2 2\n"
3095
3096                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3097                 "            OpStore %outloc %res\n"
3098                 "            OpReturn\n"
3099
3100                 "            OpFunctionEnd\n";
3101         specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3102         specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3103         specMat4.numWorkGroups = IVec3(numElements, 1, 1);
3104
3105         specVec3.assembly =
3106                 string(getComputeAsmShaderPreamble()) +
3107
3108                 "OpSource GLSL 430\n"
3109                 "OpName %main \"main\"\n"
3110                 "OpName %id \"gl_GlobalInvocationID\"\n"
3111
3112                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3113
3114                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3115
3116                 "%id = OpVariable %uvec3ptr Input\n"
3117                 "%zero       = OpConstant %i32 0\n"
3118                 "%float_0    = OpConstant %f32 0.0\n"
3119                 "%float_1    = OpConstant %f32 1.0\n"
3120                 "%float_n1   = OpConstant %f32 -1.0\n"
3121                 "%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
3122                 "%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
3123
3124                 "%main     = OpFunction %void None %voidf\n"
3125                 "%entry    = OpLabel\n"
3126                 "%idval    = OpLoad %uvec3 %id\n"
3127                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3128                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3129                 "%inval    = OpLoad %f32 %inloc\n"
3130
3131                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3132                 "            OpSelectionMerge %cm None\n"
3133                 "            OpBranchConditional %comp %tb %fb\n"
3134                 "%tb       = OpLabel\n"
3135                 "            OpBranch %cm\n"
3136                 "%fb       = OpLabel\n"
3137                 "            OpBranch %cm\n"
3138                 "%cm       = OpLabel\n"
3139                 "%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
3140                 "%res      = OpCompositeExtract %f32 %vres 2\n"
3141
3142                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3143                 "            OpStore %outloc %res\n"
3144                 "            OpReturn\n"
3145
3146                 "            OpFunctionEnd\n";
3147         specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3148         specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3149         specVec3.numWorkGroups = IVec3(numElements, 1, 1);
3150
3151         specInt.assembly =
3152                 string(getComputeAsmShaderPreamble()) +
3153
3154                 "OpSource GLSL 430\n"
3155                 "OpName %main \"main\"\n"
3156                 "OpName %id \"gl_GlobalInvocationID\"\n"
3157
3158                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3159
3160                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3161
3162                 "%id = OpVariable %uvec3ptr Input\n"
3163                 "%zero       = OpConstant %i32 0\n"
3164                 "%float_0    = OpConstant %f32 0.0\n"
3165                 "%i1         = OpConstant %i32 1\n"
3166                 "%i2         = OpConstant %i32 -1\n"
3167
3168                 "%main     = OpFunction %void None %voidf\n"
3169                 "%entry    = OpLabel\n"
3170                 "%idval    = OpLoad %uvec3 %id\n"
3171                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3172                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3173                 "%inval    = OpLoad %f32 %inloc\n"
3174
3175                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3176                 "            OpSelectionMerge %cm None\n"
3177                 "            OpBranchConditional %comp %tb %fb\n"
3178                 "%tb       = OpLabel\n"
3179                 "            OpBranch %cm\n"
3180                 "%fb       = OpLabel\n"
3181                 "            OpBranch %cm\n"
3182                 "%cm       = OpLabel\n"
3183                 "%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
3184                 "%res      = OpConvertSToF %f32 %ires\n"
3185
3186                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3187                 "            OpStore %outloc %res\n"
3188                 "            OpReturn\n"
3189
3190                 "            OpFunctionEnd\n";
3191         specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3192         specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3193         specInt.numWorkGroups = IVec3(numElements, 1, 1);
3194
3195         specArray.assembly =
3196                 string(getComputeAsmShaderPreamble()) +
3197
3198                 "OpSource GLSL 430\n"
3199                 "OpName %main \"main\"\n"
3200                 "OpName %id \"gl_GlobalInvocationID\"\n"
3201
3202                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3203
3204                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3205
3206                 "%id = OpVariable %uvec3ptr Input\n"
3207                 "%zero       = OpConstant %i32 0\n"
3208                 "%u7         = OpConstant %u32 7\n"
3209                 "%float_0    = OpConstant %f32 0.0\n"
3210                 "%float_1    = OpConstant %f32 1.0\n"
3211                 "%float_n1   = OpConstant %f32 -1.0\n"
3212                 "%f32a7      = OpTypeArray %f32 %u7\n"
3213                 "%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
3214                 "%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
3215                 "%main     = OpFunction %void None %voidf\n"
3216                 "%entry    = OpLabel\n"
3217                 "%idval    = OpLoad %uvec3 %id\n"
3218                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3219                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3220                 "%inval    = OpLoad %f32 %inloc\n"
3221
3222                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3223                 "            OpSelectionMerge %cm None\n"
3224                 "            OpBranchConditional %comp %tb %fb\n"
3225                 "%tb       = OpLabel\n"
3226                 "            OpBranch %cm\n"
3227                 "%fb       = OpLabel\n"
3228                 "            OpBranch %cm\n"
3229                 "%cm       = OpLabel\n"
3230                 "%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
3231                 "%res      = OpCompositeExtract %f32 %ares 5\n"
3232
3233                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3234                 "            OpStore %outloc %res\n"
3235                 "            OpReturn\n"
3236
3237                 "            OpFunctionEnd\n";
3238         specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3239         specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3240         specArray.numWorkGroups = IVec3(numElements, 1, 1);
3241
3242         specStruct.assembly =
3243                 string(getComputeAsmShaderPreamble()) +
3244
3245                 "OpSource GLSL 430\n"
3246                 "OpName %main \"main\"\n"
3247                 "OpName %id \"gl_GlobalInvocationID\"\n"
3248
3249                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3250
3251                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3252
3253                 "%id = OpVariable %uvec3ptr Input\n"
3254                 "%zero       = OpConstant %i32 0\n"
3255                 "%float_0    = OpConstant %f32 0.0\n"
3256                 "%float_1    = OpConstant %f32 1.0\n"
3257                 "%float_n1   = OpConstant %f32 -1.0\n"
3258
3259                 "%v2f32      = OpTypeVector %f32 2\n"
3260                 "%Data2      = OpTypeStruct %f32 %v2f32\n"
3261                 "%Data       = OpTypeStruct %Data2 %f32\n"
3262
3263                 "%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
3264                 "%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
3265                 "%s1         = OpConstantComposite %Data %in1b %float_1\n"
3266                 "%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
3267                 "%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
3268                 "%s2         = OpConstantComposite %Data %in2b %float_n1\n"
3269
3270                 "%main     = OpFunction %void None %voidf\n"
3271                 "%entry    = OpLabel\n"
3272                 "%idval    = OpLoad %uvec3 %id\n"
3273                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3274                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3275                 "%inval    = OpLoad %f32 %inloc\n"
3276
3277                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3278                 "            OpSelectionMerge %cm None\n"
3279                 "            OpBranchConditional %comp %tb %fb\n"
3280                 "%tb       = OpLabel\n"
3281                 "            OpBranch %cm\n"
3282                 "%fb       = OpLabel\n"
3283                 "            OpBranch %cm\n"
3284                 "%cm       = OpLabel\n"
3285                 "%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
3286                 "%res      = OpCompositeExtract %f32 %sres 0 0\n"
3287
3288                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3289                 "            OpStore %outloc %res\n"
3290                 "            OpReturn\n"
3291
3292                 "            OpFunctionEnd\n";
3293         specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3294         specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3295         specStruct.numWorkGroups = IVec3(numElements, 1, 1);
3296
3297         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
3298         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
3299         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float16", "OpPhi with 16bit float variables", specFloat16));
3300         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
3301         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
3302         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
3303         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
3304 }
3305
3306 string generateConstantDefinitions (int count)
3307 {
3308         std::ostringstream      r;
3309         for (int i = 0; i < count; i++)
3310                 r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
3311         r << "\n";
3312         return r.str();
3313 }
3314
3315 string generateSwitchCases (int count)
3316 {
3317         std::ostringstream      r;
3318         for (int i = 0; i < count; i++)
3319                 r << " " << i << " %case" << i;
3320         r << "\n";
3321         return r.str();
3322 }
3323
3324 string generateSwitchTargets (int count)
3325 {
3326         std::ostringstream      r;
3327         for (int i = 0; i < count; i++)
3328                 r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3329         r << "\n";
3330         return r.str();
3331 }
3332
3333 string generateOpPhiParams (int count)
3334 {
3335         std::ostringstream      r;
3336         for (int i = 0; i < count; i++)
3337                 r << " %cf" << (i * 10 + 5) << " %case" << i;
3338         r << "\n";
3339         return r.str();
3340 }
3341
3342 string generateIntWidth (int value)
3343 {
3344         std::ostringstream      r;
3345         r << value;
3346         return r.str();
3347 }
3348
3349 // Expand input string by injecting "ABC" between the input
3350 // string characters. The acc/add/treshold parameters are used
3351 // to skip some of the injections to make the result less
3352 // uniform (and a lot shorter).
3353 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3354 {
3355         std::ostringstream      res;
3356         const char*                     p = s.c_str();
3357
3358         while (*p)
3359         {
3360                 res << *p;
3361                 acc += add;
3362                 if (acc > treshold)
3363                 {
3364                         acc -= treshold;
3365                         res << "ABC";
3366                 }
3367                 p++;
3368         }
3369         return res.str();
3370 }
3371
3372 // Calculate expected result based on the code string
3373 float calcOpPhiCase5 (float val, const string& s)
3374 {
3375         const char*             p               = s.c_str();
3376         float                   x[8];
3377         bool                    b[8];
3378         const float             tv[8]   = { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3379         const float             v               = deFloatAbs(val);
3380         float                   res             = 0;
3381         int                             depth   = -1;
3382         int                             skip    = 0;
3383
3384         for (int i = 7; i >= 0; --i)
3385                 x[i] = std::fmod((float)v, (float)(2 << i));
3386         for (int i = 7; i >= 0; --i)
3387                 b[i] = x[i] > tv[i];
3388
3389         while (*p)
3390         {
3391                 if (*p == 'A')
3392                 {
3393                         depth++;
3394                         if (skip == 0 && b[depth])
3395                         {
3396                                 res++;
3397                         }
3398                         else
3399                                 skip++;
3400                 }
3401                 if (*p == 'B')
3402                 {
3403                         if (skip)
3404                                 skip--;
3405                         if (b[depth] || skip)
3406                                 skip++;
3407                 }
3408                 if (*p == 'C')
3409                 {
3410                         depth--;
3411                         if (skip)
3412                                 skip--;
3413                 }
3414                 p++;
3415         }
3416         return res;
3417 }
3418
3419 // In the code string, the letters represent the following:
3420 //
3421 // A:
3422 //     if (certain bit is set)
3423 //     {
3424 //       result++;
3425 //
3426 // B:
3427 //     } else {
3428 //
3429 // C:
3430 //     }
3431 //
3432 // examples:
3433 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3434 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3435 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3436 //
3437 // Code generation gets a bit complicated due to the else-branches,
3438 // which do not generate new values. Thus, the generator needs to
3439 // keep track of the previous variable change seen by the else
3440 // branch.
3441 string generateOpPhiCase5 (const string& s)
3442 {
3443         std::stack<int>                         idStack;
3444         std::stack<std::string>         value;
3445         std::stack<std::string>         valueLabel;
3446         std::stack<std::string>         mergeLeft;
3447         std::stack<std::string>         mergeRight;
3448         std::ostringstream                      res;
3449         const char*                                     p                       = s.c_str();
3450         int                                                     depth           = -1;
3451         int                                                     currId          = 0;
3452         int                                                     iter            = 0;
3453
3454         idStack.push(-1);
3455         value.push("%f32_0");
3456         valueLabel.push("%f32_0 %entry");
3457
3458         while (*p)
3459         {
3460                 if (*p == 'A')
3461                 {
3462                         depth++;
3463                         currId = iter;
3464                         idStack.push(currId);
3465                         res << "\tOpSelectionMerge %m" << currId << " None\n";
3466                         res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3467                         res << "%t" << currId << " = OpLabel\n";
3468                         res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3469                         std::ostringstream tag;
3470                         tag << "%rt" << currId;
3471                         value.push(tag.str());
3472                         tag << " %t" << currId;
3473                         valueLabel.push(tag.str());
3474                 }
3475
3476                 if (*p == 'B')
3477                 {
3478                         mergeLeft.push(valueLabel.top());
3479                         value.pop();
3480                         valueLabel.pop();
3481                         res << "\tOpBranch %m" << currId << "\n";
3482                         res << "%f" << currId << " = OpLabel\n";
3483                         std::ostringstream tag;
3484                         tag << value.top() << " %f" << currId;
3485                         valueLabel.pop();
3486                         valueLabel.push(tag.str());
3487                 }
3488
3489                 if (*p == 'C')
3490                 {
3491                         mergeRight.push(valueLabel.top());
3492                         res << "\tOpBranch %m" << currId << "\n";
3493                         res << "%m" << currId << " = OpLabel\n";
3494                         if (*(p + 1) == 0)
3495                                 res << "%res"; // last result goes to %res
3496                         else
3497                                 res << "%rm" << currId;
3498                         res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3499                         std::ostringstream tag;
3500                         tag << "%rm" << currId;
3501                         value.pop();
3502                         value.push(tag.str());
3503                         tag << " %m" << currId;
3504                         valueLabel.pop();
3505                         valueLabel.push(tag.str());
3506                         mergeLeft.pop();
3507                         mergeRight.pop();
3508                         depth--;
3509                         idStack.pop();
3510                         currId = idStack.top();
3511                 }
3512                 p++;
3513                 iter++;
3514         }
3515         return res.str();
3516 }
3517
3518 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3519 {
3520         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3521         ComputeShaderSpec                               spec1;
3522         ComputeShaderSpec                               spec2;
3523         ComputeShaderSpec                               spec3;
3524         ComputeShaderSpec                               spec4;
3525         ComputeShaderSpec                               spec5;
3526         de::Random                                              rnd                             (deStringHash(group->getName()));
3527         const int                                               numElements             = 100;
3528         vector<float>                                   inputFloats             (numElements, 0);
3529         vector<float>                                   outputFloats1   (numElements, 0);
3530         vector<float>                                   outputFloats2   (numElements, 0);
3531         vector<float>                                   outputFloats3   (numElements, 0);
3532         vector<float>                                   outputFloats4   (numElements, 0);
3533         vector<float>                                   outputFloats5   (numElements, 0);
3534         std::string                                             codestring              = "ABC";
3535         const int                                               test4Width              = 1024;
3536
3537         // Build case 5 code string. Each iteration makes the hierarchy more complicated.
3538         // 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3539         // shader code.
3540         for (int i = 0, acc = 0; i < 9; i++)
3541                 codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3542
3543         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3544
3545         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3546         floorAll(inputFloats);
3547
3548         for (size_t ndx = 0; ndx < numElements; ++ndx)
3549         {
3550                 switch (ndx % 3)
3551                 {
3552                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
3553                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
3554                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
3555                         default:        break;
3556                 }
3557                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3558                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3559
3560                 int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3561                 outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3562
3563                 outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3564         }
3565
3566         spec1.assembly =
3567                 string(getComputeAsmShaderPreamble()) +
3568
3569                 "OpSource GLSL 430\n"
3570                 "OpName %main \"main\"\n"
3571                 "OpName %id \"gl_GlobalInvocationID\"\n"
3572
3573                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3574
3575                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3576
3577                 "%id = OpVariable %uvec3ptr Input\n"
3578                 "%zero       = OpConstant %i32 0\n"
3579                 "%three      = OpConstant %u32 3\n"
3580                 "%constf5p5  = OpConstant %f32 5.5\n"
3581                 "%constf20p5 = OpConstant %f32 20.5\n"
3582                 "%constf1p75 = OpConstant %f32 1.75\n"
3583                 "%constf8p5  = OpConstant %f32 8.5\n"
3584                 "%constf6p5  = OpConstant %f32 6.5\n"
3585
3586                 "%main     = OpFunction %void None %voidf\n"
3587                 "%entry    = OpLabel\n"
3588                 "%idval    = OpLoad %uvec3 %id\n"
3589                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3590                 "%selector = OpUMod %u32 %x %three\n"
3591                 "            OpSelectionMerge %phi None\n"
3592                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3593
3594                 // Case 1 before OpPhi.
3595                 "%case1    = OpLabel\n"
3596                 "            OpBranch %phi\n"
3597
3598                 "%default  = OpLabel\n"
3599                 "            OpUnreachable\n"
3600
3601                 "%phi      = OpLabel\n"
3602                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3603                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3604                 "%inval    = OpLoad %f32 %inloc\n"
3605                 "%add      = OpFAdd %f32 %inval %operand\n"
3606                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3607                 "            OpStore %outloc %add\n"
3608                 "            OpReturn\n"
3609
3610                 // Case 0 after OpPhi.
3611                 "%case0    = OpLabel\n"
3612                 "            OpBranch %phi\n"
3613
3614
3615                 // Case 2 after OpPhi.
3616                 "%case2    = OpLabel\n"
3617                 "            OpBranch %phi\n"
3618
3619                 "            OpFunctionEnd\n";
3620         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3621         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3622         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3623
3624         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3625
3626         spec2.assembly =
3627                 string(getComputeAsmShaderPreamble()) +
3628
3629                 "OpName %main \"main\"\n"
3630                 "OpName %id \"gl_GlobalInvocationID\"\n"
3631
3632                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3633
3634                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3635
3636                 "%id         = OpVariable %uvec3ptr Input\n"
3637                 "%zero       = OpConstant %i32 0\n"
3638                 "%one        = OpConstant %i32 1\n"
3639                 "%three      = OpConstant %i32 3\n"
3640                 "%constf6p5  = OpConstant %f32 6.5\n"
3641
3642                 "%main       = OpFunction %void None %voidf\n"
3643                 "%entry      = OpLabel\n"
3644                 "%idval      = OpLoad %uvec3 %id\n"
3645                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3646                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3647                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3648                 "%inval      = OpLoad %f32 %inloc\n"
3649                 "              OpBranch %phi\n"
3650
3651                 "%phi        = OpLabel\n"
3652                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3653                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3654                 "%step_next  = OpIAdd %i32 %step %one\n"
3655                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3656                 "%still_loop = OpSLessThan %bool %step %three\n"
3657                 "              OpLoopMerge %exit %phi None\n"
3658                 "              OpBranchConditional %still_loop %phi %exit\n"
3659
3660                 "%exit       = OpLabel\n"
3661                 "              OpStore %outloc %accum\n"
3662                 "              OpReturn\n"
3663                 "              OpFunctionEnd\n";
3664         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3665         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3666         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3667
3668         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3669
3670         spec3.assembly =
3671                 string(getComputeAsmShaderPreamble()) +
3672
3673                 "OpName %main \"main\"\n"
3674                 "OpName %id \"gl_GlobalInvocationID\"\n"
3675
3676                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3677
3678                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3679
3680                 "%f32ptr_f   = OpTypePointer Function %f32\n"
3681                 "%id         = OpVariable %uvec3ptr Input\n"
3682                 "%true       = OpConstantTrue %bool\n"
3683                 "%false      = OpConstantFalse %bool\n"
3684                 "%zero       = OpConstant %i32 0\n"
3685                 "%constf8p5  = OpConstant %f32 8.5\n"
3686
3687                 "%main       = OpFunction %void None %voidf\n"
3688                 "%entry      = OpLabel\n"
3689                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3690                 "%idval      = OpLoad %uvec3 %id\n"
3691                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3692                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3693                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3694                 "%a_init     = OpLoad %f32 %inloc\n"
3695                 "%b_init     = OpLoad %f32 %b\n"
3696                 "              OpBranch %phi\n"
3697
3698                 "%phi        = OpLabel\n"
3699                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3700                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3701                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3702                 "              OpLoopMerge %exit %phi None\n"
3703                 "              OpBranchConditional %still_loop %phi %exit\n"
3704
3705                 "%exit       = OpLabel\n"
3706                 "%sub        = OpFSub %f32 %a_next %b_next\n"
3707                 "              OpStore %outloc %sub\n"
3708                 "              OpReturn\n"
3709                 "              OpFunctionEnd\n";
3710         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3711         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3712         spec3.numWorkGroups = IVec3(numElements, 1, 1);
3713
3714         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3715
3716         spec4.assembly =
3717                 "OpCapability Shader\n"
3718                 "%ext = OpExtInstImport \"GLSL.std.450\"\n"
3719                 "OpMemoryModel Logical GLSL450\n"
3720                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3721                 "OpExecutionMode %main LocalSize 1 1 1\n"
3722
3723                 "OpSource GLSL 430\n"
3724                 "OpName %main \"main\"\n"
3725                 "OpName %id \"gl_GlobalInvocationID\"\n"
3726
3727                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3728
3729                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3730
3731                 "%id       = OpVariable %uvec3ptr Input\n"
3732                 "%zero     = OpConstant %i32 0\n"
3733                 "%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3734
3735                 + generateConstantDefinitions(test4Width) +
3736
3737                 "%main     = OpFunction %void None %voidf\n"
3738                 "%entry    = OpLabel\n"
3739                 "%idval    = OpLoad %uvec3 %id\n"
3740                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3741                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3742                 "%inval    = OpLoad %f32 %inloc\n"
3743                 "%xf       = OpConvertUToF %f32 %x\n"
3744                 "%xm       = OpFMul %f32 %xf %inval\n"
3745                 "%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3746                 "%xi       = OpConvertFToU %u32 %xa\n"
3747                 "%selector = OpUMod %u32 %xi %cimod\n"
3748                 "            OpSelectionMerge %phi None\n"
3749                 "            OpSwitch %selector %default "
3750
3751                 + generateSwitchCases(test4Width) +
3752
3753                 "%default  = OpLabel\n"
3754                 "            OpUnreachable\n"
3755
3756                 + generateSwitchTargets(test4Width) +
3757
3758                 "%phi      = OpLabel\n"
3759                 "%result   = OpPhi %f32"
3760
3761                 + generateOpPhiParams(test4Width) +
3762
3763                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3764                 "            OpStore %outloc %result\n"
3765                 "            OpReturn\n"
3766
3767                 "            OpFunctionEnd\n";
3768         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3769         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3770         spec4.numWorkGroups = IVec3(numElements, 1, 1);
3771
3772         group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3773
3774         spec5.assembly =
3775                 "OpCapability Shader\n"
3776                 "%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3777                 "OpMemoryModel Logical GLSL450\n"
3778                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3779                 "OpExecutionMode %main LocalSize 1 1 1\n"
3780                 "%code     = OpString \"" + codestring + "\"\n"
3781
3782                 "OpSource GLSL 430\n"
3783                 "OpName %main \"main\"\n"
3784                 "OpName %id \"gl_GlobalInvocationID\"\n"
3785
3786                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3787
3788                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3789
3790                 "%id       = OpVariable %uvec3ptr Input\n"
3791                 "%zero     = OpConstant %i32 0\n"
3792                 "%f32_0    = OpConstant %f32 0.0\n"
3793                 "%f32_0_5  = OpConstant %f32 0.5\n"
3794                 "%f32_1    = OpConstant %f32 1.0\n"
3795                 "%f32_1_5  = OpConstant %f32 1.5\n"
3796                 "%f32_2    = OpConstant %f32 2.0\n"
3797                 "%f32_3_5  = OpConstant %f32 3.5\n"
3798                 "%f32_4    = OpConstant %f32 4.0\n"
3799                 "%f32_7_5  = OpConstant %f32 7.5\n"
3800                 "%f32_8    = OpConstant %f32 8.0\n"
3801                 "%f32_15_5 = OpConstant %f32 15.5\n"
3802                 "%f32_16   = OpConstant %f32 16.0\n"
3803                 "%f32_31_5 = OpConstant %f32 31.5\n"
3804                 "%f32_32   = OpConstant %f32 32.0\n"
3805                 "%f32_63_5 = OpConstant %f32 63.5\n"
3806                 "%f32_64   = OpConstant %f32 64.0\n"
3807                 "%f32_127_5 = OpConstant %f32 127.5\n"
3808                 "%f32_128  = OpConstant %f32 128.0\n"
3809                 "%f32_256  = OpConstant %f32 256.0\n"
3810
3811                 "%main     = OpFunction %void None %voidf\n"
3812                 "%entry    = OpLabel\n"
3813                 "%idval    = OpLoad %uvec3 %id\n"
3814                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3815                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3816                 "%inval    = OpLoad %f32 %inloc\n"
3817
3818                 "%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3819                 "%x8       = OpFMod %f32 %xabs %f32_256\n"
3820                 "%x7       = OpFMod %f32 %xabs %f32_128\n"
3821                 "%x6       = OpFMod %f32 %xabs %f32_64\n"
3822                 "%x5       = OpFMod %f32 %xabs %f32_32\n"
3823                 "%x4       = OpFMod %f32 %xabs %f32_16\n"
3824                 "%x3       = OpFMod %f32 %xabs %f32_8\n"
3825                 "%x2       = OpFMod %f32 %xabs %f32_4\n"
3826                 "%x1       = OpFMod %f32 %xabs %f32_2\n"
3827
3828                 "%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3829                 "%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3830                 "%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3831                 "%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3832                 "%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3833                 "%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3834                 "%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3835                 "%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3836
3837                 + generateOpPhiCase5(codestring) +
3838
3839                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3840                 "            OpStore %outloc %res\n"
3841                 "            OpReturn\n"
3842
3843                 "            OpFunctionEnd\n";
3844         spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3845         spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
3846         spec5.numWorkGroups = IVec3(numElements, 1, 1);
3847
3848         group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
3849
3850         createOpPhiVartypeTests(group, testCtx);
3851
3852         return group.release();
3853 }
3854
3855 // Assembly code used for testing block order is based on GLSL source code:
3856 //
3857 // #version 430
3858 //
3859 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3860 //   float elements[];
3861 // } input_data;
3862 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3863 //   float elements[];
3864 // } output_data;
3865 //
3866 // void main() {
3867 //   uint x = gl_GlobalInvocationID.x;
3868 //   output_data.elements[x] = input_data.elements[x];
3869 //   if (x > uint(50)) {
3870 //     switch (x % uint(3)) {
3871 //       case 0: output_data.elements[x] += 1.5f; break;
3872 //       case 1: output_data.elements[x] += 42.f; break;
3873 //       case 2: output_data.elements[x] -= 27.f; break;
3874 //       default: break;
3875 //     }
3876 //   } else {
3877 //     output_data.elements[x] = -input_data.elements[x];
3878 //   }
3879 // }
3880 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
3881 {
3882         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
3883         ComputeShaderSpec                               spec;
3884         de::Random                                              rnd                             (deStringHash(group->getName()));
3885         const int                                               numElements             = 100;
3886         vector<float>                                   inputFloats             (numElements, 0);
3887         vector<float>                                   outputFloats    (numElements, 0);
3888
3889         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3890
3891         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3892         floorAll(inputFloats);
3893
3894         for (size_t ndx = 0; ndx <= 50; ++ndx)
3895                 outputFloats[ndx] = -inputFloats[ndx];
3896
3897         for (size_t ndx = 51; ndx < numElements; ++ndx)
3898         {
3899                 switch (ndx % 3)
3900                 {
3901                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
3902                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
3903                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
3904                         default:        break;
3905                 }
3906         }
3907
3908         spec.assembly =
3909                 string(getComputeAsmShaderPreamble()) +
3910
3911                 "OpSource GLSL 430\n"
3912                 "OpName %main \"main\"\n"
3913                 "OpName %id \"gl_GlobalInvocationID\"\n"
3914
3915                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3916
3917                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
3918
3919                 "%u32ptr       = OpTypePointer Function %u32\n"
3920                 "%u32ptr_input = OpTypePointer Input %u32\n"
3921
3922                 + string(getComputeAsmInputOutputBuffer()) +
3923
3924                 "%id        = OpVariable %uvec3ptr Input\n"
3925                 "%zero      = OpConstant %i32 0\n"
3926                 "%const3    = OpConstant %u32 3\n"
3927                 "%const50   = OpConstant %u32 50\n"
3928                 "%constf1p5 = OpConstant %f32 1.5\n"
3929                 "%constf27  = OpConstant %f32 27.0\n"
3930                 "%constf42  = OpConstant %f32 42.0\n"
3931
3932                 "%main = OpFunction %void None %voidf\n"
3933
3934                 // entry block.
3935                 "%entry    = OpLabel\n"
3936
3937                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
3938                 "%xvar     = OpVariable %u32ptr Function\n"
3939                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
3940                 "%x        = OpLoad %u32 %xptr\n"
3941                 "            OpStore %xvar %x\n"
3942
3943                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
3944                 "            OpSelectionMerge %if_merge None\n"
3945                 "            OpBranchConditional %cmp %if_true %if_false\n"
3946
3947                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
3948                 "%if_false = OpLabel\n"
3949                 "%x_f      = OpLoad %u32 %xvar\n"
3950                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
3951                 "%inval_f  = OpLoad %f32 %inloc_f\n"
3952                 "%negate   = OpFNegate %f32 %inval_f\n"
3953                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
3954                 "            OpStore %outloc_f %negate\n"
3955                 "            OpBranch %if_merge\n"
3956
3957                 // Merge block for if-statement: placed in the middle of true and false branch.
3958                 "%if_merge = OpLabel\n"
3959                 "            OpReturn\n"
3960
3961                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
3962                 "%if_true  = OpLabel\n"
3963                 "%xval_t   = OpLoad %u32 %xvar\n"
3964                 "%mod      = OpUMod %u32 %xval_t %const3\n"
3965                 "            OpSelectionMerge %switch_merge None\n"
3966                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
3967
3968                 // Merge block for switch-statement: placed before the case
3969                 // bodies.  But it must follow OpSwitch which dominates it.
3970                 "%switch_merge = OpLabel\n"
3971                 "                OpBranch %if_merge\n"
3972
3973                 // Case 1 for switch-statement: placed before case 0.
3974                 // It must follow the OpSwitch that dominates it.
3975                 "%case1    = OpLabel\n"
3976                 "%x_1      = OpLoad %u32 %xvar\n"
3977                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
3978                 "%inval_1  = OpLoad %f32 %inloc_1\n"
3979                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
3980                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
3981                 "            OpStore %outloc_1 %addf42\n"
3982                 "            OpBranch %switch_merge\n"
3983
3984                 // Case 2 for switch-statement.
3985                 "%case2    = OpLabel\n"
3986                 "%x_2      = OpLoad %u32 %xvar\n"
3987                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
3988                 "%inval_2  = OpLoad %f32 %inloc_2\n"
3989                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
3990                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
3991                 "            OpStore %outloc_2 %subf27\n"
3992                 "            OpBranch %switch_merge\n"
3993
3994                 // Default case for switch-statement: placed in the middle of normal cases.
3995                 "%default = OpLabel\n"
3996                 "           OpBranch %switch_merge\n"
3997
3998                 // Case 0 for switch-statement: out of order.
3999                 "%case0    = OpLabel\n"
4000                 "%x_0      = OpLoad %u32 %xvar\n"
4001                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
4002                 "%inval_0  = OpLoad %f32 %inloc_0\n"
4003                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
4004                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
4005                 "            OpStore %outloc_0 %addf1p5\n"
4006                 "            OpBranch %switch_merge\n"
4007
4008                 "            OpFunctionEnd\n";
4009         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4010         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4011         spec.numWorkGroups = IVec3(numElements, 1, 1);
4012
4013         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
4014
4015         return group.release();
4016 }
4017
4018 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
4019 {
4020         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
4021         ComputeShaderSpec                               spec1;
4022         ComputeShaderSpec                               spec2;
4023         de::Random                                              rnd                             (deStringHash(group->getName()));
4024         const int                                               numElements             = 100;
4025         vector<float>                                   inputFloats             (numElements, 0);
4026         vector<float>                                   outputFloats1   (numElements, 0);
4027         vector<float>                                   outputFloats2   (numElements, 0);
4028         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
4029
4030         for (size_t ndx = 0; ndx < numElements; ++ndx)
4031         {
4032                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
4033                 outputFloats2[ndx] = -inputFloats[ndx];
4034         }
4035
4036         const string assembly(
4037                 "OpCapability Shader\n"
4038                 "OpMemoryModel Logical GLSL450\n"
4039                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
4040                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
4041                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
4042                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
4043                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
4044                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
4045
4046                 "OpName %comp_main1              \"entrypoint1\"\n"
4047                 "OpName %comp_main2              \"entrypoint2\"\n"
4048                 "OpName %vert_main               \"entrypoint2\"\n"
4049                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
4050                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
4051                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
4052                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
4053                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
4054                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
4055                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
4056
4057                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
4058                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
4059                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
4060                 "OpDecorate %vert_builtin_st         Block\n"
4061                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
4062                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
4063                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
4064
4065                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4066
4067                 "%zero       = OpConstant %i32 0\n"
4068                 "%one        = OpConstant %u32 1\n"
4069                 "%c_f32_1    = OpConstant %f32 1\n"
4070
4071                 "%i32inputptr         = OpTypePointer Input %i32\n"
4072                 "%vec4                = OpTypeVector %f32 4\n"
4073                 "%vec4ptr             = OpTypePointer Output %vec4\n"
4074                 "%f32arr1             = OpTypeArray %f32 %one\n"
4075                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
4076                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
4077                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
4078
4079                 "%id         = OpVariable %uvec3ptr Input\n"
4080                 "%vertexIndex = OpVariable %i32inputptr Input\n"
4081                 "%instanceIndex = OpVariable %i32inputptr Input\n"
4082                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
4083
4084                 // gl_Position = vec4(1.);
4085                 "%vert_main  = OpFunction %void None %voidf\n"
4086                 "%vert_entry = OpLabel\n"
4087                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
4088                 "              OpStore %position %c_vec4_1\n"
4089                 "              OpReturn\n"
4090                 "              OpFunctionEnd\n"
4091
4092                 // Double inputs.
4093                 "%comp_main1  = OpFunction %void None %voidf\n"
4094                 "%comp1_entry = OpLabel\n"
4095                 "%idval1      = OpLoad %uvec3 %id\n"
4096                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
4097                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
4098                 "%inval1      = OpLoad %f32 %inloc1\n"
4099                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
4100                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
4101                 "               OpStore %outloc1 %add\n"
4102                 "               OpReturn\n"
4103                 "               OpFunctionEnd\n"
4104
4105                 // Negate inputs.
4106                 "%comp_main2  = OpFunction %void None %voidf\n"
4107                 "%comp2_entry = OpLabel\n"
4108                 "%idval2      = OpLoad %uvec3 %id\n"
4109                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
4110                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
4111                 "%inval2      = OpLoad %f32 %inloc2\n"
4112                 "%neg         = OpFNegate %f32 %inval2\n"
4113                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
4114                 "               OpStore %outloc2 %neg\n"
4115                 "               OpReturn\n"
4116                 "               OpFunctionEnd\n");
4117
4118         spec1.assembly = assembly;
4119         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4120         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
4121         spec1.numWorkGroups = IVec3(numElements, 1, 1);
4122         spec1.entryPoint = "entrypoint1";
4123
4124         spec2.assembly = assembly;
4125         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4126         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
4127         spec2.numWorkGroups = IVec3(numElements, 1, 1);
4128         spec2.entryPoint = "entrypoint2";
4129
4130         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
4131         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
4132
4133         return group.release();
4134 }
4135
4136 inline std::string makeLongUTF8String (size_t num4ByteChars)
4137 {
4138         // An example of a longest valid UTF-8 character.  Be explicit about the
4139         // character type because Microsoft compilers can otherwise interpret the
4140         // character string as being over wide (16-bit) characters. Ideally, we
4141         // would just use a C++11 UTF-8 string literal, but we want to support older
4142         // Microsoft compilers.
4143         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
4144         std::string longString;
4145         longString.reserve(num4ByteChars * 4);
4146         for (size_t count = 0; count < num4ByteChars; count++)
4147         {
4148                 longString += earthAfrica;
4149         }
4150         return longString;
4151 }
4152
4153 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
4154 {
4155         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
4156         vector<CaseParameter>                   cases;
4157         de::Random                                              rnd                             (deStringHash(group->getName()));
4158         const int                                               numElements             = 100;
4159         vector<float>                                   positiveFloats  (numElements, 0);
4160         vector<float>                                   negativeFloats  (numElements, 0);
4161         const StringTemplate                    shaderTemplate  (
4162                 "OpCapability Shader\n"
4163                 "OpMemoryModel Logical GLSL450\n"
4164
4165                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4166                 "OpExecutionMode %main LocalSize 1 1 1\n"
4167
4168                 "${SOURCE}\n"
4169
4170                 "OpName %main           \"main\"\n"
4171                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4172
4173                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4174
4175                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4176
4177                 "%id        = OpVariable %uvec3ptr Input\n"
4178                 "%zero      = OpConstant %i32 0\n"
4179
4180                 "%main      = OpFunction %void None %voidf\n"
4181                 "%label     = OpLabel\n"
4182                 "%idval     = OpLoad %uvec3 %id\n"
4183                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4184                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4185                 "%inval     = OpLoad %f32 %inloc\n"
4186                 "%neg       = OpFNegate %f32 %inval\n"
4187                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4188                 "             OpStore %outloc %neg\n"
4189                 "             OpReturn\n"
4190                 "             OpFunctionEnd\n");
4191
4192         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
4193         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
4194         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
4195                                                                                                                                                         "OpSource GLSL 430 %fname"));
4196         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
4197                                                                                                                                                         "OpSource GLSL 430 %fname"));
4198         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
4199                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
4200         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
4201                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
4202         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
4203                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
4204         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
4205                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
4206         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
4207                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
4208                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
4209         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4210                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4211                                                                                                                                                         "OpSourceContinued \"\""));
4212         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4213                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4214                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
4215         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4216                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4217                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
4218         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4219                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
4220                                                                                                                                                         "OpSourceContinued \"void\"\n"
4221                                                                                                                                                         "OpSourceContinued \"main()\"\n"
4222                                                                                                                                                         "OpSourceContinued \"{}\""));
4223         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
4224                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
4225                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
4226
4227         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4228
4229         for (size_t ndx = 0; ndx < numElements; ++ndx)
4230                 negativeFloats[ndx] = -positiveFloats[ndx];
4231
4232         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4233         {
4234                 map<string, string>             specializations;
4235                 ComputeShaderSpec               spec;
4236
4237                 specializations["SOURCE"] = cases[caseNdx].param;
4238                 spec.assembly = shaderTemplate.specialize(specializations);
4239                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4240                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4241                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4242
4243                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4244         }
4245
4246         return group.release();
4247 }
4248
4249 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
4250 {
4251         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
4252         vector<CaseParameter>                   cases;
4253         de::Random                                              rnd                             (deStringHash(group->getName()));
4254         const int                                               numElements             = 100;
4255         vector<float>                                   inputFloats             (numElements, 0);
4256         vector<float>                                   outputFloats    (numElements, 0);
4257         const StringTemplate                    shaderTemplate  (
4258                 string(getComputeAsmShaderPreamble()) +
4259
4260                 "OpSourceExtension \"${EXTENSION}\"\n"
4261
4262                 "OpName %main           \"main\"\n"
4263                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4264
4265                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4266
4267                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4268
4269                 "%id        = OpVariable %uvec3ptr Input\n"
4270                 "%zero      = OpConstant %i32 0\n"
4271
4272                 "%main      = OpFunction %void None %voidf\n"
4273                 "%label     = OpLabel\n"
4274                 "%idval     = OpLoad %uvec3 %id\n"
4275                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4276                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4277                 "%inval     = OpLoad %f32 %inloc\n"
4278                 "%neg       = OpFNegate %f32 %inval\n"
4279                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4280                 "             OpStore %outloc %neg\n"
4281                 "             OpReturn\n"
4282                 "             OpFunctionEnd\n");
4283
4284         cases.push_back(CaseParameter("empty_extension",        ""));
4285         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
4286         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
4287         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
4288         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
4289
4290         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
4291
4292         for (size_t ndx = 0; ndx < numElements; ++ndx)
4293                 outputFloats[ndx] = -inputFloats[ndx];
4294
4295         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4296         {
4297                 map<string, string>             specializations;
4298                 ComputeShaderSpec               spec;
4299
4300                 specializations["EXTENSION"] = cases[caseNdx].param;
4301                 spec.assembly = shaderTemplate.specialize(specializations);
4302                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4303                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4304                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4305
4306                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4307         }
4308
4309         return group.release();
4310 }
4311
4312 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
4313 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
4314 {
4315         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
4316         vector<CaseParameter>                   cases;
4317         de::Random                                              rnd                             (deStringHash(group->getName()));
4318         const int                                               numElements             = 100;
4319         vector<float>                                   positiveFloats  (numElements, 0);
4320         vector<float>                                   negativeFloats  (numElements, 0);
4321         const StringTemplate                    shaderTemplate  (
4322                 string(getComputeAsmShaderPreamble()) +
4323
4324                 "OpSource GLSL 430\n"
4325                 "OpName %main           \"main\"\n"
4326                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4327
4328                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4329
4330                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4331                 "%uvec2     = OpTypeVector %u32 2\n"
4332                 "%bvec3     = OpTypeVector %bool 3\n"
4333                 "%fvec4     = OpTypeVector %f32 4\n"
4334                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
4335                 "%const100  = OpConstant %u32 100\n"
4336                 "%uarr100   = OpTypeArray %i32 %const100\n"
4337                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
4338                 "%pointer   = OpTypePointer Function %i32\n"
4339                 + string(getComputeAsmInputOutputBuffer()) +
4340
4341                 "%null      = OpConstantNull ${TYPE}\n"
4342
4343                 "%id        = OpVariable %uvec3ptr Input\n"
4344                 "%zero      = OpConstant %i32 0\n"
4345
4346                 "%main      = OpFunction %void None %voidf\n"
4347                 "%label     = OpLabel\n"
4348                 "%idval     = OpLoad %uvec3 %id\n"
4349                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4350                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4351                 "%inval     = OpLoad %f32 %inloc\n"
4352                 "%neg       = OpFNegate %f32 %inval\n"
4353                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4354                 "             OpStore %outloc %neg\n"
4355                 "             OpReturn\n"
4356                 "             OpFunctionEnd\n");
4357
4358         cases.push_back(CaseParameter("bool",                   "%bool"));
4359         cases.push_back(CaseParameter("sint32",                 "%i32"));
4360         cases.push_back(CaseParameter("uint32",                 "%u32"));
4361         cases.push_back(CaseParameter("float32",                "%f32"));
4362         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
4363         cases.push_back(CaseParameter("vec3bool",               "%bvec3"));
4364         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
4365         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
4366         cases.push_back(CaseParameter("array",                  "%uarr100"));
4367         cases.push_back(CaseParameter("struct",                 "%struct"));
4368         cases.push_back(CaseParameter("pointer",                "%pointer"));
4369
4370         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4371
4372         for (size_t ndx = 0; ndx < numElements; ++ndx)
4373                 negativeFloats[ndx] = -positiveFloats[ndx];
4374
4375         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4376         {
4377                 map<string, string>             specializations;
4378                 ComputeShaderSpec               spec;
4379
4380                 specializations["TYPE"] = cases[caseNdx].param;
4381                 spec.assembly = shaderTemplate.specialize(specializations);
4382                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4383                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4384                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4385
4386                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4387         }
4388
4389         return group.release();
4390 }
4391
4392 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4393 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4394 {
4395         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4396         vector<CaseParameter>                   cases;
4397         de::Random                                              rnd                             (deStringHash(group->getName()));
4398         const int                                               numElements             = 100;
4399         vector<float>                                   positiveFloats  (numElements, 0);
4400         vector<float>                                   negativeFloats  (numElements, 0);
4401         const StringTemplate                    shaderTemplate  (
4402                 string(getComputeAsmShaderPreamble()) +
4403
4404                 "OpSource GLSL 430\n"
4405                 "OpName %main           \"main\"\n"
4406                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4407
4408                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4409
4410                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4411
4412                 "%id        = OpVariable %uvec3ptr Input\n"
4413                 "%zero      = OpConstant %i32 0\n"
4414
4415                 "${CONSTANT}\n"
4416
4417                 "%main      = OpFunction %void None %voidf\n"
4418                 "%label     = OpLabel\n"
4419                 "%idval     = OpLoad %uvec3 %id\n"
4420                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4421                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4422                 "%inval     = OpLoad %f32 %inloc\n"
4423                 "%neg       = OpFNegate %f32 %inval\n"
4424                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4425                 "             OpStore %outloc %neg\n"
4426                 "             OpReturn\n"
4427                 "             OpFunctionEnd\n");
4428
4429         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
4430                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
4431         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4432                                                                                                         "%ten = OpConstant %f32 10.\n"
4433                                                                                                         "%fzero = OpConstant %f32 0.\n"
4434                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4435                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4436         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
4437                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4438                                                                                                         "%fzero = OpConstant %f32 0.\n"
4439                                                                                                         "%one = OpConstant %f32 1.\n"
4440                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4441                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4442                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4443                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4444         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
4445                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
4446                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
4447                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4448                                                                                                         "%one = OpConstant %u32 1\n"
4449                                                                                                         "%ten = OpConstant %i32 10\n"
4450                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
4451                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
4452                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
4453
4454         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4455
4456         for (size_t ndx = 0; ndx < numElements; ++ndx)
4457                 negativeFloats[ndx] = -positiveFloats[ndx];
4458
4459         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4460         {
4461                 map<string, string>             specializations;
4462                 ComputeShaderSpec               spec;
4463
4464                 specializations["CONSTANT"] = cases[caseNdx].param;
4465                 spec.assembly = shaderTemplate.specialize(specializations);
4466                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4467                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4468                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4469
4470                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4471         }
4472
4473         return group.release();
4474 }
4475
4476 // Creates a floating point number with the given exponent, and significand
4477 // bits set. It can only create normalized numbers. Only the least significant
4478 // 24 bits of the significand will be examined. The final bit of the
4479 // significand will also be ignored. This allows alignment to be written
4480 // similarly to C99 hex-floats.
4481 // For example if you wanted to write 0x1.7f34p-12 you would call
4482 // constructNormalizedFloat(-12, 0x7f3400)
4483 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4484 {
4485         float f = 1.0f;
4486
4487         for (deInt32 idx = 0; idx < 23; ++idx)
4488         {
4489                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4490                 significand <<= 1;
4491         }
4492
4493         return std::ldexp(f, exponent);
4494 }
4495
4496 // Compare instruction for the OpQuantizeF16 compute exact case.
4497 // Returns true if the output is what is expected from the test case.
4498 bool compareOpQuantizeF16ComputeExactCase (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4499 {
4500         if (outputAllocs.size() != 1)
4501                 return false;
4502
4503         // Only size is needed because we cannot compare Nans.
4504         size_t byteSize = expectedOutputs[0].getByteSize();
4505
4506         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4507
4508         if (byteSize != 4*sizeof(float)) {
4509                 return false;
4510         }
4511
4512         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4513                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4514                 return false;
4515         }
4516         outputAsFloat++;
4517
4518         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4519                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4520                 return false;
4521         }
4522         outputAsFloat++;
4523
4524         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4525                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4526                 return false;
4527         }
4528         outputAsFloat++;
4529
4530         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4531                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4532                 return false;
4533         }
4534
4535         return true;
4536 }
4537
4538 // Checks that every output from a test-case is a float NaN.
4539 bool compareNan (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4540 {
4541         if (outputAllocs.size() != 1)
4542                 return false;
4543
4544         // Only size is needed because we cannot compare Nans.
4545         size_t byteSize = expectedOutputs[0].getByteSize();
4546
4547         const float* const      output_as_float = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4548
4549         for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4550         {
4551                 if (!deFloatIsNaN(output_as_float[idx]))
4552                 {
4553                         return false;
4554                 }
4555         }
4556
4557         return true;
4558 }
4559
4560 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4561 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4562 {
4563         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4564
4565         const std::string shader (
4566                 string(getComputeAsmShaderPreamble()) +
4567
4568                 "OpSource GLSL 430\n"
4569                 "OpName %main           \"main\"\n"
4570                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4571
4572                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4573
4574                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4575
4576                 "%id        = OpVariable %uvec3ptr Input\n"
4577                 "%zero      = OpConstant %i32 0\n"
4578
4579                 "%main      = OpFunction %void None %voidf\n"
4580                 "%label     = OpLabel\n"
4581                 "%idval     = OpLoad %uvec3 %id\n"
4582                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4583                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4584                 "%inval     = OpLoad %f32 %inloc\n"
4585                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
4586                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4587                 "             OpStore %outloc %quant\n"
4588                 "             OpReturn\n"
4589                 "             OpFunctionEnd\n");
4590
4591         {
4592                 ComputeShaderSpec       spec;
4593                 const deUint32          numElements             = 100;
4594                 vector<float>           infinities;
4595                 vector<float>           results;
4596
4597                 infinities.reserve(numElements);
4598                 results.reserve(numElements);
4599
4600                 for (size_t idx = 0; idx < numElements; ++idx)
4601                 {
4602                         switch(idx % 4)
4603                         {
4604                                 case 0:
4605                                         infinities.push_back(std::numeric_limits<float>::infinity());
4606                                         results.push_back(std::numeric_limits<float>::infinity());
4607                                         break;
4608                                 case 1:
4609                                         infinities.push_back(-std::numeric_limits<float>::infinity());
4610                                         results.push_back(-std::numeric_limits<float>::infinity());
4611                                         break;
4612                                 case 2:
4613                                         infinities.push_back(std::ldexp(1.0f, 16));
4614                                         results.push_back(std::numeric_limits<float>::infinity());
4615                                         break;
4616                                 case 3:
4617                                         infinities.push_back(std::ldexp(-1.0f, 32));
4618                                         results.push_back(-std::numeric_limits<float>::infinity());
4619                                         break;
4620                         }
4621                 }
4622
4623                 spec.assembly = shader;
4624                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4625                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4626                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4627
4628                 group->addChild(new SpvAsmComputeShaderCase(
4629                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4630         }
4631
4632         {
4633                 ComputeShaderSpec       spec;
4634                 vector<float>           nans;
4635                 const deUint32          numElements             = 100;
4636
4637                 nans.reserve(numElements);
4638
4639                 for (size_t idx = 0; idx < numElements; ++idx)
4640                 {
4641                         if (idx % 2 == 0)
4642                         {
4643                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
4644                         }
4645                         else
4646                         {
4647                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4648                         }
4649                 }
4650
4651                 spec.assembly = shader;
4652                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4653                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4654                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4655                 spec.verifyIO = &compareNan;
4656
4657                 group->addChild(new SpvAsmComputeShaderCase(
4658                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4659         }
4660
4661         {
4662                 ComputeShaderSpec       spec;
4663                 vector<float>           small;
4664                 vector<float>           zeros;
4665                 const deUint32          numElements             = 100;
4666
4667                 small.reserve(numElements);
4668                 zeros.reserve(numElements);
4669
4670                 for (size_t idx = 0; idx < numElements; ++idx)
4671                 {
4672                         switch(idx % 6)
4673                         {
4674                                 case 0:
4675                                         small.push_back(0.f);
4676                                         zeros.push_back(0.f);
4677                                         break;
4678                                 case 1:
4679                                         small.push_back(-0.f);
4680                                         zeros.push_back(-0.f);
4681                                         break;
4682                                 case 2:
4683                                         small.push_back(std::ldexp(1.0f, -16));
4684                                         zeros.push_back(0.f);
4685                                         break;
4686                                 case 3:
4687                                         small.push_back(std::ldexp(-1.0f, -32));
4688                                         zeros.push_back(-0.f);
4689                                         break;
4690                                 case 4:
4691                                         small.push_back(std::ldexp(1.0f, -127));
4692                                         zeros.push_back(0.f);
4693                                         break;
4694                                 case 5:
4695                                         small.push_back(-std::ldexp(1.0f, -128));
4696                                         zeros.push_back(-0.f);
4697                                         break;
4698                         }
4699                 }
4700
4701                 spec.assembly = shader;
4702                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4703                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4704                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4705
4706                 group->addChild(new SpvAsmComputeShaderCase(
4707                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4708         }
4709
4710         {
4711                 ComputeShaderSpec       spec;
4712                 vector<float>           exact;
4713                 const deUint32          numElements             = 200;
4714
4715                 exact.reserve(numElements);
4716
4717                 for (size_t idx = 0; idx < numElements; ++idx)
4718                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4719
4720                 spec.assembly = shader;
4721                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4722                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4723                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4724
4725                 group->addChild(new SpvAsmComputeShaderCase(
4726                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4727         }
4728
4729         {
4730                 ComputeShaderSpec       spec;
4731                 vector<float>           inputs;
4732                 const deUint32          numElements             = 4;
4733
4734                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
4735                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
4736                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
4737                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
4738
4739                 spec.assembly = shader;
4740                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4741                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4742                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4743                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4744
4745                 group->addChild(new SpvAsmComputeShaderCase(
4746                         testCtx, "rounded", "Check that are rounded when needed", spec));
4747         }
4748
4749         return group.release();
4750 }
4751
4752 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4753 {
4754         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4755
4756         const std::string shader (
4757                 string(getComputeAsmShaderPreamble()) +
4758
4759                 "OpName %main           \"main\"\n"
4760                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4761
4762                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4763
4764                 "OpDecorate %sc_0  SpecId 0\n"
4765                 "OpDecorate %sc_1  SpecId 1\n"
4766                 "OpDecorate %sc_2  SpecId 2\n"
4767                 "OpDecorate %sc_3  SpecId 3\n"
4768                 "OpDecorate %sc_4  SpecId 4\n"
4769                 "OpDecorate %sc_5  SpecId 5\n"
4770
4771                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4772
4773                 "%id        = OpVariable %uvec3ptr Input\n"
4774                 "%zero      = OpConstant %i32 0\n"
4775                 "%c_u32_6   = OpConstant %u32 6\n"
4776
4777                 "%sc_0      = OpSpecConstant %f32 0.\n"
4778                 "%sc_1      = OpSpecConstant %f32 0.\n"
4779                 "%sc_2      = OpSpecConstant %f32 0.\n"
4780                 "%sc_3      = OpSpecConstant %f32 0.\n"
4781                 "%sc_4      = OpSpecConstant %f32 0.\n"
4782                 "%sc_5      = OpSpecConstant %f32 0.\n"
4783
4784                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4785                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4786                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4787                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4788                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4789                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4790
4791                 "%main      = OpFunction %void None %voidf\n"
4792                 "%label     = OpLabel\n"
4793                 "%idval     = OpLoad %uvec3 %id\n"
4794                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4795                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4796                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
4797                 "            OpSelectionMerge %exit None\n"
4798                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4799
4800                 "%case0     = OpLabel\n"
4801                 "             OpStore %outloc %sc_0_quant\n"
4802                 "             OpBranch %exit\n"
4803
4804                 "%case1     = OpLabel\n"
4805                 "             OpStore %outloc %sc_1_quant\n"
4806                 "             OpBranch %exit\n"
4807
4808                 "%case2     = OpLabel\n"
4809                 "             OpStore %outloc %sc_2_quant\n"
4810                 "             OpBranch %exit\n"
4811
4812                 "%case3     = OpLabel\n"
4813                 "             OpStore %outloc %sc_3_quant\n"
4814                 "             OpBranch %exit\n"
4815
4816                 "%case4     = OpLabel\n"
4817                 "             OpStore %outloc %sc_4_quant\n"
4818                 "             OpBranch %exit\n"
4819
4820                 "%case5     = OpLabel\n"
4821                 "             OpStore %outloc %sc_5_quant\n"
4822                 "             OpBranch %exit\n"
4823
4824                 "%exit      = OpLabel\n"
4825                 "             OpReturn\n"
4826
4827                 "             OpFunctionEnd\n");
4828
4829         {
4830                 ComputeShaderSpec       spec;
4831                 const deUint8           numCases        = 4;
4832                 vector<float>           inputs          (numCases, 0.f);
4833                 vector<float>           outputs;
4834
4835                 spec.assembly           = shader;
4836                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4837
4838                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4839                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4840                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4841                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4842
4843                 outputs.push_back(std::numeric_limits<float>::infinity());
4844                 outputs.push_back(-std::numeric_limits<float>::infinity());
4845                 outputs.push_back(std::numeric_limits<float>::infinity());
4846                 outputs.push_back(-std::numeric_limits<float>::infinity());
4847
4848                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4849                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4850
4851                 group->addChild(new SpvAsmComputeShaderCase(
4852                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4853         }
4854
4855         {
4856                 ComputeShaderSpec       spec;
4857                 const deUint8           numCases        = 2;
4858                 vector<float>           inputs          (numCases, 0.f);
4859                 vector<float>           outputs;
4860
4861                 spec.assembly           = shader;
4862                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4863                 spec.verifyIO           = &compareNan;
4864
4865                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
4866                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
4867
4868                 for (deUint8 idx = 0; idx < numCases; ++idx)
4869                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4870
4871                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4872                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4873
4874                 group->addChild(new SpvAsmComputeShaderCase(
4875                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4876         }
4877
4878         {
4879                 ComputeShaderSpec       spec;
4880                 const deUint8           numCases        = 6;
4881                 vector<float>           inputs          (numCases, 0.f);
4882                 vector<float>           outputs;
4883
4884                 spec.assembly           = shader;
4885                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4886
4887                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(0.f));
4888                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-0.f));
4889                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
4890                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
4891                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
4892                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
4893
4894                 outputs.push_back(0.f);
4895                 outputs.push_back(-0.f);
4896                 outputs.push_back(0.f);
4897                 outputs.push_back(-0.f);
4898                 outputs.push_back(0.f);
4899                 outputs.push_back(-0.f);
4900
4901                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4902                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4903
4904                 group->addChild(new SpvAsmComputeShaderCase(
4905                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4906         }
4907
4908         {
4909                 ComputeShaderSpec       spec;
4910                 const deUint8           numCases        = 6;
4911                 vector<float>           inputs          (numCases, 0.f);
4912                 vector<float>           outputs;
4913
4914                 spec.assembly           = shader;
4915                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4916
4917                 for (deUint8 idx = 0; idx < 6; ++idx)
4918                 {
4919                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
4920                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(f));
4921                         outputs.push_back(f);
4922                 }
4923
4924                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4925                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4926
4927                 group->addChild(new SpvAsmComputeShaderCase(
4928                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4929         }
4930
4931         {
4932                 ComputeShaderSpec       spec;
4933                 const deUint8           numCases        = 4;
4934                 vector<float>           inputs          (numCases, 0.f);
4935                 vector<float>           outputs;
4936
4937                 spec.assembly           = shader;
4938                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4939                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
4940
4941                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
4942                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
4943                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
4944                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
4945
4946                 for (deUint8 idx = 0; idx < numCases; ++idx)
4947                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4948
4949                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4950                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4951
4952                 group->addChild(new SpvAsmComputeShaderCase(
4953                         testCtx, "rounded", "Check that are rounded when needed", spec));
4954         }
4955
4956         return group.release();
4957 }
4958
4959 // Checks that constant null/composite values can be used in computation.
4960 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
4961 {
4962         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
4963         ComputeShaderSpec                               spec;
4964         de::Random                                              rnd                             (deStringHash(group->getName()));
4965         const int                                               numElements             = 100;
4966         vector<float>                                   positiveFloats  (numElements, 0);
4967         vector<float>                                   negativeFloats  (numElements, 0);
4968
4969         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4970
4971         for (size_t ndx = 0; ndx < numElements; ++ndx)
4972                 negativeFloats[ndx] = -positiveFloats[ndx];
4973
4974         spec.assembly =
4975                 "OpCapability Shader\n"
4976                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
4977                 "OpMemoryModel Logical GLSL450\n"
4978                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4979                 "OpExecutionMode %main LocalSize 1 1 1\n"
4980
4981                 "OpSource GLSL 430\n"
4982                 "OpName %main           \"main\"\n"
4983                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4984
4985                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4986
4987                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4988
4989                 "%fmat      = OpTypeMatrix %fvec3 3\n"
4990                 "%ten       = OpConstant %u32 10\n"
4991                 "%f32arr10  = OpTypeArray %f32 %ten\n"
4992                 "%fst       = OpTypeStruct %f32 %f32\n"
4993
4994                 + string(getComputeAsmInputOutputBuffer()) +
4995
4996                 "%id        = OpVariable %uvec3ptr Input\n"
4997                 "%zero      = OpConstant %i32 0\n"
4998
4999                 // Create a bunch of null values
5000                 "%unull     = OpConstantNull %u32\n"
5001                 "%fnull     = OpConstantNull %f32\n"
5002                 "%vnull     = OpConstantNull %fvec3\n"
5003                 "%mnull     = OpConstantNull %fmat\n"
5004                 "%anull     = OpConstantNull %f32arr10\n"
5005                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
5006
5007                 "%main      = OpFunction %void None %voidf\n"
5008                 "%label     = OpLabel\n"
5009                 "%idval     = OpLoad %uvec3 %id\n"
5010                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5011                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5012                 "%inval     = OpLoad %f32 %inloc\n"
5013                 "%neg       = OpFNegate %f32 %inval\n"
5014
5015                 // Get the abs() of (a certain element of) those null values
5016                 "%unull_cov = OpConvertUToF %f32 %unull\n"
5017                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
5018                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
5019                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
5020                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
5021                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
5022                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
5023                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
5024                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
5025                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
5026                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
5027
5028                 // Add them all
5029                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
5030                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
5031                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
5032                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
5033                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
5034                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
5035
5036                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5037                 "             OpStore %outloc %final\n" // write to output
5038                 "             OpReturn\n"
5039                 "             OpFunctionEnd\n";
5040         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5041         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5042         spec.numWorkGroups = IVec3(numElements, 1, 1);
5043
5044         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
5045
5046         return group.release();
5047 }
5048
5049 // Assembly code used for testing loop control is based on GLSL source code:
5050 // #version 430
5051 //
5052 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5053 //   float elements[];
5054 // } input_data;
5055 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5056 //   float elements[];
5057 // } output_data;
5058 //
5059 // void main() {
5060 //   uint x = gl_GlobalInvocationID.x;
5061 //   output_data.elements[x] = input_data.elements[x];
5062 //   for (uint i = 0; i < 4; ++i)
5063 //     output_data.elements[x] += 1.f;
5064 // }
5065 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
5066 {
5067         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
5068         vector<CaseParameter>                   cases;
5069         de::Random                                              rnd                             (deStringHash(group->getName()));
5070         const int                                               numElements             = 100;
5071         vector<float>                                   inputFloats             (numElements, 0);
5072         vector<float>                                   outputFloats    (numElements, 0);
5073         const StringTemplate                    shaderTemplate  (
5074                 string(getComputeAsmShaderPreamble()) +
5075
5076                 "OpSource GLSL 430\n"
5077                 "OpName %main \"main\"\n"
5078                 "OpName %id \"gl_GlobalInvocationID\"\n"
5079
5080                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5081
5082                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5083
5084                 "%u32ptr      = OpTypePointer Function %u32\n"
5085
5086                 "%id          = OpVariable %uvec3ptr Input\n"
5087                 "%zero        = OpConstant %i32 0\n"
5088                 "%uzero       = OpConstant %u32 0\n"
5089                 "%one         = OpConstant %i32 1\n"
5090                 "%constf1     = OpConstant %f32 1.0\n"
5091                 "%four        = OpConstant %u32 4\n"
5092
5093                 "%main        = OpFunction %void None %voidf\n"
5094                 "%entry       = OpLabel\n"
5095                 "%i           = OpVariable %u32ptr Function\n"
5096                 "               OpStore %i %uzero\n"
5097
5098                 "%idval       = OpLoad %uvec3 %id\n"
5099                 "%x           = OpCompositeExtract %u32 %idval 0\n"
5100                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
5101                 "%inval       = OpLoad %f32 %inloc\n"
5102                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
5103                 "               OpStore %outloc %inval\n"
5104                 "               OpBranch %loop_entry\n"
5105
5106                 "%loop_entry  = OpLabel\n"
5107                 "%i_val       = OpLoad %u32 %i\n"
5108                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
5109                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
5110                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
5111                 "%loop_body   = OpLabel\n"
5112                 "%outval      = OpLoad %f32 %outloc\n"
5113                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
5114                 "               OpStore %outloc %addf1\n"
5115                 "%new_i       = OpIAdd %u32 %i_val %one\n"
5116                 "               OpStore %i %new_i\n"
5117                 "               OpBranch %loop_entry\n"
5118                 "%loop_merge  = OpLabel\n"
5119                 "               OpReturn\n"
5120                 "               OpFunctionEnd\n");
5121
5122         cases.push_back(CaseParameter("none",                           "None"));
5123         cases.push_back(CaseParameter("unroll",                         "Unroll"));
5124         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
5125         cases.push_back(CaseParameter("unroll_dont_unroll",     "Unroll|DontUnroll"));
5126
5127         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5128
5129         for (size_t ndx = 0; ndx < numElements; ++ndx)
5130                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
5131
5132         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5133         {
5134                 map<string, string>             specializations;
5135                 ComputeShaderSpec               spec;
5136
5137                 specializations["CONTROL"] = cases[caseNdx].param;
5138                 spec.assembly = shaderTemplate.specialize(specializations);
5139                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5140                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5141                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5142
5143                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5144         }
5145
5146         group->addChild(new SpvAsmLoopControlDependencyLengthCase(testCtx, "dependency_length", "dependency_length"));
5147         group->addChild(new SpvAsmLoopControlDependencyInfiniteCase(testCtx, "dependency_infinite", "dependency_infinite"));
5148
5149         return group.release();
5150 }
5151
5152 // Assembly code used for testing selection control is based on GLSL source code:
5153 // #version 430
5154 //
5155 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5156 //   float elements[];
5157 // } input_data;
5158 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5159 //   float elements[];
5160 // } output_data;
5161 //
5162 // void main() {
5163 //   uint x = gl_GlobalInvocationID.x;
5164 //   float val = input_data.elements[x];
5165 //   if (val > 10.f)
5166 //     output_data.elements[x] = val + 1.f;
5167 //   else
5168 //     output_data.elements[x] = val - 1.f;
5169 // }
5170 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
5171 {
5172         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
5173         vector<CaseParameter>                   cases;
5174         de::Random                                              rnd                             (deStringHash(group->getName()));
5175         const int                                               numElements             = 100;
5176         vector<float>                                   inputFloats             (numElements, 0);
5177         vector<float>                                   outputFloats    (numElements, 0);
5178         const StringTemplate                    shaderTemplate  (
5179                 string(getComputeAsmShaderPreamble()) +
5180
5181                 "OpSource GLSL 430\n"
5182                 "OpName %main \"main\"\n"
5183                 "OpName %id \"gl_GlobalInvocationID\"\n"
5184
5185                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5186
5187                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5188
5189                 "%id       = OpVariable %uvec3ptr Input\n"
5190                 "%zero     = OpConstant %i32 0\n"
5191                 "%constf1  = OpConstant %f32 1.0\n"
5192                 "%constf10 = OpConstant %f32 10.0\n"
5193
5194                 "%main     = OpFunction %void None %voidf\n"
5195                 "%entry    = OpLabel\n"
5196                 "%idval    = OpLoad %uvec3 %id\n"
5197                 "%x        = OpCompositeExtract %u32 %idval 0\n"
5198                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
5199                 "%inval    = OpLoad %f32 %inloc\n"
5200                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
5201                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
5202
5203                 "            OpSelectionMerge %if_end ${CONTROL}\n"
5204                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
5205                 "%if_true  = OpLabel\n"
5206                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
5207                 "            OpStore %outloc %addf1\n"
5208                 "            OpBranch %if_end\n"
5209                 "%if_false = OpLabel\n"
5210                 "%subf1    = OpFSub %f32 %inval %constf1\n"
5211                 "            OpStore %outloc %subf1\n"
5212                 "            OpBranch %if_end\n"
5213                 "%if_end   = OpLabel\n"
5214                 "            OpReturn\n"
5215                 "            OpFunctionEnd\n");
5216
5217         cases.push_back(CaseParameter("none",                                   "None"));
5218         cases.push_back(CaseParameter("flatten",                                "Flatten"));
5219         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
5220         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
5221
5222         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5223
5224         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5225         floorAll(inputFloats);
5226
5227         for (size_t ndx = 0; ndx < numElements; ++ndx)
5228                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
5229
5230         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5231         {
5232                 map<string, string>             specializations;
5233                 ComputeShaderSpec               spec;
5234
5235                 specializations["CONTROL"] = cases[caseNdx].param;
5236                 spec.assembly = shaderTemplate.specialize(specializations);
5237                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5238                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5239                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5240
5241                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5242         }
5243
5244         return group.release();
5245 }
5246
5247 void getOpNameAbuseCases (vector<CaseParameter> &abuseCases)
5248 {
5249         // Generate a long name.
5250         std::string longname;
5251         longname.resize(65535, 'k'); // max string literal, spir-v 2.17
5252
5253         // Some bad names, abusing utf-8 encoding. This may also cause problems
5254         // with the logs.
5255         // 1. Various illegal code points in utf-8
5256         std::string utf8illegal =
5257                 "Illegal bytes in UTF-8: "
5258                 "\xc0 \xc1 \xf5 \xf6 \xf7 \xf8 \xf9 \xfa \xfb \xfc \xfd \xfe \xff"
5259                 "illegal surrogates: \xed\xad\xbf \xed\xbe\x80";
5260
5261         // 2. Zero encoded as overlong, not exactly legal but often supported to differentiate from terminating zero
5262         std::string utf8nul = "UTF-8 encoded nul \xC0\x80 (should not end name)";
5263
5264         // 3. Some overlong encodings
5265         std::string utf8overlong =
5266                 "UTF-8 overlong \xF0\x82\x82\xAC \xfc\x83\xbf\xbf\xbf\xbf \xf8\x87\xbf\xbf\xbf "
5267                 "\xf0\x8f\xbf\xbf";
5268
5269         // 4. Internet "zalgo" meme "bleeding text"
5270         std::string utf8zalgo =
5271                 "\x56\xcc\xb5\xcc\x85\xcc\x94\xcc\x88\xcd\x8a\xcc\x91\xcc\x88\xcd\x91\xcc\x83\xcd\x82"
5272                 "\xcc\x83\xcd\x90\xcc\x8a\xcc\x92\xcc\x92\xcd\x8b\xcc\x94\xcd\x9d\xcc\x98\xcc\xab\xcc"
5273                 "\xae\xcc\xa9\xcc\xad\xcc\x97\xcc\xb0\x75\xcc\xb6\xcc\xbe\xcc\x80\xcc\x82\xcc\x84\xcd"
5274                 "\x84\xcc\x90\xcd\x86\xcc\x9a\xcd\x84\xcc\x9b\xcd\x86\xcd\x92\xcc\x9a\xcd\x99\xcd\x99"
5275                 "\xcc\xbb\xcc\x98\xcd\x8e\xcd\x88\xcd\x9a\xcc\xa6\xcc\x9c\xcc\xab\xcc\x99\xcd\x94\xcd"
5276                 "\x99\xcd\x95\xcc\xa5\xcc\xab\xcd\x89\x6c\xcc\xb8\xcc\x8e\xcc\x8b\xcc\x8b\xcc\x9a\xcc"
5277                 "\x8e\xcd\x9d\xcc\x80\xcc\xa1\xcc\xad\xcd\x9c\xcc\xba\xcc\x96\xcc\xb3\xcc\xa2\xcd\x8e"
5278                 "\xcc\xa2\xcd\x96\x6b\xcc\xb8\xcc\x84\xcd\x81\xcc\xbf\xcc\x8d\xcc\x89\xcc\x85\xcc\x92"
5279                 "\xcc\x84\xcc\x90\xcd\x81\xcc\x93\xcd\x90\xcd\x92\xcd\x9d\xcc\x84\xcd\x98\xcd\x9d\xcd"
5280                 "\xa0\xcd\x91\xcc\x94\xcc\xb9\xcd\x93\xcc\xa5\xcd\x87\xcc\xad\xcc\xa7\xcd\x96\xcd\x99"
5281                 "\xcc\x9d\xcc\xbc\xcd\x96\xcd\x93\xcc\x9d\xcc\x99\xcc\xa8\xcc\xb1\xcd\x85\xcc\xba\xcc"
5282                 "\xa7\x61\xcc\xb8\xcc\x8e\xcc\x81\xcd\x90\xcd\x84\xcd\x8c\xcc\x8c\xcc\x85\xcd\x86\xcc"
5283                 "\x84\xcd\x84\xcc\x90\xcc\x84\xcc\x8d\xcd\x99\xcd\x8d\xcc\xb0\xcc\xa3\xcc\xa6\xcd\x89"
5284                 "\xcd\x8d\xcd\x87\xcc\x98\xcd\x8d\xcc\xa4\xcd\x9a\xcd\x8e\xcc\xab\xcc\xb9\xcc\xac\xcc"
5285                 "\xa2\xcd\x87\xcc\xa0\xcc\xb3\xcd\x89\xcc\xb9\xcc\xa7\xcc\xa6\xcd\x89\xcd\x95\x6e\xcc"
5286                 "\xb8\xcd\x8a\xcc\x8a\xcd\x82\xcc\x9b\xcd\x81\xcd\x90\xcc\x85\xcc\x9b\xcd\x80\xcd\x91"
5287                 "\xcd\x9b\xcc\x81\xcd\x81\xcc\x9a\xcc\xb3\xcd\x9c\xcc\x9e\xcc\x9d\xcd\x99\xcc\xa2\xcd"
5288                 "\x93\xcd\x96\xcc\x97\xff";
5289
5290         // General name abuses
5291         abuseCases.push_back(CaseParameter("_has_very_long_name", longname));
5292         abuseCases.push_back(CaseParameter("_utf8_illegal", utf8illegal));
5293         abuseCases.push_back(CaseParameter("_utf8_nul", utf8nul));
5294         abuseCases.push_back(CaseParameter("_utf8_overlong", utf8overlong));
5295         abuseCases.push_back(CaseParameter("_utf8_zalgo", utf8zalgo));
5296
5297         // GL keywords
5298         abuseCases.push_back(CaseParameter("_is_gl_Position", "gl_Position"));
5299         abuseCases.push_back(CaseParameter("_is_gl_InstanceID", "gl_InstanceID"));
5300         abuseCases.push_back(CaseParameter("_is_gl_PrimitiveID", "gl_PrimitiveID"));
5301         abuseCases.push_back(CaseParameter("_is_gl_TessCoord", "gl_TessCoord"));
5302         abuseCases.push_back(CaseParameter("_is_gl_PerVertex", "gl_PerVertex"));
5303         abuseCases.push_back(CaseParameter("_is_gl_InvocationID", "gl_InvocationID"));
5304         abuseCases.push_back(CaseParameter("_is_gl_PointSize", "gl_PointSize"));
5305         abuseCases.push_back(CaseParameter("_is_gl_PointCoord", "gl_PointCoord"));
5306         abuseCases.push_back(CaseParameter("_is_gl_Layer", "gl_Layer"));
5307         abuseCases.push_back(CaseParameter("_is_gl_FragDepth", "gl_FragDepth"));
5308         abuseCases.push_back(CaseParameter("_is_gl_NumWorkGroups", "gl_NumWorkGroups"));
5309         abuseCases.push_back(CaseParameter("_is_gl_WorkGroupID", "gl_WorkGroupID"));
5310         abuseCases.push_back(CaseParameter("_is_gl_LocalInvocationID", "gl_LocalInvocationID"));
5311         abuseCases.push_back(CaseParameter("_is_gl_GlobalInvocationID", "gl_GlobalInvocationID"));
5312         abuseCases.push_back(CaseParameter("_is_gl_MaxVertexAttribs", "gl_MaxVertexAttribs"));
5313         abuseCases.push_back(CaseParameter("_is_gl_MaxViewports", "gl_MaxViewports"));
5314         abuseCases.push_back(CaseParameter("_is_gl_MaxComputeWorkGroupCount", "gl_MaxComputeWorkGroupCount"));
5315         abuseCases.push_back(CaseParameter("_is_mat3", "mat3"));
5316         abuseCases.push_back(CaseParameter("_is_volatile", "volatile"));
5317         abuseCases.push_back(CaseParameter("_is_inout", "inout"));
5318         abuseCases.push_back(CaseParameter("_is_isampler3d", "isampler3d"));
5319 }
5320
5321 tcu::TestCaseGroup* createOpNameGroup (tcu::TestContext& testCtx)
5322 {
5323         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opname", "Tests OpName cases"));
5324         de::MovePtr<tcu::TestCaseGroup> entryMainGroup  (new tcu::TestCaseGroup(testCtx, "entry_main", "OpName tests with entry main"));
5325         de::MovePtr<tcu::TestCaseGroup> entryNotGroup   (new tcu::TestCaseGroup(testCtx, "entry_rdc", "OpName tests with entry rdc"));
5326         de::MovePtr<tcu::TestCaseGroup> abuseGroup              (new tcu::TestCaseGroup(testCtx, "abuse", "OpName abuse tests"));
5327         vector<CaseParameter>                   cases;
5328         vector<CaseParameter>                   abuseCases;
5329         vector<string>                                  testFunc;
5330         de::Random                                              rnd                             (deStringHash(group->getName()));
5331         const int                                               numElements             = 128;
5332         vector<float>                                   inputFloats             (numElements, 0);
5333         vector<float>                                   outputFloats    (numElements, 0);
5334
5335         getOpNameAbuseCases(abuseCases);
5336
5337         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5338
5339         for(size_t ndx = 0; ndx < numElements; ++ndx)
5340                 outputFloats[ndx] = -inputFloats[ndx];
5341
5342         const string commonShaderHeader =
5343                 "OpCapability Shader\n"
5344                 "OpMemoryModel Logical GLSL450\n"
5345                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5346                 "OpExecutionMode %main LocalSize 1 1 1\n";
5347
5348         const string commonShaderFooter =
5349                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5350
5351                 + string(getComputeAsmInputOutputBufferTraits())
5352                 + string(getComputeAsmCommonTypes())
5353                 + string(getComputeAsmInputOutputBuffer()) +
5354
5355                 "%id        = OpVariable %uvec3ptr Input\n"
5356                 "%zero      = OpConstant %i32 0\n"
5357
5358                 "%func      = OpFunction %void None %voidf\n"
5359                 "%5         = OpLabel\n"
5360                 "             OpReturn\n"
5361                 "             OpFunctionEnd\n"
5362
5363                 "%main      = OpFunction %void None %voidf\n"
5364                 "%entry     = OpLabel\n"
5365                 "%7         = OpFunctionCall %void %func\n"
5366
5367                 "%idval     = OpLoad %uvec3 %id\n"
5368                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5369
5370                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5371                 "%inval     = OpLoad %f32 %inloc\n"
5372                 "%neg       = OpFNegate %f32 %inval\n"
5373                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5374                 "             OpStore %outloc %neg\n"
5375
5376                 "             OpReturn\n"
5377                 "             OpFunctionEnd\n";
5378
5379         const StringTemplate shaderTemplate (
5380                 "OpCapability Shader\n"
5381                 "OpMemoryModel Logical GLSL450\n"
5382                 "OpEntryPoint GLCompute %main \"${ENTRY}\" %id\n"
5383                 "OpExecutionMode %main LocalSize 1 1 1\n"
5384                 "OpName %${ID} \"${NAME}\"\n" +
5385                 commonShaderFooter);
5386
5387         const std::string multipleNames =
5388                 commonShaderHeader +
5389                 "OpName %main \"to_be\"\n"
5390                 "OpName %id   \"or_not\"\n"
5391                 "OpName %main \"to_be\"\n"
5392                 "OpName %main \"makes_no\"\n"
5393                 "OpName %func \"difference\"\n"
5394                 "OpName %5    \"to_me\"\n" +
5395                 commonShaderFooter;
5396
5397         {
5398                 ComputeShaderSpec       spec;
5399
5400                 spec.assembly           = multipleNames;
5401                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5402                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5403                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5404
5405                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "main_has_multiple_names", "multiple_names", spec));
5406         }
5407
5408         const std::string everythingNamed =
5409                 commonShaderHeader +
5410                 "OpName %main   \"name1\"\n"
5411                 "OpName %id     \"name2\"\n"
5412                 "OpName %zero   \"name3\"\n"
5413                 "OpName %entry  \"name4\"\n"
5414                 "OpName %func   \"name5\"\n"
5415                 "OpName %5      \"name6\"\n"
5416                 "OpName %7      \"name7\"\n"
5417                 "OpName %idval  \"name8\"\n"
5418                 "OpName %inloc  \"name9\"\n"
5419                 "OpName %inval  \"name10\"\n"
5420                 "OpName %neg    \"name11\"\n"
5421                 "OpName %outloc \"name12\"\n"+
5422                 commonShaderFooter;
5423         {
5424                 ComputeShaderSpec       spec;
5425
5426                 spec.assembly           = everythingNamed;
5427                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5428                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5429                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5430
5431                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named", "everything_named", spec));
5432         }
5433
5434         const std::string everythingNamedTheSame =
5435                 commonShaderHeader +
5436                 "OpName %main   \"the_same\"\n"
5437                 "OpName %id     \"the_same\"\n"
5438                 "OpName %zero   \"the_same\"\n"
5439                 "OpName %entry  \"the_same\"\n"
5440                 "OpName %func   \"the_same\"\n"
5441                 "OpName %5      \"the_same\"\n"
5442                 "OpName %7      \"the_same\"\n"
5443                 "OpName %idval  \"the_same\"\n"
5444                 "OpName %inloc  \"the_same\"\n"
5445                 "OpName %inval  \"the_same\"\n"
5446                 "OpName %neg    \"the_same\"\n"
5447                 "OpName %outloc \"the_same\"\n"+
5448                 commonShaderFooter;
5449         {
5450                 ComputeShaderSpec       spec;
5451
5452                 spec.assembly           = everythingNamedTheSame;
5453                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5454                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5455                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5456
5457                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5458         }
5459
5460         // main_is_...
5461         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5462         {
5463                 map<string, string>     specializations;
5464                 ComputeShaderSpec       spec;
5465
5466                 specializations["ENTRY"]        = "main";
5467                 specializations["ID"]           = "main";
5468                 specializations["NAME"]         = abuseCases[ndx].param;
5469                 spec.assembly                           = shaderTemplate.specialize(specializations);
5470                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5471                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5472                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5473
5474                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("main") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5475         }
5476
5477         // x_is_....
5478         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5479         {
5480                 map<string, string>     specializations;
5481                 ComputeShaderSpec       spec;
5482
5483                 specializations["ENTRY"]        = "main";
5484                 specializations["ID"]           = "x";
5485                 specializations["NAME"]         = abuseCases[ndx].param;
5486                 spec.assembly                           = shaderTemplate.specialize(specializations);
5487                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5488                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5489                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5490
5491                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5492         }
5493
5494         cases.push_back(CaseParameter("_is_main", "main"));
5495         cases.push_back(CaseParameter("_is_not_main", "not_main"));
5496         testFunc.push_back("main");
5497         testFunc.push_back("func");
5498
5499         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5500         {
5501                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5502                 {
5503                         map<string, string>     specializations;
5504                         ComputeShaderSpec       spec;
5505
5506                         specializations["ENTRY"]        = "main";
5507                         specializations["ID"]           = testFunc[fNdx];
5508                         specializations["NAME"]         = cases[ndx].param;
5509                         spec.assembly                           = shaderTemplate.specialize(specializations);
5510                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5511                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5512                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5513
5514                         entryMainGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5515                 }
5516         }
5517
5518         cases.push_back(CaseParameter("_is_entry", "rdc"));
5519
5520         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5521         {
5522                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5523                 {
5524                         map<string, string>     specializations;
5525                         ComputeShaderSpec       spec;
5526
5527                         specializations["ENTRY"]        = "rdc";
5528                         specializations["ID"]           = testFunc[fNdx];
5529                         specializations["NAME"]         = cases[ndx].param;
5530                         spec.assembly                           = shaderTemplate.specialize(specializations);
5531                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5532                         spec.entryPoint                         = "rdc";
5533                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5534                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5535
5536                         entryNotGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5537                 }
5538         }
5539
5540         group->addChild(entryMainGroup.release());
5541         group->addChild(entryNotGroup.release());
5542         group->addChild(abuseGroup.release());
5543
5544         return group.release();
5545 }
5546
5547 tcu::TestCaseGroup* createOpMemberNameGroup (tcu::TestContext& testCtx)
5548 {
5549         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opmembername", "Tests OpMemberName cases"));
5550         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "abuse", "OpMemberName abuse tests"));
5551         vector<CaseParameter>                   abuseCases;
5552         vector<string>                                  testFunc;
5553         de::Random                                              rnd(deStringHash(group->getName()));
5554         const int                                               numElements = 128;
5555         vector<float>                                   inputFloats(numElements, 0);
5556         vector<float>                                   outputFloats(numElements, 0);
5557
5558         getOpNameAbuseCases(abuseCases);
5559
5560         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5561
5562         for (size_t ndx = 0; ndx < numElements; ++ndx)
5563                 outputFloats[ndx] = -inputFloats[ndx];
5564
5565         const string commonShaderHeader =
5566                 "OpCapability Shader\n"
5567                 "OpMemoryModel Logical GLSL450\n"
5568                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5569                 "OpExecutionMode %main LocalSize 1 1 1\n";
5570
5571         const string commonShaderFooter =
5572                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5573
5574                 + string(getComputeAsmInputOutputBufferTraits())
5575                 + string(getComputeAsmCommonTypes())
5576                 + string(getComputeAsmInputOutputBuffer()) +
5577
5578                 "%u3str     = OpTypeStruct %u32 %u32 %u32\n"
5579
5580                 "%id        = OpVariable %uvec3ptr Input\n"
5581                 "%zero      = OpConstant %i32 0\n"
5582
5583                 "%main      = OpFunction %void None %voidf\n"
5584                 "%entry     = OpLabel\n"
5585
5586                 "%idval     = OpLoad %uvec3 %id\n"
5587                 "%x0        = OpCompositeExtract %u32 %idval 0\n"
5588
5589                 "%idstr     = OpCompositeConstruct %u3str %x0 %x0 %x0\n"
5590                 "%x         = OpCompositeExtract %u32 %idstr 0\n"
5591
5592                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5593                 "%inval     = OpLoad %f32 %inloc\n"
5594                 "%neg       = OpFNegate %f32 %inval\n"
5595                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5596                 "             OpStore %outloc %neg\n"
5597
5598                 "             OpReturn\n"
5599                 "             OpFunctionEnd\n";
5600
5601         const StringTemplate shaderTemplate(
5602                 commonShaderHeader +
5603                 "OpMemberName %u3str 0 \"${NAME}\"\n" +
5604                 commonShaderFooter);
5605
5606         const std::string multipleNames =
5607                 commonShaderHeader +
5608                 "OpMemberName %u3str 0 \"to_be\"\n"
5609                 "OpMemberName %u3str 1 \"or_not\"\n"
5610                 "OpMemberName %u3str 0 \"to_be\"\n"
5611                 "OpMemberName %u3str 2 \"makes_no\"\n"
5612                 "OpMemberName %u3str 0 \"difference\"\n"
5613                 "OpMemberName %u3str 0 \"to_me\"\n" +
5614                 commonShaderFooter;
5615         {
5616                 ComputeShaderSpec       spec;
5617
5618                 spec.assembly = multipleNames;
5619                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5620                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5621                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5622
5623                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "u3str_x_has_multiple_names", "multiple_names", spec));
5624         }
5625
5626         const std::string everythingNamedTheSame =
5627                 commonShaderHeader +
5628                 "OpMemberName %u3str 0 \"the_same\"\n"
5629                 "OpMemberName %u3str 1 \"the_same\"\n"
5630                 "OpMemberName %u3str 2 \"the_same\"\n" +
5631                 commonShaderFooter;
5632
5633         {
5634                 ComputeShaderSpec       spec;
5635
5636                 spec.assembly = everythingNamedTheSame;
5637                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5638                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5639                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5640
5641                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5642         }
5643
5644         // u3str_x_is_....
5645         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5646         {
5647                 map<string, string>     specializations;
5648                 ComputeShaderSpec       spec;
5649
5650                 specializations["NAME"] = abuseCases[ndx].param;
5651                 spec.assembly = shaderTemplate.specialize(specializations);
5652                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5653                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5654                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5655
5656                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("u3str_x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5657         }
5658
5659         group->addChild(abuseGroup.release());
5660
5661         return group.release();
5662 }
5663
5664 // Assembly code used for testing function control is based on GLSL source code:
5665 //
5666 // #version 430
5667 //
5668 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5669 //   float elements[];
5670 // } input_data;
5671 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5672 //   float elements[];
5673 // } output_data;
5674 //
5675 // float const10() { return 10.f; }
5676 //
5677 // void main() {
5678 //   uint x = gl_GlobalInvocationID.x;
5679 //   output_data.elements[x] = input_data.elements[x] + const10();
5680 // }
5681 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
5682 {
5683         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
5684         vector<CaseParameter>                   cases;
5685         de::Random                                              rnd                             (deStringHash(group->getName()));
5686         const int                                               numElements             = 100;
5687         vector<float>                                   inputFloats             (numElements, 0);
5688         vector<float>                                   outputFloats    (numElements, 0);
5689         const StringTemplate                    shaderTemplate  (
5690                 string(getComputeAsmShaderPreamble()) +
5691
5692                 "OpSource GLSL 430\n"
5693                 "OpName %main \"main\"\n"
5694                 "OpName %func_const10 \"const10(\"\n"
5695                 "OpName %id \"gl_GlobalInvocationID\"\n"
5696
5697                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5698
5699                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5700
5701                 "%f32f = OpTypeFunction %f32\n"
5702                 "%id = OpVariable %uvec3ptr Input\n"
5703                 "%zero = OpConstant %i32 0\n"
5704                 "%constf10 = OpConstant %f32 10.0\n"
5705
5706                 "%main         = OpFunction %void None %voidf\n"
5707                 "%entry        = OpLabel\n"
5708                 "%idval        = OpLoad %uvec3 %id\n"
5709                 "%x            = OpCompositeExtract %u32 %idval 0\n"
5710                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
5711                 "%inval        = OpLoad %f32 %inloc\n"
5712                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
5713                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
5714                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
5715                 "                OpStore %outloc %fadd\n"
5716                 "                OpReturn\n"
5717                 "                OpFunctionEnd\n"
5718
5719                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
5720                 "%label        = OpLabel\n"
5721                 "                OpReturnValue %constf10\n"
5722                 "                OpFunctionEnd\n");
5723
5724         cases.push_back(CaseParameter("none",                                           "None"));
5725         cases.push_back(CaseParameter("inline",                                         "Inline"));
5726         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
5727         cases.push_back(CaseParameter("pure",                                           "Pure"));
5728         cases.push_back(CaseParameter("const",                                          "Const"));
5729         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
5730         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
5731         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
5732         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
5733
5734         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5735
5736         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5737         floorAll(inputFloats);
5738
5739         for (size_t ndx = 0; ndx < numElements; ++ndx)
5740                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
5741
5742         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5743         {
5744                 map<string, string>             specializations;
5745                 ComputeShaderSpec               spec;
5746
5747                 specializations["CONTROL"] = cases[caseNdx].param;
5748                 spec.assembly = shaderTemplate.specialize(specializations);
5749                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5750                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5751                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5752
5753                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5754         }
5755
5756         return group.release();
5757 }
5758
5759 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5760 {
5761         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5762         vector<CaseParameter>                   cases;
5763         de::Random                                              rnd                             (deStringHash(group->getName()));
5764         const int                                               numElements             = 100;
5765         vector<float>                                   inputFloats             (numElements, 0);
5766         vector<float>                                   outputFloats    (numElements, 0);
5767         const StringTemplate                    shaderTemplate  (
5768                 string(getComputeAsmShaderPreamble()) +
5769
5770                 "OpSource GLSL 430\n"
5771                 "OpName %main           \"main\"\n"
5772                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5773
5774                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5775
5776                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5777
5778                 "%f32ptr_f  = OpTypePointer Function %f32\n"
5779
5780                 "%id        = OpVariable %uvec3ptr Input\n"
5781                 "%zero      = OpConstant %i32 0\n"
5782                 "%four      = OpConstant %i32 4\n"
5783
5784                 "%main      = OpFunction %void None %voidf\n"
5785                 "%label     = OpLabel\n"
5786                 "%copy      = OpVariable %f32ptr_f Function\n"
5787                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5788                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5789                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5790                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5791                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
5792                 "%val1      = OpLoad %f32 %copy\n"
5793                 "%val2      = OpLoad %f32 %inloc\n"
5794                 "%add       = OpFAdd %f32 %val1 %val2\n"
5795                 "             OpStore %outloc %add ${ACCESS}\n"
5796                 "             OpReturn\n"
5797                 "             OpFunctionEnd\n");
5798
5799         cases.push_back(CaseParameter("null",                                   ""));
5800         cases.push_back(CaseParameter("none",                                   "None"));
5801         cases.push_back(CaseParameter("volatile",                               "Volatile"));
5802         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
5803         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
5804         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
5805         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
5806
5807         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5808
5809         for (size_t ndx = 0; ndx < numElements; ++ndx)
5810                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5811
5812         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5813         {
5814                 map<string, string>             specializations;
5815                 ComputeShaderSpec               spec;
5816
5817                 specializations["ACCESS"] = cases[caseNdx].param;
5818                 spec.assembly = shaderTemplate.specialize(specializations);
5819                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5820                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5821                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5822
5823                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5824         }
5825
5826         return group.release();
5827 }
5828
5829 // Checks that we can get undefined values for various types, without exercising a computation with it.
5830 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5831 {
5832         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5833         vector<CaseParameter>                   cases;
5834         de::Random                                              rnd                             (deStringHash(group->getName()));
5835         const int                                               numElements             = 100;
5836         vector<float>                                   positiveFloats  (numElements, 0);
5837         vector<float>                                   negativeFloats  (numElements, 0);
5838         const StringTemplate                    shaderTemplate  (
5839                 string(getComputeAsmShaderPreamble()) +
5840
5841                 "OpSource GLSL 430\n"
5842                 "OpName %main           \"main\"\n"
5843                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5844
5845                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5846
5847                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5848                 "%uvec2     = OpTypeVector %u32 2\n"
5849                 "%fvec4     = OpTypeVector %f32 4\n"
5850                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
5851                 "%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
5852                 "%sampler   = OpTypeSampler\n"
5853                 "%simage    = OpTypeSampledImage %image\n"
5854                 "%const100  = OpConstant %u32 100\n"
5855                 "%uarr100   = OpTypeArray %i32 %const100\n"
5856                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
5857                 "%pointer   = OpTypePointer Function %i32\n"
5858                 + string(getComputeAsmInputOutputBuffer()) +
5859
5860                 "%id        = OpVariable %uvec3ptr Input\n"
5861                 "%zero      = OpConstant %i32 0\n"
5862
5863                 "%main      = OpFunction %void None %voidf\n"
5864                 "%label     = OpLabel\n"
5865
5866                 "%undef     = OpUndef ${TYPE}\n"
5867
5868                 "%idval     = OpLoad %uvec3 %id\n"
5869                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5870
5871                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5872                 "%inval     = OpLoad %f32 %inloc\n"
5873                 "%neg       = OpFNegate %f32 %inval\n"
5874                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5875                 "             OpStore %outloc %neg\n"
5876                 "             OpReturn\n"
5877                 "             OpFunctionEnd\n");
5878
5879         cases.push_back(CaseParameter("bool",                   "%bool"));
5880         cases.push_back(CaseParameter("sint32",                 "%i32"));
5881         cases.push_back(CaseParameter("uint32",                 "%u32"));
5882         cases.push_back(CaseParameter("float32",                "%f32"));
5883         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
5884         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
5885         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
5886         cases.push_back(CaseParameter("image",                  "%image"));
5887         cases.push_back(CaseParameter("sampler",                "%sampler"));
5888         cases.push_back(CaseParameter("sampledimage",   "%simage"));
5889         cases.push_back(CaseParameter("array",                  "%uarr100"));
5890         cases.push_back(CaseParameter("runtimearray",   "%f32arr"));
5891         cases.push_back(CaseParameter("struct",                 "%struct"));
5892         cases.push_back(CaseParameter("pointer",                "%pointer"));
5893
5894         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5895
5896         for (size_t ndx = 0; ndx < numElements; ++ndx)
5897                 negativeFloats[ndx] = -positiveFloats[ndx];
5898
5899         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5900         {
5901                 map<string, string>             specializations;
5902                 ComputeShaderSpec               spec;
5903
5904                 specializations["TYPE"] = cases[caseNdx].param;
5905                 spec.assembly = shaderTemplate.specialize(specializations);
5906                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5907                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5908                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5909
5910                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5911         }
5912
5913                 return group.release();
5914 }
5915
5916 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
5917 tcu::TestCaseGroup* createFloat16OpConstantCompositeGroup (tcu::TestContext& testCtx)
5918 {
5919         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
5920         vector<CaseParameter>                   cases;
5921         de::Random                                              rnd                             (deStringHash(group->getName()));
5922         const int                                               numElements             = 100;
5923         vector<float>                                   positiveFloats  (numElements, 0);
5924         vector<float>                                   negativeFloats  (numElements, 0);
5925         const StringTemplate                    shaderTemplate  (
5926                 "OpCapability Shader\n"
5927                 "OpCapability Float16\n"
5928                 "OpMemoryModel Logical GLSL450\n"
5929                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5930                 "OpExecutionMode %main LocalSize 1 1 1\n"
5931                 "OpSource GLSL 430\n"
5932                 "OpName %main           \"main\"\n"
5933                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5934
5935                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5936
5937                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5938
5939                 "%id        = OpVariable %uvec3ptr Input\n"
5940                 "%zero      = OpConstant %i32 0\n"
5941                 "%f16       = OpTypeFloat 16\n"
5942                 "%c_f16_0   = OpConstant %f16 0.0\n"
5943                 "%c_f16_0_5 = OpConstant %f16 0.5\n"
5944                 "%c_f16_1   = OpConstant %f16 1.0\n"
5945                 "%v2f16     = OpTypeVector %f16 2\n"
5946                 "%v3f16     = OpTypeVector %f16 3\n"
5947                 "%v4f16     = OpTypeVector %f16 4\n"
5948
5949                 "${CONSTANT}\n"
5950
5951                 "%main      = OpFunction %void None %voidf\n"
5952                 "%label     = OpLabel\n"
5953                 "%idval     = OpLoad %uvec3 %id\n"
5954                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5955                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5956                 "%inval     = OpLoad %f32 %inloc\n"
5957                 "%neg       = OpFNegate %f32 %inval\n"
5958                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5959                 "             OpStore %outloc %neg\n"
5960                 "             OpReturn\n"
5961                 "             OpFunctionEnd\n");
5962
5963
5964         cases.push_back(CaseParameter("vector",                 "%const = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"));
5965         cases.push_back(CaseParameter("matrix",                 "%m3v3f16 = OpTypeMatrix %v3f16 3\n"
5966                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
5967                                                                                                         "%mat = OpConstantComposite %m3v3f16 %vec %vec %vec"));
5968         cases.push_back(CaseParameter("struct",                 "%m2v3f16 = OpTypeMatrix %v3f16 2\n"
5969                                                                                                         "%struct = OpTypeStruct %i32 %f16 %v3f16 %m2v3f16\n"
5970                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
5971                                                                                                         "%mat = OpConstantComposite %m2v3f16 %vec %vec\n"
5972                                                                                                         "%const = OpConstantComposite %struct %zero %c_f16_0_5 %vec %mat\n"));
5973         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %i32 %f16\n"
5974                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
5975                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
5976                                                                                                         "%st1val = OpConstantComposite %st1 %zero %c_f16_0_5\n"
5977                                                                                                         "%st2val = OpConstantComposite %st2 %zero %zero\n"
5978                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
5979
5980         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5981
5982         for (size_t ndx = 0; ndx < numElements; ++ndx)
5983                 negativeFloats[ndx] = -positiveFloats[ndx];
5984
5985         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5986         {
5987                 map<string, string>             specializations;
5988                 ComputeShaderSpec               spec;
5989
5990                 specializations["CONSTANT"] = cases[caseNdx].param;
5991                 spec.assembly = shaderTemplate.specialize(specializations);
5992                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5993                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5994                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5995
5996                 spec.extensions.push_back("VK_KHR_16bit_storage");
5997                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
5998
5999                 spec.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
6000                 spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
6001
6002                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
6003         }
6004
6005         return group.release();
6006 }
6007
6008 const vector<deFloat16> squarize(const vector<deFloat16>& inData, const deUint32 argNo)
6009 {
6010         const size_t            inDataLength    = inData.size();
6011         vector<deFloat16>       result;
6012
6013         result.reserve(inDataLength * inDataLength);
6014
6015         if (argNo == 0)
6016         {
6017                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6018                         result.insert(result.end(), inData.begin(), inData.end());
6019         }
6020
6021         if (argNo == 1)
6022         {
6023                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6024                 {
6025                         const vector<deFloat16> tmp(inDataLength, inData[numIdx]);
6026
6027                         result.insert(result.end(), tmp.begin(), tmp.end());
6028                 }
6029         }
6030
6031         return result;
6032 }
6033
6034 const vector<deFloat16> squarizeVector(const vector<deFloat16>& inData, const deUint32 argNo)
6035 {
6036         vector<deFloat16>       vec;
6037         vector<deFloat16>       result;
6038
6039         // Create vectors. vec will contain each possible pair from inData
6040         {
6041                 const size_t    inDataLength    = inData.size();
6042
6043                 DE_ASSERT(inDataLength <= 64);
6044
6045                 vec.reserve(2 * inDataLength * inDataLength);
6046
6047                 for (size_t numIdxX = 0; numIdxX < inDataLength; ++numIdxX)
6048                 for (size_t numIdxY = 0; numIdxY < inDataLength; ++numIdxY)
6049                 {
6050                         vec.push_back(inData[numIdxX]);
6051                         vec.push_back(inData[numIdxY]);
6052                 }
6053         }
6054
6055         // Create vector pairs. result will contain each possible pair from vec
6056         {
6057                 const size_t    coordsPerVector = 2;
6058                 const size_t    vectorsCount    = vec.size() / coordsPerVector;
6059
6060                 result.reserve(coordsPerVector * vectorsCount * vectorsCount);
6061
6062                 if (argNo == 0)
6063                 {
6064                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6065                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6066                         {
6067                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6068                                         result.push_back(vec[coordsPerVector * numIdxY + coordNdx]);
6069                         }
6070                 }
6071
6072                 if (argNo == 1)
6073                 {
6074                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6075                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6076                         {
6077                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6078                                         result.push_back(vec[coordsPerVector * numIdxX + coordNdx]);
6079                         }
6080                 }
6081         }
6082
6083         return result;
6084 }
6085
6086 struct fp16isNan                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isNaN(); } };
6087 struct fp16isInf                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isInf(); } };
6088 struct fp16isEqual                      { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() == in2.asFloat(); } };
6089 struct fp16isUnequal            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() != in2.asFloat(); } };
6090 struct fp16isLess                       { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <  in2.asFloat(); } };
6091 struct fp16isGreater            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >  in2.asFloat(); } };
6092 struct fp16isLessOrEqual        { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <= in2.asFloat(); } };
6093 struct fp16isGreaterOrEqual     { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >= in2.asFloat(); } };
6094
6095 template <class TestedLogicalFunction, bool onlyTestFunc, bool unationModeAnd, bool nanSupported>
6096 bool compareFP16Logical (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
6097 {
6098         if (inputs.size() != 2 || outputAllocs.size() != 1)
6099                 return false;
6100
6101         vector<deUint8> input1Bytes;
6102         vector<deUint8> input2Bytes;
6103
6104         inputs[0].getBytes(input1Bytes);
6105         inputs[1].getBytes(input2Bytes);
6106
6107         const deUint32                  denormModesCount                        = 2;
6108         const deFloat16                 float16one                                      = tcu::Float16(1.0f).bits();
6109         const deFloat16                 float16zero                                     = tcu::Float16(0.0f).bits();
6110         const tcu::Float16              zero                                            = tcu::Float16::zero(1);
6111         const deFloat16* const  outputAsFP16                            = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
6112         const deFloat16* const  input1AsFP16                            = reinterpret_cast<deFloat16* const>(&input1Bytes.front());
6113         const deFloat16* const  input2AsFP16                            = reinterpret_cast<deFloat16* const>(&input2Bytes.front());
6114         deUint32                                successfulRuns                          = denormModesCount;
6115         std::string                             results[denormModesCount];
6116         TestedLogicalFunction   testedLogicalFunction;
6117
6118         for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6119         {
6120                 const bool flushToZero = (denormMode == 1);
6121
6122                 for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deFloat16); ++idx)
6123                 {
6124                         const tcu::Float16      f1pre                   = tcu::Float16(input1AsFP16[idx]);
6125                         const tcu::Float16      f2pre                   = tcu::Float16(input2AsFP16[idx]);
6126                         const tcu::Float16      f1                              = (flushToZero && f1pre.isDenorm()) ? zero : f1pre;
6127                         const tcu::Float16      f2                              = (flushToZero && f2pre.isDenorm()) ? zero : f2pre;
6128                         deFloat16                       expectedOutput  = float16zero;
6129
6130                         if (onlyTestFunc)
6131                         {
6132                                 if (testedLogicalFunction(f1, f2))
6133                                         expectedOutput = float16one;
6134                         }
6135                         else
6136                         {
6137                                 const bool      f1nan   = f1.isNaN();
6138                                 const bool      f2nan   = f2.isNaN();
6139
6140                                 // Skip NaN floats if not supported by implementation
6141                                 if (!nanSupported && (f1nan || f2nan))
6142                                         continue;
6143
6144                                 if (unationModeAnd)
6145                                 {
6146                                         const bool      ordered         = !f1nan && !f2nan;
6147
6148                                         if (ordered && testedLogicalFunction(f1, f2))
6149                                                 expectedOutput = float16one;
6150                                 }
6151                                 else
6152                                 {
6153                                         const bool      unordered       = f1nan || f2nan;
6154
6155                                         if (unordered || testedLogicalFunction(f1, f2))
6156                                                 expectedOutput = float16one;
6157                                 }
6158                         }
6159
6160                         if (outputAsFP16[idx] != expectedOutput)
6161                         {
6162                                 std::ostringstream str;
6163
6164                                 str << "ERROR: Sub-case #" << idx
6165                                         << " flushToZero:" << flushToZero
6166                                         << std::hex
6167                                         << " failed, inputs: 0x" << f1.bits()
6168                                         << ";0x" << f2.bits()
6169                                         << " output: 0x" << outputAsFP16[idx]
6170                                         << " expected output: 0x" << expectedOutput;
6171
6172                                 results[denormMode] = str.str();
6173
6174                                 successfulRuns--;
6175
6176                                 break;
6177                         }
6178                 }
6179         }
6180
6181         if (successfulRuns == 0)
6182                 for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6183                         log << TestLog::Message << results[denormMode] << TestLog::EndMessage;
6184
6185         return successfulRuns > 0;
6186 }
6187
6188 } // anonymous
6189
6190 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
6191 {
6192         struct NameCodePair { string name, code; };
6193         RGBA                                                    defaultColors[4];
6194         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
6195         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
6196         map<string, string>                             fragments                               = passthruFragments();
6197         const NameCodePair                              tests[]                                 =
6198         {
6199                 {"unknown", "OpSource Unknown 321"},
6200                 {"essl", "OpSource ESSL 310"},
6201                 {"glsl", "OpSource GLSL 450"},
6202                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
6203                 {"opencl_c", "OpSource OpenCL_C 120"},
6204                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
6205                 {"file", opsourceGLSLWithFile},
6206                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
6207                 // Longest possible source string: SPIR-V limits instructions to 65535
6208                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
6209                 // contain 65530 UTF8 characters (one word each) plus one last word
6210                 // containing 3 ASCII characters and \0.
6211                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
6212         };
6213
6214         getDefaultColors(defaultColors);
6215         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6216         {
6217                 fragments["debug"] = tests[testNdx].code;
6218                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6219         }
6220
6221         return opSourceTests.release();
6222 }
6223
6224 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
6225 {
6226         struct NameCodePair { string name, code; };
6227         RGBA                                                            defaultColors[4];
6228         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
6229         map<string, string>                                     fragments                       = passthruFragments();
6230         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
6231         const NameCodePair                                      tests[]                         =
6232         {
6233                 {"empty", opsource + "OpSourceContinued \"\""},
6234                 {"short", opsource + "OpSourceContinued \"abcde\""},
6235                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
6236                 // Longest possible source string: SPIR-V limits instructions to 65535
6237                 // words, of which the first one is OpSourceContinued/length; the rest
6238                 // will contain 65533 UTF8 characters (one word each) plus one last word
6239                 // containing 3 ASCII characters and \0.
6240                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
6241         };
6242
6243         getDefaultColors(defaultColors);
6244         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6245         {
6246                 fragments["debug"] = tests[testNdx].code;
6247                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6248         }
6249
6250         return opSourceTests.release();
6251 }
6252 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
6253 {
6254         RGBA                                                             defaultColors[4];
6255         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
6256         map<string, string>                                      fragments;
6257         getDefaultColors(defaultColors);
6258         fragments["debug"]                      =
6259                 "%name = OpString \"name\"\n";
6260
6261         fragments["pre_main"]   =
6262                 "OpNoLine\n"
6263                 "OpNoLine\n"
6264                 "OpLine %name 1 1\n"
6265                 "OpNoLine\n"
6266                 "OpLine %name 1 1\n"
6267                 "OpLine %name 1 1\n"
6268                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6269                 "OpNoLine\n"
6270                 "OpLine %name 1 1\n"
6271                 "OpNoLine\n"
6272                 "OpLine %name 1 1\n"
6273                 "OpLine %name 1 1\n"
6274                 "%second_param1 = OpFunctionParameter %v4f32\n"
6275                 "OpNoLine\n"
6276                 "OpNoLine\n"
6277                 "%label_secondfunction = OpLabel\n"
6278                 "OpNoLine\n"
6279                 "OpReturnValue %second_param1\n"
6280                 "OpFunctionEnd\n"
6281                 "OpNoLine\n"
6282                 "OpNoLine\n";
6283
6284         fragments["testfun"]            =
6285                 // A %test_code function that returns its argument unchanged.
6286                 "OpNoLine\n"
6287                 "OpNoLine\n"
6288                 "OpLine %name 1 1\n"
6289                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6290                 "OpNoLine\n"
6291                 "%param1 = OpFunctionParameter %v4f32\n"
6292                 "OpNoLine\n"
6293                 "OpNoLine\n"
6294                 "%label_testfun = OpLabel\n"
6295                 "OpNoLine\n"
6296                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6297                 "OpReturnValue %val1\n"
6298                 "OpFunctionEnd\n"
6299                 "OpLine %name 1 1\n"
6300                 "OpNoLine\n";
6301
6302         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
6303
6304         return opLineTests.release();
6305 }
6306
6307 tcu::TestCaseGroup* createOpModuleProcessedTests(tcu::TestContext& testCtx)
6308 {
6309         RGBA                                                            defaultColors[4];
6310         de::MovePtr<tcu::TestCaseGroup>         opModuleProcessedTests                  (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "OpModuleProcessed instruction"));
6311         map<string, string>                                     fragments;
6312         std::vector<std::string>                        noExtensions;
6313         GraphicsResources                                       resources;
6314
6315         getDefaultColors(defaultColors);
6316         resources.verifyBinary = veryfiBinaryShader;
6317         resources.spirvVersion = SPIRV_VERSION_1_3;
6318
6319         fragments["moduleprocessed"]                                                    =
6320                 "OpModuleProcessed \"VULKAN CTS\"\n"
6321                 "OpModuleProcessed \"Negative values\"\n"
6322                 "OpModuleProcessed \"Date: 2017/09/21\"\n";
6323
6324         fragments["pre_main"]   =
6325                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6326                 "%second_param1 = OpFunctionParameter %v4f32\n"
6327                 "%label_secondfunction = OpLabel\n"
6328                 "OpReturnValue %second_param1\n"
6329                 "OpFunctionEnd\n";
6330
6331         fragments["testfun"]            =
6332                 // A %test_code function that returns its argument unchanged.
6333                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6334                 "%param1 = OpFunctionParameter %v4f32\n"
6335                 "%label_testfun = OpLabel\n"
6336                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6337                 "OpReturnValue %val1\n"
6338                 "OpFunctionEnd\n";
6339
6340         createTestsForAllStages ("opmoduleprocessed", defaultColors, defaultColors, fragments, resources, noExtensions, opModuleProcessedTests.get());
6341
6342         return opModuleProcessedTests.release();
6343 }
6344
6345
6346 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
6347 {
6348         RGBA                                                                                                    defaultColors[4];
6349         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
6350         map<string, string>                                                                             fragments;
6351         std::vector<std::pair<std::string, std::string> >               problemStrings;
6352
6353         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
6354         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
6355         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
6356         getDefaultColors(defaultColors);
6357
6358         fragments["debug"]                      =
6359                 "%other_name = OpString \"other_name\"\n";
6360
6361         fragments["pre_main"]   =
6362                 "OpLine %file_name 32 0\n"
6363                 "OpLine %file_name 32 32\n"
6364                 "OpLine %file_name 32 40\n"
6365                 "OpLine %other_name 32 40\n"
6366                 "OpLine %other_name 0 100\n"
6367                 "OpLine %other_name 0 4294967295\n"
6368                 "OpLine %other_name 4294967295 0\n"
6369                 "OpLine %other_name 32 40\n"
6370                 "OpLine %file_name 0 0\n"
6371                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6372                 "OpLine %file_name 1 0\n"
6373                 "%second_param1 = OpFunctionParameter %v4f32\n"
6374                 "OpLine %file_name 1 3\n"
6375                 "OpLine %file_name 1 2\n"
6376                 "%label_secondfunction = OpLabel\n"
6377                 "OpLine %file_name 0 2\n"
6378                 "OpReturnValue %second_param1\n"
6379                 "OpFunctionEnd\n"
6380                 "OpLine %file_name 0 2\n"
6381                 "OpLine %file_name 0 2\n";
6382
6383         fragments["testfun"]            =
6384                 // A %test_code function that returns its argument unchanged.
6385                 "OpLine %file_name 1 0\n"
6386                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6387                 "OpLine %file_name 16 330\n"
6388                 "%param1 = OpFunctionParameter %v4f32\n"
6389                 "OpLine %file_name 14 442\n"
6390                 "%label_testfun = OpLabel\n"
6391                 "OpLine %file_name 11 1024\n"
6392                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6393                 "OpLine %file_name 2 97\n"
6394                 "OpReturnValue %val1\n"
6395                 "OpFunctionEnd\n"
6396                 "OpLine %file_name 5 32\n";
6397
6398         for (size_t i = 0; i < problemStrings.size(); ++i)
6399         {
6400                 map<string, string> testFragments = fragments;
6401                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
6402                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
6403         }
6404
6405         return opLineTests.release();
6406 }
6407
6408 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
6409 {
6410         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
6411         RGBA                                                    colors[4];
6412
6413
6414         const char                                              functionStart[] =
6415                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6416                 "%param1 = OpFunctionParameter %v4f32\n"
6417                 "%lbl    = OpLabel\n";
6418
6419         const char                                              functionEnd[]   =
6420                 "OpReturnValue %transformed_param\n"
6421                 "OpFunctionEnd\n";
6422
6423         struct NameConstantsCode
6424         {
6425                 string name;
6426                 string constants;
6427                 string code;
6428         };
6429
6430         NameConstantsCode tests[] =
6431         {
6432                 {
6433                         "vec4",
6434                         "%cnull = OpConstantNull %v4f32\n",
6435                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
6436                 },
6437                 {
6438                         "float",
6439                         "%cnull = OpConstantNull %f32\n",
6440                         "%vp = OpVariable %fp_v4f32 Function\n"
6441                         "%v  = OpLoad %v4f32 %vp\n"
6442                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
6443                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
6444                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
6445                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
6446                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
6447                 },
6448                 {
6449                         "bool",
6450                         "%cnull             = OpConstantNull %bool\n",
6451                         "%v                 = OpVariable %fp_v4f32 Function\n"
6452                         "                     OpStore %v %param1\n"
6453                         "                     OpSelectionMerge %false_label None\n"
6454                         "                     OpBranchConditional %cnull %true_label %false_label\n"
6455                         "%true_label        = OpLabel\n"
6456                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
6457                         "                     OpBranch %false_label\n"
6458                         "%false_label       = OpLabel\n"
6459                         "%transformed_param = OpLoad %v4f32 %v\n"
6460                 },
6461                 {
6462                         "i32",
6463                         "%cnull             = OpConstantNull %i32\n",
6464                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
6465                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
6466                         "                     OpSelectionMerge %false_label None\n"
6467                         "                     OpBranchConditional %b %true_label %false_label\n"
6468                         "%true_label        = OpLabel\n"
6469                         "                     OpStore %v %param1\n"
6470                         "                     OpBranch %false_label\n"
6471                         "%false_label       = OpLabel\n"
6472                         "%transformed_param = OpLoad %v4f32 %v\n"
6473                 },
6474                 {
6475                         "struct",
6476                         "%stype             = OpTypeStruct %f32 %v4f32\n"
6477                         "%fp_stype          = OpTypePointer Function %stype\n"
6478                         "%cnull             = OpConstantNull %stype\n",
6479                         "%v                 = OpVariable %fp_stype Function %cnull\n"
6480                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
6481                         "%f_val             = OpLoad %v4f32 %f\n"
6482                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
6483                 },
6484                 {
6485                         "array",
6486                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
6487                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
6488                         "%cnull             = OpConstantNull %a4_v4f32\n",
6489                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
6490                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6491                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
6492                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
6493                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
6494                         "%f_val             = OpLoad %v4f32 %f\n"
6495                         "%f1_val            = OpLoad %v4f32 %f1\n"
6496                         "%f2_val            = OpLoad %v4f32 %f2\n"
6497                         "%f3_val            = OpLoad %v4f32 %f3\n"
6498                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
6499                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
6500                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
6501                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
6502                 },
6503                 {
6504                         "matrix",
6505                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
6506                         "%cnull             = OpConstantNull %mat4x4_f32\n",
6507                         // Our null matrix * any vector should result in a zero vector.
6508                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
6509                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
6510                 }
6511         };
6512
6513         getHalfColorsFullAlpha(colors);
6514
6515         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6516         {
6517                 map<string, string> fragments;
6518                 fragments["pre_main"] = tests[testNdx].constants;
6519                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6520                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
6521         }
6522         return opConstantNullTests.release();
6523 }
6524 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
6525 {
6526         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
6527         RGBA                                                    inputColors[4];
6528         RGBA                                                    outputColors[4];
6529
6530
6531         const char                                              functionStart[]  =
6532                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6533                 "%param1 = OpFunctionParameter %v4f32\n"
6534                 "%lbl    = OpLabel\n";
6535
6536         const char                                              functionEnd[]           =
6537                 "OpReturnValue %transformed_param\n"
6538                 "OpFunctionEnd\n";
6539
6540         struct NameConstantsCode
6541         {
6542                 string name;
6543                 string constants;
6544                 string code;
6545         };
6546
6547         NameConstantsCode tests[] =
6548         {
6549                 {
6550                         "vec4",
6551
6552                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
6553                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
6554                 },
6555                 {
6556                         "struct",
6557
6558                         "%stype             = OpTypeStruct %v4f32 %f32\n"
6559                         "%fp_stype          = OpTypePointer Function %stype\n"
6560                         "%f32_n_1           = OpConstant %f32 -1.0\n"
6561                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
6562                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
6563                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
6564
6565                         "%v                 = OpVariable %fp_stype Function %cval\n"
6566                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6567                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
6568                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
6569                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
6570                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
6571                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
6572                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
6573                 },
6574                 {
6575                         // [1|0|0|0.5] [x] = x + 0.5
6576                         // [0|1|0|0.5] [y] = y + 0.5
6577                         // [0|0|1|0.5] [z] = z + 0.5
6578                         // [0|0|0|1  ] [1] = 1
6579                         "matrix",
6580
6581                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
6582                         "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
6583                         "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
6584                         "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
6585                         "%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"
6586                         "%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",
6587
6588                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
6589                 },
6590                 {
6591                         "array",
6592
6593                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6594                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6595                         "%f32_n_1             = OpConstant %f32 -1.0\n"
6596                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
6597                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
6598
6599                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
6600                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
6601                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
6602                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
6603                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
6604                         "%f_val               = OpLoad %f32 %f\n"
6605                         "%f1_val              = OpLoad %f32 %f1\n"
6606                         "%f2_val              = OpLoad %f32 %f2\n"
6607                         "%f3_val              = OpLoad %f32 %f3\n"
6608                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
6609                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
6610                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
6611                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
6612                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6613                 },
6614                 {
6615                         //
6616                         // [
6617                         //   {
6618                         //      0.0,
6619                         //      [ 1.0, 1.0, 1.0, 1.0]
6620                         //   },
6621                         //   {
6622                         //      1.0,
6623                         //      [ 0.0, 0.5, 0.0, 0.0]
6624                         //   }, //     ^^^
6625                         //   {
6626                         //      0.0,
6627                         //      [ 1.0, 1.0, 1.0, 1.0]
6628                         //   }
6629                         // ]
6630                         "array_of_struct_of_array",
6631
6632                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6633                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6634                         "%stype               = OpTypeStruct %f32 %a4f32\n"
6635                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
6636                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
6637                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
6638                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6639                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
6640                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
6641                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
6642
6643                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
6644                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
6645                         "%f_l                 = OpLoad %f32 %f\n"
6646                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
6647                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6648                 }
6649         };
6650
6651         getHalfColorsFullAlpha(inputColors);
6652         outputColors[0] = RGBA(255, 255, 255, 255);
6653         outputColors[1] = RGBA(255, 127, 127, 255);
6654         outputColors[2] = RGBA(127, 255, 127, 255);
6655         outputColors[3] = RGBA(127, 127, 255, 255);
6656
6657         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6658         {
6659                 map<string, string> fragments;
6660                 fragments["pre_main"] = tests[testNdx].constants;
6661                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6662                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
6663         }
6664         return opConstantCompositeTests.release();
6665 }
6666
6667 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
6668 {
6669         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
6670         RGBA                                                    inputColors[4];
6671         RGBA                                                    outputColors[4];
6672         map<string, string>                             fragments;
6673
6674         // vec4 test_code(vec4 param) {
6675         //   vec4 result = param;
6676         //   for (int i = 0; i < 4; ++i) {
6677         //     if (i == 0) result[i] = 0.;
6678         //     else        result[i] = 1. - result[i];
6679         //   }
6680         //   return result;
6681         // }
6682         const char                                              function[]                      =
6683                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6684                 "%param1    = OpFunctionParameter %v4f32\n"
6685                 "%lbl       = OpLabel\n"
6686                 "%iptr      = OpVariable %fp_i32 Function\n"
6687                 "%result    = OpVariable %fp_v4f32 Function\n"
6688                 "             OpStore %iptr %c_i32_0\n"
6689                 "             OpStore %result %param1\n"
6690                 "             OpBranch %loop\n"
6691
6692                 // Loop entry block.
6693                 "%loop      = OpLabel\n"
6694                 "%ival      = OpLoad %i32 %iptr\n"
6695                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6696                 "             OpLoopMerge %exit %if_entry None\n"
6697                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
6698
6699                 // Merge block for loop.
6700                 "%exit      = OpLabel\n"
6701                 "%ret       = OpLoad %v4f32 %result\n"
6702                 "             OpReturnValue %ret\n"
6703
6704                 // If-statement entry block.
6705                 "%if_entry  = OpLabel\n"
6706                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6707                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
6708                 "             OpSelectionMerge %if_exit None\n"
6709                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
6710
6711                 // False branch for if-statement.
6712                 "%if_false  = OpLabel\n"
6713                 "%val       = OpLoad %f32 %loc\n"
6714                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
6715                 "             OpStore %loc %sub\n"
6716                 "             OpBranch %if_exit\n"
6717
6718                 // Merge block for if-statement.
6719                 "%if_exit   = OpLabel\n"
6720                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6721                 "             OpStore %iptr %ival_next\n"
6722                 "             OpBranch %loop\n"
6723
6724                 // True branch for if-statement.
6725                 "%if_true   = OpLabel\n"
6726                 "             OpStore %loc %c_f32_0\n"
6727                 "             OpBranch %if_exit\n"
6728
6729                 "             OpFunctionEnd\n";
6730
6731         fragments["testfun"]    = function;
6732
6733         inputColors[0]                  = RGBA(127, 127, 127, 0);
6734         inputColors[1]                  = RGBA(127, 0,   0,   0);
6735         inputColors[2]                  = RGBA(0,   127, 0,   0);
6736         inputColors[3]                  = RGBA(0,   0,   127, 0);
6737
6738         outputColors[0]                 = RGBA(0, 128, 128, 255);
6739         outputColors[1]                 = RGBA(0, 255, 255, 255);
6740         outputColors[2]                 = RGBA(0, 128, 255, 255);
6741         outputColors[3]                 = RGBA(0, 255, 128, 255);
6742
6743         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6744
6745         return group.release();
6746 }
6747
6748 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
6749 {
6750         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
6751         RGBA                                                    inputColors[4];
6752         RGBA                                                    outputColors[4];
6753         map<string, string>                             fragments;
6754
6755         const char                                              typesAndConstants[]     =
6756                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6757                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6758                 "%c_f32_p6  = OpConstant %f32 0.6\n"
6759                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6760
6761         // vec4 test_code(vec4 param) {
6762         //   vec4 result = param;
6763         //   for (int i = 0; i < 4; ++i) {
6764         //     switch (i) {
6765         //       case 0: result[i] += .2; break;
6766         //       case 1: result[i] += .6; break;
6767         //       case 2: result[i] += .4; break;
6768         //       case 3: result[i] += .8; break;
6769         //       default: break; // unreachable
6770         //     }
6771         //   }
6772         //   return result;
6773         // }
6774         const char                                              function[]                      =
6775                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6776                 "%param1    = OpFunctionParameter %v4f32\n"
6777                 "%lbl       = OpLabel\n"
6778                 "%iptr      = OpVariable %fp_i32 Function\n"
6779                 "%result    = OpVariable %fp_v4f32 Function\n"
6780                 "             OpStore %iptr %c_i32_0\n"
6781                 "             OpStore %result %param1\n"
6782                 "             OpBranch %loop\n"
6783
6784                 // Loop entry block.
6785                 "%loop      = OpLabel\n"
6786                 "%ival      = OpLoad %i32 %iptr\n"
6787                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6788                 "             OpLoopMerge %exit %switch_exit None\n"
6789                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
6790
6791                 // Merge block for loop.
6792                 "%exit      = OpLabel\n"
6793                 "%ret       = OpLoad %v4f32 %result\n"
6794                 "             OpReturnValue %ret\n"
6795
6796                 // Switch-statement entry block.
6797                 "%switch_entry   = OpLabel\n"
6798                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
6799                 "%val            = OpLoad %f32 %loc\n"
6800                 "                  OpSelectionMerge %switch_exit None\n"
6801                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6802
6803                 "%case2          = OpLabel\n"
6804                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
6805                 "                  OpStore %loc %addp4\n"
6806                 "                  OpBranch %switch_exit\n"
6807
6808                 "%switch_default = OpLabel\n"
6809                 "                  OpUnreachable\n"
6810
6811                 "%case3          = OpLabel\n"
6812                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
6813                 "                  OpStore %loc %addp8\n"
6814                 "                  OpBranch %switch_exit\n"
6815
6816                 "%case0          = OpLabel\n"
6817                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
6818                 "                  OpStore %loc %addp2\n"
6819                 "                  OpBranch %switch_exit\n"
6820
6821                 // Merge block for switch-statement.
6822                 "%switch_exit    = OpLabel\n"
6823                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
6824                 "                  OpStore %iptr %ival_next\n"
6825                 "                  OpBranch %loop\n"
6826
6827                 "%case1          = OpLabel\n"
6828                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
6829                 "                  OpStore %loc %addp6\n"
6830                 "                  OpBranch %switch_exit\n"
6831
6832                 "                  OpFunctionEnd\n";
6833
6834         fragments["pre_main"]   = typesAndConstants;
6835         fragments["testfun"]    = function;
6836
6837         inputColors[0]                  = RGBA(127, 27,  127, 51);
6838         inputColors[1]                  = RGBA(127, 0,   0,   51);
6839         inputColors[2]                  = RGBA(0,   27,  0,   51);
6840         inputColors[3]                  = RGBA(0,   0,   127, 51);
6841
6842         outputColors[0]                 = RGBA(178, 180, 229, 255);
6843         outputColors[1]                 = RGBA(178, 153, 102, 255);
6844         outputColors[2]                 = RGBA(51,  180, 102, 255);
6845         outputColors[3]                 = RGBA(51,  153, 229, 255);
6846
6847         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6848
6849         return group.release();
6850 }
6851
6852 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
6853 {
6854         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
6855         RGBA                                                    inputColors[4];
6856         RGBA                                                    outputColors[4];
6857         map<string, string>                             fragments;
6858
6859         const char                                              decorations[]           =
6860                 "OpDecorate %array_group         ArrayStride 4\n"
6861                 "OpDecorate %struct_member_group Offset 0\n"
6862                 "%array_group         = OpDecorationGroup\n"
6863                 "%struct_member_group = OpDecorationGroup\n"
6864
6865                 "OpDecorate %group1 RelaxedPrecision\n"
6866                 "OpDecorate %group3 RelaxedPrecision\n"
6867                 "OpDecorate %group3 Invariant\n"
6868                 "OpDecorate %group3 Restrict\n"
6869                 "%group0 = OpDecorationGroup\n"
6870                 "%group1 = OpDecorationGroup\n"
6871                 "%group3 = OpDecorationGroup\n";
6872
6873         const char                                              typesAndConstants[]     =
6874                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
6875                 "%struct1   = OpTypeStruct %a3f32\n"
6876                 "%struct2   = OpTypeStruct %a3f32\n"
6877                 "%fp_struct1 = OpTypePointer Function %struct1\n"
6878                 "%fp_struct2 = OpTypePointer Function %struct2\n"
6879                 "%c_f32_2    = OpConstant %f32 2.\n"
6880                 "%c_f32_n2   = OpConstant %f32 -2.\n"
6881
6882                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
6883                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
6884                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
6885                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
6886
6887         const char                                              function[]                      =
6888                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6889                 "%param     = OpFunctionParameter %v4f32\n"
6890                 "%entry     = OpLabel\n"
6891                 "%result    = OpVariable %fp_v4f32 Function\n"
6892                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
6893                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
6894                 "             OpStore %result %param\n"
6895                 "             OpStore %v_struct1 %c_struct1\n"
6896                 "             OpStore %v_struct2 %c_struct2\n"
6897                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
6898                 "%val1      = OpLoad %f32 %ptr1\n"
6899                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
6900                 "%val2      = OpLoad %f32 %ptr2\n"
6901                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
6902                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6903                 "%val       = OpLoad %f32 %ptr\n"
6904                 "%addresult = OpFAdd %f32 %addvalues %val\n"
6905                 "             OpStore %ptr %addresult\n"
6906                 "%ret       = OpLoad %v4f32 %result\n"
6907                 "             OpReturnValue %ret\n"
6908                 "             OpFunctionEnd\n";
6909
6910         struct CaseNameDecoration
6911         {
6912                 string name;
6913                 string decoration;
6914         };
6915
6916         CaseNameDecoration tests[] =
6917         {
6918                 {
6919                         "same_decoration_group_on_multiple_types",
6920                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
6921                 },
6922                 {
6923                         "empty_decoration_group",
6924                         "OpGroupDecorate %group0      %a3f32\n"
6925                         "OpGroupDecorate %group0      %result\n"
6926                 },
6927                 {
6928                         "one_element_decoration_group",
6929                         "OpGroupDecorate %array_group %a3f32\n"
6930                 },
6931                 {
6932                         "multiple_elements_decoration_group",
6933                         "OpGroupDecorate %group3      %v_struct1\n"
6934                 },
6935                 {
6936                         "multiple_decoration_groups_on_same_variable",
6937                         "OpGroupDecorate %group0      %v_struct2\n"
6938                         "OpGroupDecorate %group1      %v_struct2\n"
6939                         "OpGroupDecorate %group3      %v_struct2\n"
6940                 },
6941                 {
6942                         "same_decoration_group_multiple_times",
6943                         "OpGroupDecorate %group1      %addvalues\n"
6944                         "OpGroupDecorate %group1      %addvalues\n"
6945                         "OpGroupDecorate %group1      %addvalues\n"
6946                 },
6947
6948         };
6949
6950         getHalfColorsFullAlpha(inputColors);
6951         getHalfColorsFullAlpha(outputColors);
6952
6953         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
6954         {
6955                 fragments["decoration"] = decorations + tests[idx].decoration;
6956                 fragments["pre_main"]   = typesAndConstants;
6957                 fragments["testfun"]    = function;
6958
6959                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
6960         }
6961
6962         return group.release();
6963 }
6964
6965 struct SpecConstantTwoIntGraphicsCase
6966 {
6967         const char*             caseName;
6968         const char*             scDefinition0;
6969         const char*             scDefinition1;
6970         const char*             scResultType;
6971         const char*             scOperation;
6972         deInt32                 scActualValue0;
6973         deInt32                 scActualValue1;
6974         const char*             resultOperation;
6975         RGBA                    expectedColors[4];
6976         deInt32                 scActualValueLength;
6977
6978                                         SpecConstantTwoIntGraphicsCase (const char*             name,
6979                                                                                                         const char*             definition0,
6980                                                                                                         const char*             definition1,
6981                                                                                                         const char*             resultType,
6982                                                                                                         const char*             operation,
6983                                                                                                         const deInt32   value0,
6984                                                                                                         const deInt32   value1,
6985                                                                                                         const char*             resultOp,
6986                                                                                                         const RGBA              (&output)[4],
6987                                                                                                         const deInt32   valueLength = sizeof(deInt32))
6988                                                 : caseName                              (name)
6989                                                 , scDefinition0                 (definition0)
6990                                                 , scDefinition1                 (definition1)
6991                                                 , scResultType                  (resultType)
6992                                                 , scOperation                   (operation)
6993                                                 , scActualValue0                (value0)
6994                                                 , scActualValue1                (value1)
6995                                                 , resultOperation               (resultOp)
6996                                                 , scActualValueLength   (valueLength)
6997         {
6998                 expectedColors[0] = output[0];
6999                 expectedColors[1] = output[1];
7000                 expectedColors[2] = output[2];
7001                 expectedColors[3] = output[3];
7002         }
7003 };
7004
7005 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
7006 {
7007         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
7008         vector<SpecConstantTwoIntGraphicsCase>  cases;
7009         RGBA                                                    inputColors[4];
7010         RGBA                                                    outputColors0[4];
7011         RGBA                                                    outputColors1[4];
7012         RGBA                                                    outputColors2[4];
7013
7014         const deInt32                                   m1AsFloat16                     = 0xbc00; // -1(fp16) == 1 01111 0000000000 == 1011 1100 0000 0000
7015
7016         const char      decorations1[]                  =
7017                 "OpDecorate %sc_0  SpecId 0\n"
7018                 "OpDecorate %sc_1  SpecId 1\n";
7019
7020         const char      typesAndConstants1[]    =
7021                 "${OPTYPE_DEFINITIONS:opt}"
7022                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
7023                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
7024                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
7025
7026         const char      function1[]                             =
7027                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7028                 "%param     = OpFunctionParameter %v4f32\n"
7029                 "%label     = OpLabel\n"
7030                 "%result    = OpVariable %fp_v4f32 Function\n"
7031                 "${TYPE_CONVERT:opt}"
7032                 "             OpStore %result %param\n"
7033                 "%gen       = ${GEN_RESULT}\n"
7034                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
7035                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
7036                 "%val       = OpLoad %f32 %loc\n"
7037                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7038                 "             OpStore %loc %add\n"
7039                 "%ret       = OpLoad %v4f32 %result\n"
7040                 "             OpReturnValue %ret\n"
7041                 "             OpFunctionEnd\n";
7042
7043         inputColors[0] = RGBA(127, 127, 127, 255);
7044         inputColors[1] = RGBA(127, 0,   0,   255);
7045         inputColors[2] = RGBA(0,   127, 0,   255);
7046         inputColors[3] = RGBA(0,   0,   127, 255);
7047
7048         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
7049         outputColors0[0] = RGBA(255, 127, 127, 255);
7050         outputColors0[1] = RGBA(255, 0,   0,   255);
7051         outputColors0[2] = RGBA(128, 127, 0,   255);
7052         outputColors0[3] = RGBA(128, 0,   127, 255);
7053
7054         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
7055         outputColors1[0] = RGBA(127, 255, 127, 255);
7056         outputColors1[1] = RGBA(127, 128, 0,   255);
7057         outputColors1[2] = RGBA(0,   255, 0,   255);
7058         outputColors1[3] = RGBA(0,   128, 127, 255);
7059
7060         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
7061         outputColors2[0] = RGBA(127, 127, 255, 255);
7062         outputColors2[1] = RGBA(127, 0,   128, 255);
7063         outputColors2[2] = RGBA(0,   127, 128, 255);
7064         outputColors2[3] = RGBA(0,   0,   255, 255);
7065
7066         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
7067         const char addZeroToSc32[]              = "OpIAdd %i32 %c_i32_0 %sc_op32";
7068         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
7069         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
7070
7071         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
7072         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
7073         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
7074         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
7075         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
7076         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7077         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7078         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
7079         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
7080         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
7081         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
7082         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
7083         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
7084         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
7085         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
7086         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
7087         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7088         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
7089         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
7090         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
7091         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7092         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
7093         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
7094         cases.push_back(SpecConstantTwoIntGraphicsCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                             42,             24,             selectTrueUsingSc,      outputColors2));
7095         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7096         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7097         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7098         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7099         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
7100         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
7101         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
7102         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
7103         cases.push_back(SpecConstantTwoIntGraphicsCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                                   -1,             0,              addZeroToSc32,          outputColors0));
7104         // -1082130432 stored as 32-bit two's complement is the binary representation of -1 as IEEE-754 Float
7105         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                                   -1082130432, 0, addZeroToSc32,          outputColors0));
7106         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                                   m1AsFloat16, 0, addZeroToSc32,          outputColors0, sizeof(deFloat16)));
7107         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
7108
7109         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
7110         {
7111                 map<string, string>                     specializations;
7112                 map<string, string>                     fragments;
7113                 SpecConstants                           specConstants;
7114                 PushConstants                           noPushConstants;
7115                 GraphicsResources                       noResources;
7116                 GraphicsInterfaces                      noInterfaces;
7117                 vector<string>                          extensions;
7118                 VulkanFeatures                          requiredFeatures;
7119
7120                 // Special SPIR-V code for SConvert-case
7121                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
7122                 {
7123                         requiredFeatures.coreFeatures.shaderInt16 = VK_TRUE;
7124                         fragments["capability"]                                 = "OpCapability Int16\n";                                       // Adds 16-bit integer capability
7125                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                            // Adds 16-bit integer type
7126                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpSConvert %i32 %sc_op\n";        // Converts 16-bit integer to 32-bit integer
7127                 }
7128
7129                 // Special SPIR-V code for FConvert-case
7130                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
7131                 {
7132                         requiredFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
7133                         fragments["capability"]                                 = "OpCapability Float64\n";                                     // Adds 64-bit float capability
7134                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                            // Adds 64-bit float type
7135                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 64-bit float to 32-bit integer
7136                 }
7137
7138                 // Special SPIR-V code for FConvert-case for 16-bit floats
7139                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
7140                 {
7141                         extensions.push_back("VK_KHR_shader_float16_int8");
7142                         requiredFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
7143                         fragments["capability"]                                 = "OpCapability Float16\n";                                     // Adds 16-bit float capability
7144                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                            // Adds 16-bit float type
7145                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 16-bit float to 32-bit integer
7146                 }
7147
7148                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
7149                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
7150                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
7151                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
7152                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
7153
7154                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
7155                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
7156                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
7157
7158                 specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
7159                 specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
7160
7161                 createTestsForAllStages(
7162                         cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants,
7163                         noPushConstants, noResources, noInterfaces, extensions, requiredFeatures, group.get());
7164         }
7165
7166         const char      decorations2[]                  =
7167                 "OpDecorate %sc_0  SpecId 0\n"
7168                 "OpDecorate %sc_1  SpecId 1\n"
7169                 "OpDecorate %sc_2  SpecId 2\n";
7170
7171         const char      typesAndConstants2[]    =
7172                 "%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
7173                 "%vec3_undef  = OpUndef %v3i32\n"
7174
7175                 "%sc_0        = OpSpecConstant %i32 0\n"
7176                 "%sc_1        = OpSpecConstant %i32 0\n"
7177                 "%sc_2        = OpSpecConstant %i32 0\n"
7178                 "%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0      0\n"                                                 // (sc_0, 0,    0)
7179                 "%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0      1\n"                                                 // (0,    sc_1, 0)
7180                 "%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0      2\n"                                                 // (0,    0,    sc_2)
7181                 "%sc_vec3_0_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
7182                 "%sc_vec3_1_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
7183                 "%sc_vec3_2_s = OpSpecConstantOp %v3i32 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
7184                 "%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
7185                 "%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
7186                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
7187                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
7188                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
7189                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
7190                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";                                                             // (sc_2 - sc_0) * sc_1
7191
7192         const char      function2[]                             =
7193                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7194                 "%param     = OpFunctionParameter %v4f32\n"
7195                 "%label     = OpLabel\n"
7196                 "%result    = OpVariable %fp_v4f32 Function\n"
7197                 "             OpStore %result %param\n"
7198                 "%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
7199                 "%val       = OpLoad %f32 %loc\n"
7200                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7201                 "             OpStore %loc %add\n"
7202                 "%ret       = OpLoad %v4f32 %result\n"
7203                 "             OpReturnValue %ret\n"
7204                 "             OpFunctionEnd\n";
7205
7206         map<string, string>     fragments;
7207         SpecConstants           specConstants;
7208
7209         fragments["decoration"] = decorations2;
7210         fragments["pre_main"]   = typesAndConstants2;
7211         fragments["testfun"]    = function2;
7212
7213         specConstants.append<deInt32>(56789);
7214         specConstants.append<deInt32>(-2);
7215         specConstants.append<deInt32>(56788);
7216
7217         createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
7218
7219         return group.release();
7220 }
7221
7222 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
7223 {
7224         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
7225         RGBA                                                    inputColors[4];
7226         RGBA                                                    outputColors1[4];
7227         RGBA                                                    outputColors2[4];
7228         RGBA                                                    outputColors3[4];
7229         RGBA                                                    outputColors4[4];
7230         map<string, string>                             fragments1;
7231         map<string, string>                             fragments2;
7232         map<string, string>                             fragments3;
7233         map<string, string>                             fragments4;
7234         std::vector<std::string>                extensions4;
7235         GraphicsResources                               resources4;
7236         VulkanFeatures                                  vulkanFeatures4;
7237
7238         const char      typesAndConstants1[]    =
7239                 "%c_f32_p2  = OpConstant %f32 0.2\n"
7240                 "%c_f32_p4  = OpConstant %f32 0.4\n"
7241                 "%c_f32_p5  = OpConstant %f32 0.5\n"
7242                 "%c_f32_p8  = OpConstant %f32 0.8\n";
7243
7244         // vec4 test_code(vec4 param) {
7245         //   vec4 result = param;
7246         //   for (int i = 0; i < 4; ++i) {
7247         //     float operand;
7248         //     switch (i) {
7249         //       case 0: operand = .2; break;
7250         //       case 1: operand = .5; break;
7251         //       case 2: operand = .4; break;
7252         //       case 3: operand = .0; break;
7253         //       default: break; // unreachable
7254         //     }
7255         //     result[i] += operand;
7256         //   }
7257         //   return result;
7258         // }
7259         const char      function1[]                             =
7260                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7261                 "%param1    = OpFunctionParameter %v4f32\n"
7262                 "%lbl       = OpLabel\n"
7263                 "%iptr      = OpVariable %fp_i32 Function\n"
7264                 "%result    = OpVariable %fp_v4f32 Function\n"
7265                 "             OpStore %iptr %c_i32_0\n"
7266                 "             OpStore %result %param1\n"
7267                 "             OpBranch %loop\n"
7268
7269                 "%loop      = OpLabel\n"
7270                 "%ival      = OpLoad %i32 %iptr\n"
7271                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
7272                 "             OpLoopMerge %exit %phi None\n"
7273                 "             OpBranchConditional %lt_4 %entry %exit\n"
7274
7275                 "%entry     = OpLabel\n"
7276                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
7277                 "%val       = OpLoad %f32 %loc\n"
7278                 "             OpSelectionMerge %phi None\n"
7279                 "             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
7280
7281                 "%case0     = OpLabel\n"
7282                 "             OpBranch %phi\n"
7283                 "%case1     = OpLabel\n"
7284                 "             OpBranch %phi\n"
7285                 "%case2     = OpLabel\n"
7286                 "             OpBranch %phi\n"
7287                 "%case3     = OpLabel\n"
7288                 "             OpBranch %phi\n"
7289
7290                 "%default   = OpLabel\n"
7291                 "             OpUnreachable\n"
7292
7293                 "%phi       = OpLabel\n"
7294                 "%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
7295                 "%add       = OpFAdd %f32 %val %operand\n"
7296                 "             OpStore %loc %add\n"
7297                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
7298                 "             OpStore %iptr %ival_next\n"
7299                 "             OpBranch %loop\n"
7300
7301                 "%exit      = OpLabel\n"
7302                 "%ret       = OpLoad %v4f32 %result\n"
7303                 "             OpReturnValue %ret\n"
7304
7305                 "             OpFunctionEnd\n";
7306
7307         fragments1["pre_main"]  = typesAndConstants1;
7308         fragments1["testfun"]   = function1;
7309
7310         getHalfColorsFullAlpha(inputColors);
7311
7312         outputColors1[0]                = RGBA(178, 255, 229, 255);
7313         outputColors1[1]                = RGBA(178, 127, 102, 255);
7314         outputColors1[2]                = RGBA(51,  255, 102, 255);
7315         outputColors1[3]                = RGBA(51,  127, 229, 255);
7316
7317         createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
7318
7319         const char      typesAndConstants2[]    =
7320                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7321
7322         // Add .4 to the second element of the given parameter.
7323         const char      function2[]                             =
7324                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7325                 "%param     = OpFunctionParameter %v4f32\n"
7326                 "%entry     = OpLabel\n"
7327                 "%result    = OpVariable %fp_v4f32 Function\n"
7328                 "             OpStore %result %param\n"
7329                 "%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7330                 "%val       = OpLoad %f32 %loc\n"
7331                 "             OpBranch %phi\n"
7332
7333                 "%phi        = OpLabel\n"
7334                 "%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
7335                 "%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
7336                 "%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
7337                 "%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
7338                 "%still_loop = OpSLessThan %bool %step %c_i32_2\n"
7339                 "              OpLoopMerge %exit %phi None\n"
7340                 "              OpBranchConditional %still_loop %phi %exit\n"
7341
7342                 "%exit       = OpLabel\n"
7343                 "              OpStore %loc %accum\n"
7344                 "%ret        = OpLoad %v4f32 %result\n"
7345                 "              OpReturnValue %ret\n"
7346
7347                 "              OpFunctionEnd\n";
7348
7349         fragments2["pre_main"]  = typesAndConstants2;
7350         fragments2["testfun"]   = function2;
7351
7352         outputColors2[0]                        = RGBA(127, 229, 127, 255);
7353         outputColors2[1]                        = RGBA(127, 102, 0,   255);
7354         outputColors2[2]                        = RGBA(0,   229, 0,   255);
7355         outputColors2[3]                        = RGBA(0,   102, 127, 255);
7356
7357         createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
7358
7359         const char      typesAndConstants3[]    =
7360                 "%true      = OpConstantTrue %bool\n"
7361                 "%false     = OpConstantFalse %bool\n"
7362                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7363
7364         // Swap the second and the third element of the given parameter.
7365         const char      function3[]                             =
7366                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7367                 "%param     = OpFunctionParameter %v4f32\n"
7368                 "%entry     = OpLabel\n"
7369                 "%result    = OpVariable %fp_v4f32 Function\n"
7370                 "             OpStore %result %param\n"
7371                 "%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
7372                 "%a_init    = OpLoad %f32 %a_loc\n"
7373                 "%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
7374                 "%b_init    = OpLoad %f32 %b_loc\n"
7375                 "             OpBranch %phi\n"
7376
7377                 "%phi        = OpLabel\n"
7378                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7379                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
7380                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
7381                 "              OpLoopMerge %exit %phi None\n"
7382                 "              OpBranchConditional %still_loop %phi %exit\n"
7383
7384                 "%exit       = OpLabel\n"
7385                 "              OpStore %a_loc %a_next\n"
7386                 "              OpStore %b_loc %b_next\n"
7387                 "%ret        = OpLoad %v4f32 %result\n"
7388                 "              OpReturnValue %ret\n"
7389
7390                 "              OpFunctionEnd\n";
7391
7392         fragments3["pre_main"]  = typesAndConstants3;
7393         fragments3["testfun"]   = function3;
7394
7395         outputColors3[0]                        = RGBA(127, 127, 127, 255);
7396         outputColors3[1]                        = RGBA(127, 0,   0,   255);
7397         outputColors3[2]                        = RGBA(0,   0,   127, 255);
7398         outputColors3[3]                        = RGBA(0,   127, 0,   255);
7399
7400         createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
7401
7402         const char      typesAndConstants4[]    =
7403                 "%f16        = OpTypeFloat 16\n"
7404                 "%v4f16      = OpTypeVector %f16 4\n"
7405                 "%fp_f16     = OpTypePointer Function %f16\n"
7406                 "%fp_v4f16   = OpTypePointer Function %v4f16\n"
7407                 "%true       = OpConstantTrue %bool\n"
7408                 "%false      = OpConstantFalse %bool\n"
7409                 "%c_f32_p2   = OpConstant %f32 0.2\n";
7410
7411         // Swap the second and the third element of the given parameter.
7412         const char      function4[]                             =
7413                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7414                 "%param      = OpFunctionParameter %v4f32\n"
7415                 "%entry      = OpLabel\n"
7416                 "%result     = OpVariable %fp_v4f16 Function\n"
7417                 "%param16    = OpFConvert %v4f16 %param\n"
7418                 "              OpStore %result %param16\n"
7419                 "%a_loc      = OpAccessChain %fp_f16 %result %c_i32_1\n"
7420                 "%a_init     = OpLoad %f16 %a_loc\n"
7421                 "%b_loc      = OpAccessChain %fp_f16 %result %c_i32_2\n"
7422                 "%b_init     = OpLoad %f16 %b_loc\n"
7423                 "              OpBranch %phi\n"
7424
7425                 "%phi        = OpLabel\n"
7426                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7427                 "%a_next     = OpPhi %f16  %a_init %entry %b_next %phi\n"
7428                 "%b_next     = OpPhi %f16  %b_init %entry %a_next %phi\n"
7429                 "              OpLoopMerge %exit %phi None\n"
7430                 "              OpBranchConditional %still_loop %phi %exit\n"
7431
7432                 "%exit       = OpLabel\n"
7433                 "              OpStore %a_loc %a_next\n"
7434                 "              OpStore %b_loc %b_next\n"
7435                 "%ret16      = OpLoad %v4f16 %result\n"
7436                 "%ret        = OpFConvert %v4f32 %ret16\n"
7437                 "              OpReturnValue %ret\n"
7438
7439                 "              OpFunctionEnd\n";
7440
7441         fragments4["pre_main"]          = typesAndConstants4;
7442         fragments4["testfun"]           = function4;
7443         fragments4["capability"]        = "OpCapability StorageUniformBufferBlock16\n";
7444         fragments4["extension"]         = "OpExtension \"SPV_KHR_16bit_storage\"";
7445
7446         extensions4.push_back("VK_KHR_16bit_storage");
7447         extensions4.push_back("VK_KHR_shader_float16_int8");
7448
7449         vulkanFeatures4.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
7450         vulkanFeatures4.extFloat16Int8  = EXTFLOAT16INT8FEATURES_FLOAT16;
7451
7452         outputColors4[0]                        = RGBA(127, 127, 127, 255);
7453         outputColors4[1]                        = RGBA(127, 0,   0,   255);
7454         outputColors4[2]                        = RGBA(0,   0,   127, 255);
7455         outputColors4[3]                        = RGBA(0,   127, 0,   255);
7456
7457         createTestsForAllStages("swap16", inputColors, outputColors4, fragments4, resources4, extensions4, group.get(), vulkanFeatures4);
7458
7459         return group.release();
7460 }
7461
7462 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
7463 {
7464         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
7465         RGBA                                                    inputColors[4];
7466         RGBA                                                    outputColors[4];
7467
7468         // With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
7469         // For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
7470         // only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
7471         // On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
7472         const char                                              constantsAndTypes[]      =
7473                 "%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
7474                 "%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
7475                 "%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
7476                 "%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
7477                 "%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n";
7478
7479         const char                                              function[]       =
7480                 "%test_code      = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7481                 "%param          = OpFunctionParameter %v4f32\n"
7482                 "%label          = OpLabel\n"
7483                 "%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
7484                 "%var2           = OpVariable %fp_f32 Function\n"
7485                 "%red            = OpCompositeExtract %f32 %param 0\n"
7486                 "%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
7487                 "                  OpStore %var2 %plus_red\n"
7488                 "%val1           = OpLoad %f32 %var1\n"
7489                 "%val2           = OpLoad %f32 %var2\n"
7490                 "%mul            = OpFMul %f32 %val1 %val2\n"
7491                 "%add            = OpFAdd %f32 %mul %c_f32_n1\n"
7492                 "%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
7493                 "%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
7494                 "%success        = OpLogicalOr %bool %is0 %isn1n24\n"
7495                 "%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
7496                 "%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
7497                 "                  OpReturnValue %ret\n"
7498                 "                  OpFunctionEnd\n";
7499
7500         struct CaseNameDecoration
7501         {
7502                 string name;
7503                 string decoration;
7504         };
7505
7506
7507         CaseNameDecoration tests[] = {
7508                 {"multiplication",      "OpDecorate %mul NoContraction"},
7509                 {"addition",            "OpDecorate %add NoContraction"},
7510                 {"both",                        "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
7511         };
7512
7513         getHalfColorsFullAlpha(inputColors);
7514
7515         for (deUint8 idx = 0; idx < 4; ++idx)
7516         {
7517                 inputColors[idx].setRed(0);
7518                 outputColors[idx] = RGBA(0, 0, 0, 255);
7519         }
7520
7521         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
7522         {
7523                 map<string, string> fragments;
7524
7525                 fragments["decoration"] = tests[testNdx].decoration;
7526                 fragments["pre_main"] = constantsAndTypes;
7527                 fragments["testfun"] = function;
7528
7529                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
7530         }
7531
7532         return group.release();
7533 }
7534
7535 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
7536 {
7537         de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
7538         RGBA                                                    colors[4];
7539
7540         const char                                              constantsAndTypes[]      =
7541                 "%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
7542                 "%fp_a2f32          = OpTypePointer Function %a2f32\n"
7543                 "%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
7544                 "%fp_stype          = OpTypePointer Function %stype\n";
7545
7546         const char                                              function[]       =
7547                 "%test_code         = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7548                 "%param1            = OpFunctionParameter %v4f32\n"
7549                 "%lbl               = OpLabel\n"
7550                 "%v1                = OpVariable %fp_v4f32 Function\n"
7551                 "%v2                = OpVariable %fp_a2f32 Function\n"
7552                 "%v3                = OpVariable %fp_f32 Function\n"
7553                 "%v                 = OpVariable %fp_stype Function\n"
7554                 "%vv                = OpVariable %fp_stype Function\n"
7555                 "%vvv               = OpVariable %fp_f32 Function\n"
7556
7557                 "                     OpStore %v1 %c_v4f32_1_1_1_1\n"
7558                 "                     OpStore %v2 %c_a2f32_1\n"
7559                 "                     OpStore %v3 %c_f32_1\n"
7560
7561                 "%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
7562                 "%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
7563                 "%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
7564                 "%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
7565                 "%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
7566                 "%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
7567
7568                 "                    OpStore %p_v4f32 %v1_v ${access_type}\n"
7569                 "                    OpStore %p_a2f32 %v2_v ${access_type}\n"
7570                 "                    OpStore %p_f32 %v3_v ${access_type}\n"
7571
7572                 "                    OpCopyMemory %vv %v ${access_type}\n"
7573                 "                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
7574
7575                 "%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
7576                 "%v_f32_2          = OpLoad %f32 %p_f32_2\n"
7577                 "%v_f32_3          = OpLoad %f32 %vvv\n"
7578
7579                 "%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
7580                 "%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
7581                 "                    OpReturnValue %ret2\n"
7582                 "                    OpFunctionEnd\n";
7583
7584         struct NameMemoryAccess
7585         {
7586                 string name;
7587                 string accessType;
7588         };
7589
7590
7591         NameMemoryAccess tests[] =
7592         {
7593                 { "none", "" },
7594                 { "volatile", "Volatile" },
7595                 { "aligned",  "Aligned 1" },
7596                 { "volatile_aligned",  "Volatile|Aligned 1" },
7597                 { "nontemporal_aligned",  "Nontemporal|Aligned 1" },
7598                 { "volatile_nontemporal",  "Volatile|Nontemporal" },
7599                 { "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
7600         };
7601
7602         getHalfColorsFullAlpha(colors);
7603
7604         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
7605         {
7606                 map<string, string> fragments;
7607                 map<string, string> memoryAccess;
7608                 memoryAccess["access_type"] = tests[testNdx].accessType;
7609
7610                 fragments["pre_main"] = constantsAndTypes;
7611                 fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
7612                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
7613         }
7614         return memoryAccessTests.release();
7615 }
7616 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
7617 {
7618         de::MovePtr<tcu::TestCaseGroup>         opUndefTests             (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
7619         RGBA                                                            defaultColors[4];
7620         map<string, string>                                     fragments;
7621         getDefaultColors(defaultColors);
7622
7623         // First, simple cases that don't do anything with the OpUndef result.
7624         struct NameCodePair { string name, decl, type; };
7625         const NameCodePair tests[] =
7626         {
7627                 {"bool", "", "%bool"},
7628                 {"vec2uint32", "", "%v2u32"},
7629                 {"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown", "%type"},
7630                 {"sampler", "%type = OpTypeSampler", "%type"},
7631                 {"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img", "%type"},
7632                 {"pointer", "", "%fp_i32"},
7633                 {"runtimearray", "%type = OpTypeRuntimeArray %f32", "%type"},
7634                 {"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100", "%type"},
7635                 {"struct", "%type = OpTypeStruct %f32 %i32 %u32", "%type"}};
7636         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
7637         {
7638                 fragments["undef_type"] = tests[testNdx].type;
7639                 fragments["testfun"] = StringTemplate(
7640                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7641                         "%param1 = OpFunctionParameter %v4f32\n"
7642                         "%label_testfun = OpLabel\n"
7643                         "%undef = OpUndef ${undef_type}\n"
7644                         "OpReturnValue %param1\n"
7645                         "OpFunctionEnd\n").specialize(fragments);
7646                 fragments["pre_main"] = tests[testNdx].decl;
7647                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
7648         }
7649         fragments.clear();
7650
7651         fragments["testfun"] =
7652                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7653                 "%param1 = OpFunctionParameter %v4f32\n"
7654                 "%label_testfun = OpLabel\n"
7655                 "%undef = OpUndef %f32\n"
7656                 "%zero = OpFMul %f32 %undef %c_f32_0\n"
7657                 "%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
7658                 "%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
7659                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7660                 "%b = OpFAdd %f32 %a %actually_zero\n"
7661                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
7662                 "OpReturnValue %ret\n"
7663                 "OpFunctionEnd\n";
7664
7665         createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7666
7667         fragments["testfun"] =
7668                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7669                 "%param1 = OpFunctionParameter %v4f32\n"
7670                 "%label_testfun = OpLabel\n"
7671                 "%undef = OpUndef %i32\n"
7672                 "%zero = OpIMul %i32 %undef %c_i32_0\n"
7673                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7674                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7675                 "OpReturnValue %ret\n"
7676                 "OpFunctionEnd\n";
7677
7678         createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7679
7680         fragments["testfun"] =
7681                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7682                 "%param1 = OpFunctionParameter %v4f32\n"
7683                 "%label_testfun = OpLabel\n"
7684                 "%undef = OpUndef %u32\n"
7685                 "%zero = OpIMul %u32 %undef %c_i32_0\n"
7686                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7687                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7688                 "OpReturnValue %ret\n"
7689                 "OpFunctionEnd\n";
7690
7691         createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7692
7693         fragments["testfun"] =
7694                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7695                 "%param1 = OpFunctionParameter %v4f32\n"
7696                 "%label_testfun = OpLabel\n"
7697                 "%undef = OpUndef %v4f32\n"
7698                 "%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
7699                 "%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
7700                 "%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
7701                 "%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
7702                 "%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
7703                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7704                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7705                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7706                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7707                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7708                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7709                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7710                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7711                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7712                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7713                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7714                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7715                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7716                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7717                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7718                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7719                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7720                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7721                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7722                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7723                 "OpReturnValue %ret\n"
7724                 "OpFunctionEnd\n";
7725
7726         createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7727
7728         fragments["pre_main"] =
7729                 "%m2x2f32 = OpTypeMatrix %v2f32 2\n";
7730         fragments["testfun"] =
7731                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7732                 "%param1 = OpFunctionParameter %v4f32\n"
7733                 "%label_testfun = OpLabel\n"
7734                 "%undef = OpUndef %m2x2f32\n"
7735                 "%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
7736                 "%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
7737                 "%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
7738                 "%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
7739                 "%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
7740                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7741                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7742                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7743                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7744                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7745                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7746                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7747                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7748                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7749                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7750                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7751                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7752                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7753                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7754                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7755                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7756                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7757                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7758                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7759                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7760                 "OpReturnValue %ret\n"
7761                 "OpFunctionEnd\n";
7762
7763         createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
7764
7765         return opUndefTests.release();
7766 }
7767
7768 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
7769 {
7770         const RGBA              inputColors[4]          =
7771         {
7772                 RGBA(0,         0,              0,              255),
7773                 RGBA(0,         0,              255,    255),
7774                 RGBA(0,         255,    0,              255),
7775                 RGBA(0,         255,    255,    255)
7776         };
7777
7778         const RGBA              expectedColors[4]       =
7779         {
7780                 RGBA(255,        0,              0,              255),
7781                 RGBA(255,        0,              0,              255),
7782                 RGBA(255,        0,              0,              255),
7783                 RGBA(255,        0,              0,              255)
7784         };
7785
7786         const struct SingleFP16Possibility
7787         {
7788                 const char* name;
7789                 const char* constant;  // Value to assign to %test_constant.
7790                 float           valueAsFloat;
7791                 const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
7792         }                               tests[]                         =
7793         {
7794                 {
7795                         "negative",
7796                         "-0x1.3p1\n",
7797                         -constructNormalizedFloat(1, 0x300000),
7798                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7799                 }, // -19
7800                 {
7801                         "positive",
7802                         "0x1.0p7\n",
7803                         constructNormalizedFloat(7, 0x000000),
7804                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7805                 },  // +128
7806                 // SPIR-V requires that OpQuantizeToF16 flushes
7807                 // any numbers that would end up denormalized in F16 to zero.
7808                 {
7809                         "denorm",
7810                         "0x0.0006p-126\n",
7811                         std::ldexp(1.5f, -140),
7812                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7813                 },  // denorm
7814                 {
7815                         "negative_denorm",
7816                         "-0x0.0006p-126\n",
7817                         -std::ldexp(1.5f, -140),
7818                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7819                 }, // -denorm
7820                 {
7821                         "too_small",
7822                         "0x1.0p-16\n",
7823                         std::ldexp(1.0f, -16),
7824                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7825                 },     // too small positive
7826                 {
7827                         "negative_too_small",
7828                         "-0x1.0p-32\n",
7829                         -std::ldexp(1.0f, -32),
7830                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7831                 },      // too small negative
7832                 {
7833                         "negative_inf",
7834                         "-0x1.0p128\n",
7835                         -std::ldexp(1.0f, 128),
7836
7837                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7838                         "%inf = OpIsInf %bool %c\n"
7839                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7840                 },     // -inf to -inf
7841                 {
7842                         "inf",
7843                         "0x1.0p128\n",
7844                         std::ldexp(1.0f, 128),
7845
7846                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7847                         "%inf = OpIsInf %bool %c\n"
7848                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7849                 },     // +inf to +inf
7850                 {
7851                         "round_to_negative_inf",
7852                         "-0x1.0p32\n",
7853                         -std::ldexp(1.0f, 32),
7854
7855                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7856                         "%inf = OpIsInf %bool %c\n"
7857                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7858                 },     // round to -inf
7859                 {
7860                         "round_to_inf",
7861                         "0x1.0p16\n",
7862                         std::ldexp(1.0f, 16),
7863
7864                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7865                         "%inf = OpIsInf %bool %c\n"
7866                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7867                 },     // round to +inf
7868                 {
7869                         "nan",
7870                         "0x1.1p128\n",
7871                         std::numeric_limits<float>::quiet_NaN(),
7872
7873                         // Test for any NaN value, as NaNs are not preserved
7874                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7875                         "%cond = OpIsNan %bool %direct_quant\n"
7876                 }, // nan
7877                 {
7878                         "negative_nan",
7879                         "-0x1.0001p128\n",
7880                         std::numeric_limits<float>::quiet_NaN(),
7881
7882                         // Test for any NaN value, as NaNs are not preserved
7883                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7884                         "%cond = OpIsNan %bool %direct_quant\n"
7885                 } // -nan
7886         };
7887         const char*             constants                       =
7888                 "%test_constant = OpConstant %f32 ";  // The value will be test.constant.
7889
7890         StringTemplate  function                        (
7891                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7892                 "%param1        = OpFunctionParameter %v4f32\n"
7893                 "%label_testfun = OpLabel\n"
7894                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7895                 "%b             = OpFAdd %f32 %test_constant %a\n"
7896                 "%c             = OpQuantizeToF16 %f32 %b\n"
7897                 "${condition}\n"
7898                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7899                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7900                 "                 OpReturnValue %retval\n"
7901                 "OpFunctionEnd\n"
7902         );
7903
7904         const char*             specDecorations         = "OpDecorate %test_constant SpecId 0\n";
7905         const char*             specConstants           =
7906                         "%test_constant = OpSpecConstant %f32 0.\n"
7907                         "%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
7908
7909         StringTemplate  specConstantFunction(
7910                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7911                 "%param1        = OpFunctionParameter %v4f32\n"
7912                 "%label_testfun = OpLabel\n"
7913                 "${condition}\n"
7914                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7915                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7916                 "                 OpReturnValue %retval\n"
7917                 "OpFunctionEnd\n"
7918         );
7919
7920         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7921         {
7922                 map<string, string>                                                             codeSpecialization;
7923                 map<string, string>                                                             fragments;
7924                 codeSpecialization["condition"]                                 = tests[idx].condition;
7925                 fragments["testfun"]                                                    = function.specialize(codeSpecialization);
7926                 fragments["pre_main"]                                                   = string(constants) + tests[idx].constant + "\n";
7927                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
7928         }
7929
7930         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7931         {
7932                 map<string, string>                                                             codeSpecialization;
7933                 map<string, string>                                                             fragments;
7934                 SpecConstants                                                                   passConstants;
7935
7936                 codeSpecialization["condition"]                                 = tests[idx].condition;
7937                 fragments["testfun"]                                                    = specConstantFunction.specialize(codeSpecialization);
7938                 fragments["decoration"]                                                 = specDecorations;
7939                 fragments["pre_main"]                                                   = specConstants;
7940
7941                 passConstants.append<float>(tests[idx].valueAsFloat);
7942
7943                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
7944         }
7945 }
7946
7947 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
7948 {
7949         RGBA inputColors[4] =  {
7950                 RGBA(0,         0,              0,              255),
7951                 RGBA(0,         0,              255,    255),
7952                 RGBA(0,         255,    0,              255),
7953                 RGBA(0,         255,    255,    255)
7954         };
7955
7956         RGBA expectedColors[4] =
7957         {
7958                 RGBA(255,        0,              0,              255),
7959                 RGBA(255,        0,              0,              255),
7960                 RGBA(255,        0,              0,              255),
7961                 RGBA(255,        0,              0,              255)
7962         };
7963
7964         struct DualFP16Possibility
7965         {
7966                 const char* name;
7967                 const char* input;
7968                 float           inputAsFloat;
7969                 const char* possibleOutput1;
7970                 const char* possibleOutput2;
7971         } tests[] = {
7972                 {
7973                         "positive_round_up_or_round_down",
7974                         "0x1.3003p8",
7975                         constructNormalizedFloat(8, 0x300300),
7976                         "0x1.304p8",
7977                         "0x1.3p8"
7978                 },
7979                 {
7980                         "negative_round_up_or_round_down",
7981                         "-0x1.6008p-7",
7982                         -constructNormalizedFloat(-7, 0x600800),
7983                         "-0x1.6p-7",
7984                         "-0x1.604p-7"
7985                 },
7986                 {
7987                         "carry_bit",
7988                         "0x1.01ep2",
7989                         constructNormalizedFloat(2, 0x01e000),
7990                         "0x1.01cp2",
7991                         "0x1.02p2"
7992                 },
7993                 {
7994                         "carry_to_exponent",
7995                         "0x1.ffep1",
7996                         constructNormalizedFloat(1, 0xffe000),
7997                         "0x1.ffcp1",
7998                         "0x1.0p2"
7999                 },
8000         };
8001         StringTemplate constants (
8002                 "%input_const = OpConstant %f32 ${input}\n"
8003                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8004                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8005                 );
8006
8007         StringTemplate specConstants (
8008                 "%input_const = OpSpecConstant %f32 0.\n"
8009                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8010                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8011         );
8012
8013         const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
8014
8015         const char* function  =
8016                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8017                 "%param1        = OpFunctionParameter %v4f32\n"
8018                 "%label_testfun = OpLabel\n"
8019                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8020                 // For the purposes of this test we assume that 0.f will always get
8021                 // faithfully passed through the pipeline stages.
8022                 "%b             = OpFAdd %f32 %input_const %a\n"
8023                 "%c             = OpQuantizeToF16 %f32 %b\n"
8024                 "%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
8025                 "%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
8026                 "%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
8027                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8028                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
8029                 "                 OpReturnValue %retval\n"
8030                 "OpFunctionEnd\n";
8031
8032         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8033                 map<string, string>                                                                     fragments;
8034                 map<string, string>                                                                     constantSpecialization;
8035
8036                 constantSpecialization["input"]                                         = tests[idx].input;
8037                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8038                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8039                 fragments["testfun"]                                                            = function;
8040                 fragments["pre_main"]                                                           = constants.specialize(constantSpecialization);
8041                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
8042         }
8043
8044         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8045                 map<string, string>                                                                     fragments;
8046                 map<string, string>                                                                     constantSpecialization;
8047                 SpecConstants                                                                           passConstants;
8048
8049                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8050                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8051                 fragments["testfun"]                                                            = function;
8052                 fragments["decoration"]                                                         = specDecorations;
8053                 fragments["pre_main"]                                                           = specConstants.specialize(constantSpecialization);
8054
8055                 passConstants.append<float>(tests[idx].inputAsFloat);
8056
8057                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
8058         }
8059 }
8060
8061 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
8062 {
8063         de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
8064         createOpQuantizeSingleOptionTests(opQuantizeTests.get());
8065         createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
8066         return opQuantizeTests.release();
8067 }
8068
8069 struct ShaderPermutation
8070 {
8071         deUint8 vertexPermutation;
8072         deUint8 geometryPermutation;
8073         deUint8 tesscPermutation;
8074         deUint8 tessePermutation;
8075         deUint8 fragmentPermutation;
8076 };
8077
8078 ShaderPermutation getShaderPermutation(deUint8 inputValue)
8079 {
8080         ShaderPermutation       permutation =
8081         {
8082                 static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
8083                 static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
8084                 static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
8085                 static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
8086                 static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
8087         };
8088         return permutation;
8089 }
8090
8091 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
8092 {
8093         RGBA                                                            defaultColors[4];
8094         RGBA                                                            invertedColors[4];
8095         de::MovePtr<tcu::TestCaseGroup>         moduleTests                     (new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
8096
8097         getDefaultColors(defaultColors);
8098         getInvertedDefaultColors(invertedColors);
8099
8100         // Combined module tests
8101         {
8102                 // Shader stages: vertex and fragment
8103                 {
8104                         const ShaderElement combinedPipeline[]  =
8105                         {
8106                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8107                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8108                         };
8109
8110                         addFunctionCaseWithPrograms<InstanceContext>(
8111                                 moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline,
8112                                 createInstanceContext(combinedPipeline, map<string, string>()));
8113                 }
8114
8115                 // Shader stages: vertex, geometry and fragment
8116                 {
8117                         const ShaderElement combinedPipeline[]  =
8118                         {
8119                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8120                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8121                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8122                         };
8123
8124                         addFunctionCaseWithPrograms<InstanceContext>(
8125                                 moduleTests.get(), "same_module_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8126                                 createInstanceContext(combinedPipeline, map<string, string>()));
8127                 }
8128
8129                 // Shader stages: vertex, tessellation control, tessellation evaluation and fragment
8130                 {
8131                         const ShaderElement combinedPipeline[]  =
8132                         {
8133                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8134                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8135                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8136                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8137                         };
8138
8139                         addFunctionCaseWithPrograms<InstanceContext>(
8140                                 moduleTests.get(), "same_module_tessc_tesse", "", createCombinedModule, runAndVerifyDefaultPipeline,
8141                                 createInstanceContext(combinedPipeline, map<string, string>()));
8142                 }
8143
8144                 // Shader stages: vertex, tessellation control, tessellation evaluation, geometry and fragment
8145                 {
8146                         const ShaderElement combinedPipeline[]  =
8147                         {
8148                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8149                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8150                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8151                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8152                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8153                         };
8154
8155                         addFunctionCaseWithPrograms<InstanceContext>(
8156                                 moduleTests.get(), "same_module_tessc_tesse_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8157                                 createInstanceContext(combinedPipeline, map<string, string>()));
8158                 }
8159         }
8160
8161         const char* numbers[] =
8162         {
8163                 "1", "2"
8164         };
8165
8166         for (deInt8 idx = 0; idx < 32; ++idx)
8167         {
8168                 ShaderPermutation                       permutation             = getShaderPermutation(idx);
8169                 string                                          name                    = string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
8170                 const ShaderElement                     pipeline[]              =
8171                 {
8172                         ShaderElement("vert",   string("vert") +        numbers[permutation.vertexPermutation],         VK_SHADER_STAGE_VERTEX_BIT),
8173                         ShaderElement("geom",   string("geom") +        numbers[permutation.geometryPermutation],       VK_SHADER_STAGE_GEOMETRY_BIT),
8174                         ShaderElement("tessc",  string("tessc") +       numbers[permutation.tesscPermutation],          VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8175                         ShaderElement("tesse",  string("tesse") +       numbers[permutation.tessePermutation],          VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8176                         ShaderElement("frag",   string("frag") +        numbers[permutation.fragmentPermutation],       VK_SHADER_STAGE_FRAGMENT_BIT)
8177                 };
8178
8179                 // If there are an even number of swaps, then it should be no-op.
8180                 // If there are an odd number, the color should be flipped.
8181                 if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
8182                 {
8183                         addFunctionCaseWithPrograms<InstanceContext>(
8184                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8185                                         createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
8186                 }
8187                 else
8188                 {
8189                         addFunctionCaseWithPrograms<InstanceContext>(
8190                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8191                                         createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
8192                 }
8193         }
8194         return moduleTests.release();
8195 }
8196
8197 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
8198 {
8199         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
8200         RGBA defaultColors[4];
8201         getDefaultColors(defaultColors);
8202         map<string, string> fragments;
8203         fragments["pre_main"] =
8204                 "%c_f32_5 = OpConstant %f32 5.\n";
8205
8206         // A loop with a single block. The Continue Target is the loop block
8207         // itself. In SPIR-V terms, the "loop construct" contains no blocks at all
8208         // -- the "continue construct" forms the entire loop.
8209         fragments["testfun"] =
8210                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8211                 "%param1 = OpFunctionParameter %v4f32\n"
8212
8213                 "%entry = OpLabel\n"
8214                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8215                 "OpBranch %loop\n"
8216
8217                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8218                 "%loop = OpLabel\n"
8219                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8220                 "%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
8221                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8222                 "%val = OpFAdd %f32 %val1 %delta\n"
8223                 "%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
8224                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8225                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8226                 "OpLoopMerge %exit %loop None\n"
8227                 "OpBranchConditional %again %loop %exit\n"
8228
8229                 "%exit = OpLabel\n"
8230                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8231                 "OpReturnValue %result\n"
8232
8233                 "OpFunctionEnd\n";
8234
8235         createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
8236
8237         // Body comprised of multiple basic blocks.
8238         const StringTemplate multiBlock(
8239                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8240                 "%param1 = OpFunctionParameter %v4f32\n"
8241
8242                 "%entry = OpLabel\n"
8243                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8244                 "OpBranch %loop\n"
8245
8246                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8247                 "%loop = OpLabel\n"
8248                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
8249                 "%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
8250                 "%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
8251                 // There are several possibilities for the Continue Target below.  Each
8252                 // will be specialized into a separate test case.
8253                 "OpLoopMerge %exit ${continue_target} None\n"
8254                 "OpBranch %if\n"
8255
8256                 "%if = OpLabel\n"
8257                 ";delta_next = (delta > 0) ? -1 : 1;\n"
8258                 "%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
8259                 "OpSelectionMerge %gather DontFlatten\n"
8260                 "OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
8261
8262                 "%odd = OpLabel\n"
8263                 "OpBranch %gather\n"
8264
8265                 "%even = OpLabel\n"
8266                 "OpBranch %gather\n"
8267
8268                 "%gather = OpLabel\n"
8269                 "%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
8270                 "%val = OpFAdd %f32 %val1 %delta\n"
8271                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8272                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8273                 "OpBranchConditional %again %loop %exit\n"
8274
8275                 "%exit = OpLabel\n"
8276                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8277                 "OpReturnValue %result\n"
8278
8279                 "OpFunctionEnd\n");
8280
8281         map<string, string> continue_target;
8282
8283         // The Continue Target is the loop block itself.
8284         continue_target["continue_target"] = "%loop";
8285         fragments["testfun"] = multiBlock.specialize(continue_target);
8286         createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
8287
8288         // The Continue Target is at the end of the loop.
8289         continue_target["continue_target"] = "%gather";
8290         fragments["testfun"] = multiBlock.specialize(continue_target);
8291         createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
8292
8293         // A loop with continue statement.
8294         fragments["testfun"] =
8295                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8296                 "%param1 = OpFunctionParameter %v4f32\n"
8297
8298                 "%entry = OpLabel\n"
8299                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8300                 "OpBranch %loop\n"
8301
8302                 ";adds 4, 3, and 1 to %val0 (skips 2)\n"
8303                 "%loop = OpLabel\n"
8304                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8305                 "%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
8306                 "OpLoopMerge %exit %continue None\n"
8307                 "OpBranch %if\n"
8308
8309                 "%if = OpLabel\n"
8310                 ";skip if %count==2\n"
8311                 "%eq2 = OpIEqual %bool %count %c_i32_2\n"
8312                 "OpSelectionMerge %continue DontFlatten\n"
8313                 "OpBranchConditional %eq2 %continue %body\n"
8314
8315                 "%body = OpLabel\n"
8316                 "%fcount = OpConvertSToF %f32 %count\n"
8317                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8318                 "OpBranch %continue\n"
8319
8320                 "%continue = OpLabel\n"
8321                 "%val = OpPhi %f32 %val2 %body %val1 %if\n"
8322                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8323                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8324                 "OpBranchConditional %again %loop %exit\n"
8325
8326                 "%exit = OpLabel\n"
8327                 "%same = OpFSub %f32 %val %c_f32_8\n"
8328                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8329                 "OpReturnValue %result\n"
8330                 "OpFunctionEnd\n";
8331         createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
8332
8333         // A loop with break.
8334         fragments["testfun"] =
8335                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8336                 "%param1 = OpFunctionParameter %v4f32\n"
8337
8338                 "%entry = OpLabel\n"
8339                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8340                 "%dot = OpDot %f32 %param1 %param1\n"
8341                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8342                 "%zero = OpConvertFToU %u32 %div\n"
8343                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8344                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8345                 "OpBranch %loop\n"
8346
8347                 ";adds 4 and 3 to %val0 (exits early)\n"
8348                 "%loop = OpLabel\n"
8349                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8350                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8351                 "OpLoopMerge %exit %continue None\n"
8352                 "OpBranch %if\n"
8353
8354                 "%if = OpLabel\n"
8355                 ";end loop if %count==%two\n"
8356                 "%above2 = OpSGreaterThan %bool %count %two\n"
8357                 "OpSelectionMerge %continue DontFlatten\n"
8358                 "OpBranchConditional %above2 %body %exit\n"
8359
8360                 "%body = OpLabel\n"
8361                 "%fcount = OpConvertSToF %f32 %count\n"
8362                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8363                 "OpBranch %continue\n"
8364
8365                 "%continue = OpLabel\n"
8366                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8367                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8368                 "OpBranchConditional %again %loop %exit\n"
8369
8370                 "%exit = OpLabel\n"
8371                 "%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
8372                 "%same = OpFSub %f32 %val_post %c_f32_7\n"
8373                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8374                 "OpReturnValue %result\n"
8375                 "OpFunctionEnd\n";
8376         createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
8377
8378         // A loop with return.
8379         fragments["testfun"] =
8380                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8381                 "%param1 = OpFunctionParameter %v4f32\n"
8382
8383                 "%entry = OpLabel\n"
8384                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8385                 "%dot = OpDot %f32 %param1 %param1\n"
8386                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8387                 "%zero = OpConvertFToU %u32 %div\n"
8388                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8389                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8390                 "OpBranch %loop\n"
8391
8392                 ";returns early without modifying %param1\n"
8393                 "%loop = OpLabel\n"
8394                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8395                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8396                 "OpLoopMerge %exit %continue None\n"
8397                 "OpBranch %if\n"
8398
8399                 "%if = OpLabel\n"
8400                 ";return if %count==%two\n"
8401                 "%above2 = OpSGreaterThan %bool %count %two\n"
8402                 "OpSelectionMerge %continue DontFlatten\n"
8403                 "OpBranchConditional %above2 %body %early_exit\n"
8404
8405                 "%early_exit = OpLabel\n"
8406                 "OpReturnValue %param1\n"
8407
8408                 "%body = OpLabel\n"
8409                 "%fcount = OpConvertSToF %f32 %count\n"
8410                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8411                 "OpBranch %continue\n"
8412
8413                 "%continue = OpLabel\n"
8414                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8415                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8416                 "OpBranchConditional %again %loop %exit\n"
8417
8418                 "%exit = OpLabel\n"
8419                 ";should never get here, so return an incorrect result\n"
8420                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
8421                 "OpReturnValue %result\n"
8422                 "OpFunctionEnd\n";
8423         createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
8424
8425         // Continue inside a switch block to break to enclosing loop's merge block.
8426         // Matches roughly the following GLSL code:
8427         // for (; keep_going; keep_going = false)
8428         // {
8429         //     switch (int(param1.x))
8430         //     {
8431         //         case 0: continue;
8432         //         case 1: continue;
8433         //         default: continue;
8434         //     }
8435         //     dead code: modify return value to invalid result.
8436         // }
8437         fragments["pre_main"] =
8438                 "%fp_bool = OpTypePointer Function %bool\n"
8439                 "%true = OpConstantTrue %bool\n"
8440                 "%false = OpConstantFalse %bool\n";
8441
8442         fragments["testfun"] =
8443                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8444                 "%param1 = OpFunctionParameter %v4f32\n"
8445
8446                 "%entry = OpLabel\n"
8447                 "%keep_going = OpVariable %fp_bool Function\n"
8448                 "%val_ptr = OpVariable %fp_f32 Function\n"
8449                 "%param1_x = OpCompositeExtract %f32 %param1 0\n"
8450                 "OpStore %keep_going %true\n"
8451                 "OpBranch %forloop_begin\n"
8452
8453                 "%forloop_begin = OpLabel\n"
8454                 "OpLoopMerge %forloop_merge %forloop_continue None\n"
8455                 "OpBranch %forloop\n"
8456
8457                 "%forloop = OpLabel\n"
8458                 "%for_condition = OpLoad %bool %keep_going\n"
8459                 "OpBranchConditional %for_condition %forloop_body %forloop_merge\n"
8460
8461                 "%forloop_body = OpLabel\n"
8462                 "OpStore %val_ptr %param1_x\n"
8463                 "%param1_x_int = OpConvertFToS %i32 %param1_x\n"
8464
8465                 "OpSelectionMerge %switch_merge None\n"
8466                 "OpSwitch %param1_x_int %default 0 %case_0 1 %case_1\n"
8467                 "%case_0 = OpLabel\n"
8468                 "OpBranch %forloop_continue\n"
8469                 "%case_1 = OpLabel\n"
8470                 "OpBranch %forloop_continue\n"
8471                 "%default = OpLabel\n"
8472                 "OpBranch %forloop_continue\n"
8473                 "%switch_merge = OpLabel\n"
8474                 ";should never get here, so change the return value to invalid result\n"
8475                 "OpStore %val_ptr %c_f32_1\n"
8476                 "OpBranch %forloop_continue\n"
8477
8478                 "%forloop_continue = OpLabel\n"
8479                 "OpStore %keep_going %false\n"
8480                 "OpBranch %forloop_begin\n"
8481                 "%forloop_merge = OpLabel\n"
8482
8483                 "%val = OpLoad %f32 %val_ptr\n"
8484                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8485                 "OpReturnValue %result\n"
8486                 "OpFunctionEnd\n";
8487         createTestsForAllStages("switch_continue", defaultColors, defaultColors, fragments, testGroup.get());
8488
8489         return testGroup.release();
8490 }
8491
8492 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
8493 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
8494 {
8495         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
8496         map<string, string> fragments;
8497
8498         // A barrier inside a function body.
8499         fragments["pre_main"] =
8500                 "%Workgroup = OpConstant %i32 2\n"
8501                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n";
8502         fragments["testfun"] =
8503                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8504                 "%param1 = OpFunctionParameter %v4f32\n"
8505                 "%label_testfun = OpLabel\n"
8506                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8507                 "OpReturnValue %param1\n"
8508                 "OpFunctionEnd\n";
8509         addTessCtrlTest(testGroup.get(), "in_function", fragments);
8510
8511         // Common setup code for the following tests.
8512         fragments["pre_main"] =
8513                 "%Workgroup = OpConstant %i32 2\n"
8514                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8515                 "%c_f32_5 = OpConstant %f32 5.\n";
8516         const string setupPercentZero =  // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
8517                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8518                 "%param1 = OpFunctionParameter %v4f32\n"
8519                 "%entry = OpLabel\n"
8520                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8521                 "%dot = OpDot %f32 %param1 %param1\n"
8522                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8523                 "%zero = OpConvertFToU %u32 %div\n";
8524
8525         // Barriers inside OpSwitch branches.
8526         fragments["testfun"] =
8527                 setupPercentZero +
8528                 "OpSelectionMerge %switch_exit None\n"
8529                 "OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
8530
8531                 "%case1 = OpLabel\n"
8532                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8533                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8534                 "%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8535                 "OpBranch %switch_exit\n"
8536
8537                 "%switch_default = OpLabel\n"
8538                 "%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8539                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8540                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8541                 "OpBranch %switch_exit\n"
8542
8543                 "%case0 = OpLabel\n"
8544                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8545                 "OpBranch %switch_exit\n"
8546
8547                 "%switch_exit = OpLabel\n"
8548                 "%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
8549                 "OpReturnValue %ret\n"
8550                 "OpFunctionEnd\n";
8551         addTessCtrlTest(testGroup.get(), "in_switch", fragments);
8552
8553         // Barriers inside if-then-else.
8554         fragments["testfun"] =
8555                 setupPercentZero +
8556                 "%eq0 = OpIEqual %bool %zero %c_u32_0\n"
8557                 "OpSelectionMerge %exit DontFlatten\n"
8558                 "OpBranchConditional %eq0 %then %else\n"
8559
8560                 "%else = OpLabel\n"
8561                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8562                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8563                 "%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8564                 "OpBranch %exit\n"
8565
8566                 "%then = OpLabel\n"
8567                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8568                 "OpBranch %exit\n"
8569                 "%exit = OpLabel\n"
8570                 "%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
8571                 "OpReturnValue %ret\n"
8572                 "OpFunctionEnd\n";
8573         addTessCtrlTest(testGroup.get(), "in_if", fragments);
8574
8575         // A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
8576         // http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
8577         fragments["testfun"] =
8578                 setupPercentZero +
8579                 "%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
8580                 "%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
8581                 "OpSelectionMerge %exit DontFlatten\n"
8582                 "OpBranchConditional %thread0 %then %else\n"
8583
8584                 "%else = OpLabel\n"
8585                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8586                 "OpBranch %exit\n"
8587
8588                 "%then = OpLabel\n"
8589                 "%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
8590                 "OpBranch %exit\n"
8591
8592                 "%exit = OpLabel\n"
8593                 "%val = OpPhi %f32 %val0 %else %val1 %then\n"
8594                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8595                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
8596                 "OpReturnValue %ret\n"
8597                 "OpFunctionEnd\n";
8598         addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
8599
8600         // A barrier inside a loop.
8601         fragments["pre_main"] =
8602                 "%Workgroup = OpConstant %i32 2\n"
8603                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8604                 "%c_f32_10 = OpConstant %f32 10.\n";
8605         fragments["testfun"] =
8606                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8607                 "%param1 = OpFunctionParameter %v4f32\n"
8608                 "%entry = OpLabel\n"
8609                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8610                 "OpBranch %loop\n"
8611
8612                 ";adds 4, 3, 2, and 1 to %val0\n"
8613                 "%loop = OpLabel\n"
8614                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8615                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8616                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8617                 "%fcount = OpConvertSToF %f32 %count\n"
8618                 "%val = OpFAdd %f32 %val1 %fcount\n"
8619                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8620                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8621                 "OpLoopMerge %exit %loop None\n"
8622                 "OpBranchConditional %again %loop %exit\n"
8623
8624                 "%exit = OpLabel\n"
8625                 "%same = OpFSub %f32 %val %c_f32_10\n"
8626                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8627                 "OpReturnValue %ret\n"
8628                 "OpFunctionEnd\n";
8629         addTessCtrlTest(testGroup.get(), "in_loop", fragments);
8630
8631         return testGroup.release();
8632 }
8633
8634 // Test for the OpFRem instruction.
8635 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
8636 {
8637         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
8638         map<string, string>                                     fragments;
8639         RGBA                                                            inputColors[4];
8640         RGBA                                                            outputColors[4];
8641
8642         fragments["pre_main"]                            =
8643                 "%c_f32_3 = OpConstant %f32 3.0\n"
8644                 "%c_f32_n3 = OpConstant %f32 -3.0\n"
8645                 "%c_f32_4 = OpConstant %f32 4.0\n"
8646                 "%c_f32_p75 = OpConstant %f32 0.75\n"
8647                 "%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
8648                 "%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
8649                 "%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
8650
8651         // The test does the following.
8652         // vec4 result = (param1 * 8.0) - 4.0;
8653         // return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
8654         fragments["testfun"]                             =
8655                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8656                 "%param1 = OpFunctionParameter %v4f32\n"
8657                 "%label_testfun = OpLabel\n"
8658                 "%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
8659                 "%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
8660                 "%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
8661                 "%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
8662                 "%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
8663                 "%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
8664                 "OpReturnValue %xy_0_1\n"
8665                 "OpFunctionEnd\n";
8666
8667
8668         inputColors[0]          = RGBA(16,      16,             0, 255);
8669         inputColors[1]          = RGBA(232, 232,        0, 255);
8670         inputColors[2]          = RGBA(232, 16,         0, 255);
8671         inputColors[3]          = RGBA(16,      232,    0, 255);
8672
8673         outputColors[0]         = RGBA(64,      64,             0, 255);
8674         outputColors[1]         = RGBA(255, 255,        0, 255);
8675         outputColors[2]         = RGBA(255, 64,         0, 255);
8676         outputColors[3]         = RGBA(64,      255,    0, 255);
8677
8678         createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
8679         return testGroup.release();
8680 }
8681
8682 // Test for the OpSRem instruction.
8683 tcu::TestCaseGroup* createOpSRemGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8684 {
8685         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "srem", "OpSRem"));
8686         map<string, string>                                     fragments;
8687
8688         fragments["pre_main"]                            =
8689                 "%c_f32_255 = OpConstant %f32 255.0\n"
8690                 "%c_i32_128 = OpConstant %i32 128\n"
8691                 "%c_i32_255 = OpConstant %i32 255\n"
8692                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8693                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8694                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8695
8696         // The test does the following.
8697         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8698         // ivec4 result = ivec4(srem(ints.x, ints.y), srem(ints.y, ints.z), srem(ints.z, ints.x), 255);
8699         // return float(result + 128) / 255.0;
8700         fragments["testfun"]                             =
8701                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8702                 "%param1 = OpFunctionParameter %v4f32\n"
8703                 "%label_testfun = OpLabel\n"
8704                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8705                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8706                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8707                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8708                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8709                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8710                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8711                 "%x_out = OpSRem %i32 %x_in %y_in\n"
8712                 "%y_out = OpSRem %i32 %y_in %z_in\n"
8713                 "%z_out = OpSRem %i32 %z_in %x_in\n"
8714                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8715                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8716                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8717                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8718                 "OpReturnValue %float_out\n"
8719                 "OpFunctionEnd\n";
8720
8721         const struct CaseParams
8722         {
8723                 const char*             name;
8724                 const char*             failMessageTemplate;    // customized status message
8725                 qpTestResult    failResult;                             // override status on failure
8726                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8727                 int                             results[4][3];                  // four (x, y, z) vectors of results
8728         } cases[] =
8729         {
8730                 {
8731                         "positive",
8732                         "${reason}",
8733                         QP_TEST_RESULT_FAIL,
8734                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                 // operands
8735                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                 // results
8736                 },
8737                 {
8738                         "all",
8739                         "Inconsistent results, but within specification: ${reason}",
8740                         negFailResult,                                                                                                                  // negative operands, not required by the spec
8741                         { { 5, 12, -17 }, { -5, -5, 7 }, { 75, 8, -81 }, { 25, -60, 100 } },    // operands
8742                         { { 5, 12,  -2 }, {  0, -5, 2 }, {  3, 8,  -6 }, { 25, -60,   0 } },    // results
8743                 },
8744         };
8745         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8746
8747         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8748         {
8749                 const CaseParams&       params                  = cases[caseNdx];
8750                 RGBA                            inputColors[4];
8751                 RGBA                            outputColors[4];
8752
8753                 for (int i = 0; i < 4; ++i)
8754                 {
8755                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8756                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8757                 }
8758
8759                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8760         }
8761
8762         return testGroup.release();
8763 }
8764
8765 // Test for the OpSMod instruction.
8766 tcu::TestCaseGroup* createOpSModGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8767 {
8768         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "smod", "OpSMod"));
8769         map<string, string>                                     fragments;
8770
8771         fragments["pre_main"]                            =
8772                 "%c_f32_255 = OpConstant %f32 255.0\n"
8773                 "%c_i32_128 = OpConstant %i32 128\n"
8774                 "%c_i32_255 = OpConstant %i32 255\n"
8775                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8776                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8777                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8778
8779         // The test does the following.
8780         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8781         // ivec4 result = ivec4(smod(ints.x, ints.y), smod(ints.y, ints.z), smod(ints.z, ints.x), 255);
8782         // return float(result + 128) / 255.0;
8783         fragments["testfun"]                             =
8784                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8785                 "%param1 = OpFunctionParameter %v4f32\n"
8786                 "%label_testfun = OpLabel\n"
8787                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8788                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8789                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8790                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8791                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8792                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8793                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8794                 "%x_out = OpSMod %i32 %x_in %y_in\n"
8795                 "%y_out = OpSMod %i32 %y_in %z_in\n"
8796                 "%z_out = OpSMod %i32 %z_in %x_in\n"
8797                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8798                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8799                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8800                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8801                 "OpReturnValue %float_out\n"
8802                 "OpFunctionEnd\n";
8803
8804         const struct CaseParams
8805         {
8806                 const char*             name;
8807                 const char*             failMessageTemplate;    // customized status message
8808                 qpTestResult    failResult;                             // override status on failure
8809                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8810                 int                             results[4][3];                  // four (x, y, z) vectors of results
8811         } cases[] =
8812         {
8813                 {
8814                         "positive",
8815                         "${reason}",
8816                         QP_TEST_RESULT_FAIL,
8817                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                         // operands
8818                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                         // results
8819                 },
8820                 {
8821                         "all",
8822                         "Inconsistent results, but within specification: ${reason}",
8823                         negFailResult,                                                                                                                          // negative operands, not required by the spec
8824                         { { 5, 12, -17 }, { -5, -5,  7 }, { 75,   8, -81 }, {  25, -60, 100 } },        // operands
8825                         { { 5, -5,   3 }, {  0,  2, -3 }, {  3, -73,  69 }, { -35,  40,   0 } },        // results
8826                 },
8827         };
8828         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8829
8830         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8831         {
8832                 const CaseParams&       params                  = cases[caseNdx];
8833                 RGBA                            inputColors[4];
8834                 RGBA                            outputColors[4];
8835
8836                 for (int i = 0; i < 4; ++i)
8837                 {
8838                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8839                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8840                 }
8841
8842                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8843         }
8844         return testGroup.release();
8845 }
8846
8847 enum ConversionDataType
8848 {
8849         DATA_TYPE_SIGNED_8,
8850         DATA_TYPE_SIGNED_16,
8851         DATA_TYPE_SIGNED_32,
8852         DATA_TYPE_SIGNED_64,
8853         DATA_TYPE_UNSIGNED_8,
8854         DATA_TYPE_UNSIGNED_16,
8855         DATA_TYPE_UNSIGNED_32,
8856         DATA_TYPE_UNSIGNED_64,
8857         DATA_TYPE_FLOAT_16,
8858         DATA_TYPE_FLOAT_32,
8859         DATA_TYPE_FLOAT_64,
8860         DATA_TYPE_VEC2_SIGNED_16,
8861         DATA_TYPE_VEC2_SIGNED_32
8862 };
8863
8864 const string getBitWidthStr (ConversionDataType type)
8865 {
8866         switch (type)
8867         {
8868                 case DATA_TYPE_SIGNED_8:
8869                 case DATA_TYPE_UNSIGNED_8:
8870                         return "8";
8871
8872                 case DATA_TYPE_SIGNED_16:
8873                 case DATA_TYPE_UNSIGNED_16:
8874                 case DATA_TYPE_FLOAT_16:
8875                         return "16";
8876
8877                 case DATA_TYPE_SIGNED_32:
8878                 case DATA_TYPE_UNSIGNED_32:
8879                 case DATA_TYPE_FLOAT_32:
8880                 case DATA_TYPE_VEC2_SIGNED_16:
8881                         return "32";
8882
8883                 case DATA_TYPE_SIGNED_64:
8884                 case DATA_TYPE_UNSIGNED_64:
8885                 case DATA_TYPE_FLOAT_64:
8886                 case DATA_TYPE_VEC2_SIGNED_32:
8887                         return "64";
8888
8889                 default:
8890                         DE_ASSERT(false);
8891         }
8892         return "";
8893 }
8894
8895 const string getByteWidthStr (ConversionDataType type)
8896 {
8897         switch (type)
8898         {
8899                 case DATA_TYPE_SIGNED_8:
8900                 case DATA_TYPE_UNSIGNED_8:
8901                         return "1";
8902
8903                 case DATA_TYPE_SIGNED_16:
8904                 case DATA_TYPE_UNSIGNED_16:
8905                 case DATA_TYPE_FLOAT_16:
8906                         return "2";
8907
8908                 case DATA_TYPE_SIGNED_32:
8909                 case DATA_TYPE_UNSIGNED_32:
8910                 case DATA_TYPE_FLOAT_32:
8911                 case DATA_TYPE_VEC2_SIGNED_16:
8912                         return "4";
8913
8914                 case DATA_TYPE_SIGNED_64:
8915                 case DATA_TYPE_UNSIGNED_64:
8916                 case DATA_TYPE_FLOAT_64:
8917                 case DATA_TYPE_VEC2_SIGNED_32:
8918                         return "8";
8919
8920                 default:
8921                         DE_ASSERT(false);
8922         }
8923         return "";
8924 }
8925
8926 bool isSigned (ConversionDataType type)
8927 {
8928         switch (type)
8929         {
8930                 case DATA_TYPE_SIGNED_8:
8931                 case DATA_TYPE_SIGNED_16:
8932                 case DATA_TYPE_SIGNED_32:
8933                 case DATA_TYPE_SIGNED_64:
8934                 case DATA_TYPE_FLOAT_16:
8935                 case DATA_TYPE_FLOAT_32:
8936                 case DATA_TYPE_FLOAT_64:
8937                 case DATA_TYPE_VEC2_SIGNED_16:
8938                 case DATA_TYPE_VEC2_SIGNED_32:
8939                         return true;
8940
8941                 case DATA_TYPE_UNSIGNED_8:
8942                 case DATA_TYPE_UNSIGNED_16:
8943                 case DATA_TYPE_UNSIGNED_32:
8944                 case DATA_TYPE_UNSIGNED_64:
8945                         return false;
8946
8947                 default:
8948                         DE_ASSERT(false);
8949         }
8950         return false;
8951 }
8952
8953 bool isInt (ConversionDataType type)
8954 {
8955         switch (type)
8956         {
8957                 case DATA_TYPE_SIGNED_8:
8958                 case DATA_TYPE_SIGNED_16:
8959                 case DATA_TYPE_SIGNED_32:
8960                 case DATA_TYPE_SIGNED_64:
8961                 case DATA_TYPE_UNSIGNED_8:
8962                 case DATA_TYPE_UNSIGNED_16:
8963                 case DATA_TYPE_UNSIGNED_32:
8964                 case DATA_TYPE_UNSIGNED_64:
8965                         return true;
8966
8967                 case DATA_TYPE_FLOAT_16:
8968                 case DATA_TYPE_FLOAT_32:
8969                 case DATA_TYPE_FLOAT_64:
8970                 case DATA_TYPE_VEC2_SIGNED_16:
8971                 case DATA_TYPE_VEC2_SIGNED_32:
8972                         return false;
8973
8974                 default:
8975                         DE_ASSERT(false);
8976         }
8977         return false;
8978 }
8979
8980 bool isFloat (ConversionDataType type)
8981 {
8982         switch (type)
8983         {
8984                 case DATA_TYPE_SIGNED_8:
8985                 case DATA_TYPE_SIGNED_16:
8986                 case DATA_TYPE_SIGNED_32:
8987                 case DATA_TYPE_SIGNED_64:
8988                 case DATA_TYPE_UNSIGNED_8:
8989                 case DATA_TYPE_UNSIGNED_16:
8990                 case DATA_TYPE_UNSIGNED_32:
8991                 case DATA_TYPE_UNSIGNED_64:
8992                 case DATA_TYPE_VEC2_SIGNED_16:
8993                 case DATA_TYPE_VEC2_SIGNED_32:
8994                         return false;
8995
8996                 case DATA_TYPE_FLOAT_16:
8997                 case DATA_TYPE_FLOAT_32:
8998                 case DATA_TYPE_FLOAT_64:
8999                         return true;
9000
9001                 default:
9002                         DE_ASSERT(false);
9003         }
9004         return false;
9005 }
9006
9007 const string getTypeName (ConversionDataType type)
9008 {
9009         string prefix = isSigned(type) ? "" : "u";
9010
9011         if              (isInt(type))                                           return prefix + "int"   + getBitWidthStr(type);
9012         else if (isFloat(type))                                         return prefix + "float" + getBitWidthStr(type);
9013         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9014         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "i32vec2";
9015         else                                                                            DE_ASSERT(false);
9016
9017         return "";
9018 }
9019
9020 const string getTestName (ConversionDataType from, ConversionDataType to, const char* suffix)
9021 {
9022         const string fullSuffix(suffix == DE_NULL ? "" : string("_") + string(suffix));
9023
9024         return getTypeName(from) + "_to_" + getTypeName(to) + fullSuffix;
9025 }
9026
9027 const string getAsmTypeName (ConversionDataType type)
9028 {
9029         string prefix;
9030
9031         if              (isInt(type))                                           prefix = isSigned(type) ? "i" : "u";
9032         else if (isFloat(type))                                         prefix = "f";
9033         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9034         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "v2i32";
9035         else                                                                            DE_ASSERT(false);
9036
9037         return prefix + getBitWidthStr(type);
9038 }
9039
9040 template<typename T>
9041 BufferSp getSpecializedBuffer (deInt64 number)
9042 {
9043         return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
9044 }
9045
9046 BufferSp getBuffer (ConversionDataType type, deInt64 number)
9047 {
9048         switch (type)
9049         {
9050                 case DATA_TYPE_SIGNED_8:                return getSpecializedBuffer<deInt8>(number);
9051                 case DATA_TYPE_SIGNED_16:               return getSpecializedBuffer<deInt16>(number);
9052                 case DATA_TYPE_SIGNED_32:               return getSpecializedBuffer<deInt32>(number);
9053                 case DATA_TYPE_SIGNED_64:               return getSpecializedBuffer<deInt64>(number);
9054                 case DATA_TYPE_UNSIGNED_8:              return getSpecializedBuffer<deUint8>(number);
9055                 case DATA_TYPE_UNSIGNED_16:             return getSpecializedBuffer<deUint16>(number);
9056                 case DATA_TYPE_UNSIGNED_32:             return getSpecializedBuffer<deUint32>(number);
9057                 case DATA_TYPE_UNSIGNED_64:             return getSpecializedBuffer<deUint64>(number);
9058                 case DATA_TYPE_FLOAT_16:                return getSpecializedBuffer<deUint16>(number);
9059                 case DATA_TYPE_FLOAT_32:                return getSpecializedBuffer<deUint32>(number);
9060                 case DATA_TYPE_FLOAT_64:                return getSpecializedBuffer<deUint64>(number);
9061                 case DATA_TYPE_VEC2_SIGNED_16:  return getSpecializedBuffer<deUint32>(number);
9062                 case DATA_TYPE_VEC2_SIGNED_32:  return getSpecializedBuffer<deUint64>(number);
9063
9064                 default:                                                TCU_THROW(InternalError, "Unimplemented type passed");
9065         }
9066 }
9067
9068 bool usesInt8 (ConversionDataType from, ConversionDataType to)
9069 {
9070         return (from == DATA_TYPE_SIGNED_8 || to == DATA_TYPE_SIGNED_8 ||
9071                         from == DATA_TYPE_UNSIGNED_8 || to == DATA_TYPE_UNSIGNED_8);
9072 }
9073
9074 bool usesInt16 (ConversionDataType from, ConversionDataType to)
9075 {
9076         return (from == DATA_TYPE_SIGNED_16 || to == DATA_TYPE_SIGNED_16 ||
9077                         from == DATA_TYPE_UNSIGNED_16 || to == DATA_TYPE_UNSIGNED_16 ||
9078                         from == DATA_TYPE_VEC2_SIGNED_16 || to == DATA_TYPE_VEC2_SIGNED_16);
9079 }
9080
9081 bool usesInt32 (ConversionDataType from, ConversionDataType to)
9082 {
9083         return (from == DATA_TYPE_SIGNED_32 || to == DATA_TYPE_SIGNED_32 ||
9084                         from == DATA_TYPE_UNSIGNED_32 || to == DATA_TYPE_UNSIGNED_32 ||
9085                         from == DATA_TYPE_VEC2_SIGNED_32|| to == DATA_TYPE_VEC2_SIGNED_32);
9086 }
9087
9088 bool usesInt64 (ConversionDataType from, ConversionDataType to)
9089 {
9090         return (from == DATA_TYPE_SIGNED_64 || to == DATA_TYPE_SIGNED_64 ||
9091                         from == DATA_TYPE_UNSIGNED_64 || to == DATA_TYPE_UNSIGNED_64);
9092 }
9093
9094 bool usesFloat16 (ConversionDataType from, ConversionDataType to)
9095 {
9096         return (from == DATA_TYPE_FLOAT_16 || to == DATA_TYPE_FLOAT_16);
9097 }
9098
9099 bool usesFloat32 (ConversionDataType from, ConversionDataType to)
9100 {
9101         return (from == DATA_TYPE_FLOAT_32 || to == DATA_TYPE_FLOAT_32);
9102 }
9103
9104 bool usesFloat64 (ConversionDataType from, ConversionDataType to)
9105 {
9106         return (from == DATA_TYPE_FLOAT_64 || to == DATA_TYPE_FLOAT_64);
9107 }
9108
9109 void getVulkanFeaturesAndExtensions (ConversionDataType from, ConversionDataType to, VulkanFeatures& vulkanFeatures, vector<string>& extensions)
9110 {
9111         if (usesInt16(from, to) && !usesInt32(from, to))
9112                 vulkanFeatures.coreFeatures.shaderInt16 = DE_TRUE;
9113
9114         if (usesInt64(from, to))
9115                 vulkanFeatures.coreFeatures.shaderInt64 = DE_TRUE;
9116
9117         if (usesFloat64(from, to))
9118                 vulkanFeatures.coreFeatures.shaderFloat64 = DE_TRUE;
9119
9120         if (usesInt16(from, to) || usesFloat16(from, to))
9121         {
9122                 extensions.push_back("VK_KHR_16bit_storage");
9123                 vulkanFeatures.ext16BitStorage |= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
9124         }
9125
9126         if (usesFloat16(from, to) || usesInt8(from, to))
9127         {
9128                 extensions.push_back("VK_KHR_shader_float16_int8");
9129
9130                 if (usesFloat16(from, to))
9131                 {
9132                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
9133                 }
9134
9135                 if (usesInt8(from, to))
9136                 {
9137                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
9138
9139                         extensions.push_back("VK_KHR_8bit_storage");
9140                         vulkanFeatures.ext8BitStorage |= EXT8BITSTORAGEFEATURES_STORAGE_BUFFER;
9141                 }
9142         }
9143 }
9144
9145 struct ConvertCase
9146 {
9147         ConvertCase (const string& instruction, ConversionDataType from, ConversionDataType to, deInt64 number, bool separateOutput = false, deInt64 outputNumber = 0, const char* suffix = DE_NULL)
9148         : m_fromType            (from)
9149         , m_toType                      (to)
9150         , m_name                        (getTestName(from, to, suffix))
9151         , m_inputBuffer         (getBuffer(from, number))
9152         {
9153                 string caps;
9154                 string decl;
9155                 string exts;
9156
9157                 m_asmTypes["inputType"]         = getAsmTypeName(from);
9158                 m_asmTypes["outputType"]        = getAsmTypeName(to);
9159
9160                 if (separateOutput)
9161                         m_outputBuffer = getBuffer(to, outputNumber);
9162                 else
9163                         m_outputBuffer = getBuffer(to, number);
9164
9165                 if (usesInt8(from, to))
9166                 {
9167                         bool requiresInt8Capability = true;
9168                         if (instruction == "OpUConvert" || instruction == "OpSConvert")
9169                         {
9170                                 // Conversions between 8 and 32 bit are provided by SPV_KHR_8bit_storage. The rest requires explicit Int8
9171                                 if (usesInt32(from, to))
9172                                         requiresInt8Capability = false;
9173                         }
9174
9175                         caps += "OpCapability StorageBuffer8BitAccess\n";
9176                         if (requiresInt8Capability)
9177                                 caps += "OpCapability Int8\n";
9178
9179                         decl += "%i8         = OpTypeInt 8 1\n"
9180                                         "%u8         = OpTypeInt 8 0\n";
9181                         exts += "OpExtension \"SPV_KHR_8bit_storage\"\n";
9182                 }
9183
9184                 if (usesInt16(from, to))
9185                 {
9186                         bool requiresInt16Capability = true;
9187
9188                         if (instruction == "OpUConvert" || instruction == "OpSConvert" || instruction == "OpFConvert")
9189                         {
9190                                 // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9191                                 if (usesInt32(from, to) || usesFloat32(from, to))
9192                                         requiresInt16Capability = false;
9193                         }
9194
9195                         decl += "%i16        = OpTypeInt 16 1\n"
9196                                         "%u16        = OpTypeInt 16 0\n"
9197                                         "%i16vec2    = OpTypeVector %i16 2\n";
9198
9199                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9200                         if (requiresInt16Capability)
9201                                 caps += "OpCapability Int16\n";
9202                 }
9203
9204                 if (usesFloat16(from, to))
9205                 {
9206                         decl += "%f16        = OpTypeFloat 16\n";
9207
9208                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Float16
9209                         if (!(usesInt32(from, to) || usesFloat32(from, to)))
9210                                 caps += "OpCapability Float16\n";
9211                 }
9212
9213                 if (usesInt16(from, to) || usesFloat16(from, to))
9214                 {
9215                         caps += "OpCapability StorageUniformBufferBlock16\n";
9216                         exts += "OpExtension \"SPV_KHR_16bit_storage\"\n";
9217                 }
9218
9219                 if (usesInt64(from, to))
9220                 {
9221                         caps += "OpCapability Int64\n";
9222                         decl += "%i64        = OpTypeInt 64 1\n"
9223                                         "%u64        = OpTypeInt 64 0\n";
9224                 }
9225
9226                 if (usesFloat64(from, to))
9227                 {
9228                         caps += "OpCapability Float64\n";
9229                         decl += "%f64        = OpTypeFloat 64\n";
9230                 }
9231
9232                 m_asmTypes["datatype_capabilities"]             = caps;
9233                 m_asmTypes["datatype_additional_decl"]  = decl;
9234                 m_asmTypes["datatype_extensions"]               = exts;
9235         }
9236
9237         ConversionDataType              m_fromType;
9238         ConversionDataType              m_toType;
9239         string                                  m_name;
9240         map<string, string>             m_asmTypes;
9241         BufferSp                                m_inputBuffer;
9242         BufferSp                                m_outputBuffer;
9243 };
9244
9245 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
9246 {
9247         map<string, string> params = convertCase.m_asmTypes;
9248
9249         params["instruction"]   = instruction;
9250         params["inDecorator"]   = getByteWidthStr(convertCase.m_fromType);
9251         params["outDecorator"]  = getByteWidthStr(convertCase.m_toType);
9252
9253         const StringTemplate shader (
9254                 "OpCapability Shader\n"
9255                 "${datatype_capabilities}"
9256                 "${datatype_extensions:opt}"
9257                 "OpMemoryModel Logical GLSL450\n"
9258                 "OpEntryPoint GLCompute %main \"main\"\n"
9259                 "OpExecutionMode %main LocalSize 1 1 1\n"
9260                 "OpSource GLSL 430\n"
9261                 "OpName %main           \"main\"\n"
9262                 // Decorators
9263                 "OpDecorate %indata DescriptorSet 0\n"
9264                 "OpDecorate %indata Binding 0\n"
9265                 "OpDecorate %outdata DescriptorSet 0\n"
9266                 "OpDecorate %outdata Binding 1\n"
9267                 "OpDecorate %in_buf BufferBlock\n"
9268                 "OpDecorate %out_buf BufferBlock\n"
9269                 "OpMemberDecorate %in_buf 0 Offset 0\n"
9270                 "OpMemberDecorate %out_buf 0 Offset 0\n"
9271                 // Base types
9272                 "%void       = OpTypeVoid\n"
9273                 "%voidf      = OpTypeFunction %void\n"
9274                 "%u32        = OpTypeInt 32 0\n"
9275                 "%i32        = OpTypeInt 32 1\n"
9276                 "%f32        = OpTypeFloat 32\n"
9277                 "%v2i32      = OpTypeVector %i32 2\n"
9278                 "${datatype_additional_decl}"
9279                 "%uvec3      = OpTypeVector %u32 3\n"
9280                 // Derived types
9281                 "%in_ptr     = OpTypePointer Uniform %${inputType}\n"
9282                 "%out_ptr    = OpTypePointer Uniform %${outputType}\n"
9283                 "%in_buf     = OpTypeStruct %${inputType}\n"
9284                 "%out_buf    = OpTypeStruct %${outputType}\n"
9285                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
9286                 "%out_bufptr = OpTypePointer Uniform %out_buf\n"
9287                 "%indata     = OpVariable %in_bufptr Uniform\n"
9288                 "%outdata    = OpVariable %out_bufptr Uniform\n"
9289                 // Constants
9290                 "%zero       = OpConstant %i32 0\n"
9291                 // Main function
9292                 "%main       = OpFunction %void None %voidf\n"
9293                 "%label      = OpLabel\n"
9294                 "%inloc      = OpAccessChain %in_ptr %indata %zero\n"
9295                 "%outloc     = OpAccessChain %out_ptr %outdata %zero\n"
9296                 "%inval      = OpLoad %${inputType} %inloc\n"
9297                 "%conv       = ${instruction} %${outputType} %inval\n"
9298                 "              OpStore %outloc %conv\n"
9299                 "              OpReturn\n"
9300                 "              OpFunctionEnd\n"
9301         );
9302
9303         return shader.specialize(params);
9304 }
9305
9306 void createConvertCases (vector<ConvertCase>& testCases, const string& instruction)
9307 {
9308         if (instruction == "OpUConvert")
9309         {
9310                 // Convert unsigned int to unsigned int
9311                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_16,          42));
9312                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_32,          73));
9313                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_64,          121));
9314
9315                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_8,           33));
9316                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_32,          60653));
9317                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_64,          17991));
9318
9319                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_64,          904256275));
9320                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_16,          6275));
9321                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_8,           17));
9322
9323                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_32,          701256243));
9324                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_16,          4741));
9325                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_8,           65));
9326         }
9327         else if (instruction == "OpSConvert")
9328         {
9329                 // Sign extension int->int
9330                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_16,            -30));
9331                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_32,            55));
9332                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_64,            -3));
9333                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_32,            14669));
9334                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_64,            -3341));
9335                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_64,            973610259));
9336
9337                 // Truncate for int->int
9338                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_8,                     81));
9339                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_8,                     -93));
9340                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_8,                     3182748172687672ll,                                     true,   56));
9341                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_16,            12382));
9342                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_32,            -972812359));
9343                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_16,            -1067742499291926803ll,                         true,   -4371));
9344
9345                 // Sign extension for int->uint
9346                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_16,          56));
9347                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_32,          -47,                                                            true,   4294967249u));
9348                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_64,          -5,                                                                     true,   18446744073709551611ull));
9349                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_32,          14669));
9350                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_64,          -3341,                                                          true,   18446744073709548275ull));
9351                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_64,          973610259));
9352
9353                 // Truncate for int->uint
9354                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_8,           -25711,                                                         true,   145));
9355                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_8,           103));
9356                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_8,           -1067742499291926803ll,                         true,   61165));
9357                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_16,          12382));
9358                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_32,          -972812359,                                                     true,   3322154937u));
9359                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_16,          -1067742499291926803ll,                         true,   61165));
9360
9361                 // Sign extension for uint->int
9362                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_16,            71));
9363                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_32,            201,                                                            true,   -55));
9364                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_64,            188,                                                            true,   -68));
9365                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_32,            14669));
9366                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_64,            62195,                                                          true,   -3341));
9367                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_64,            973610259));
9368
9369                 // Truncate for uint->int
9370                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_8,                     67));
9371                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_8,                     133,                                                            true,   -123));
9372                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_8,                     836927654193256494ull,                          true,   46));
9373                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_16,            12382));
9374                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_32,            18446744072736739257ull,                        true,   -972812359));
9375                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_16,            17379001574417624813ull,                        true,   -4371));
9376
9377                 // Convert i16vec2 to i32vec2 and vice versa
9378                 // Unsigned values are used here to represent negative signed values and to allow defined shifting behaviour.
9379                 // The actual signed value -32123 is used here as uint16 value 33413 and uint32 value 4294935173
9380                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_16,       DATA_TYPE_VEC2_SIGNED_32,       (33413u << 16)                  | 27593,        true,   (4294935173ull << 32)   | 27593));
9381                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_32,       DATA_TYPE_VEC2_SIGNED_16,       (4294935173ull << 32)   | 27593,        true,   (33413u << 16)                  | 27593));
9382         }
9383         else if (instruction == "OpFConvert")
9384         {
9385                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9386                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_64,                     0x449a4000,                                                     true,   0x4093480000000000));
9387                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_32,                     0x4093480000000000,                                     true,   0x449a4000));
9388
9389                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_16,                     0x449a4000,                                                     true,   0x64D2));
9390                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_32,                     0x64D2,                                                         true,   0x449a4000));
9391
9392                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_64,                     0x64D2,                                                         true,   0x4093480000000000));
9393                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_16,                     0x4093480000000000,                                     true,   0x64D2));
9394         }
9395         else if (instruction == "OpConvertFToU")
9396         {
9397                 // Normal numbers from uint8 range
9398                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5020,                                                         true,   33,                                                                     "33"));
9399                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x42280000,                                                     true,   42,                                                                     "42"));
9400                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x4067800000000000ull,                          true,   188,                                                            "188"));
9401
9402                 // Maximum uint8 value
9403                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5BF8,                                                         true,   255,                                                            "max"));
9404                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x437F0000,                                                     true,   255,                                                            "max"));
9405                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x406FE00000000000ull,                          true,   255,                                                            "max"));
9406
9407                 // +0
9408                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x0000,                                                         true,   0,                                                                      "p0"));
9409                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x00000000,                                                     true,   0,                                                                      "p0"));
9410                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9411
9412                 // -0
9413                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x8000,                                                         true,   0,                                                                      "m0"));
9414                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x80000000,                                                     true,   0,                                                                      "m0"));
9415                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9416
9417                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9418                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x64D2,                                                         true,   1234,                                                           "1234"));
9419                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x64D2,                                                         true,   1234,                                                           "1234"));
9420                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x64D2,                                                         true,   1234,                                                           "1234"));
9421
9422                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9423                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x7BFF,                                                         true,   65504,                                                          "max"));
9424                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x7BFF,                                                         true,   65504,                                                          "max"));
9425                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x7BFF,                                                         true,   65504,                                                          "max"));
9426
9427                 // +0
9428                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x0000,                                                         true,   0,                                                                      "p0"));
9429                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x0000,                                                         true,   0,                                                                      "p0"));
9430                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x0000,                                                         true,   0,                                                                      "p0"));
9431
9432                 // -0
9433                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x8000,                                                         true,   0,                                                                      "m0"));
9434                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x8000,                                                         true,   0,                                                                      "m0"));
9435                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x8000,                                                         true,   0,                                                                      "m0"));
9436
9437                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_16,          0x449a4000,                                                     true,   1234));
9438                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_32,          0x449a4000,                                                     true,   1234));
9439                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_64,          0x449a4000,                                                     true,   1234));
9440                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_16,          0x4093480000000000,                                     true,   1234));
9441                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_32,          0x4093480000000000,                                     true,   1234));
9442                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_64,          0x4093480000000000,                                     true,   1234));
9443         }
9444         else if (instruction == "OpConvertUToF")
9445         {
9446                 // Normal numbers from uint8 range
9447                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     116,                                                            true,   0x5740,                                                         "116"));
9448                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     232,                                                            true,   0x43680000,                                                     "232"));
9449                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     164,                                                            true,   0x4064800000000000ull,                          "164"));
9450
9451                 // Maximum uint8 value
9452                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     255,                                                            true,   0x5BF8,                                                         "max"));
9453                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     255,                                                            true,   0x437F0000,                                                     "max"));
9454                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     255,                                                            true,   0x406FE00000000000ull,                          "max"));
9455
9456                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9457                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9458                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9459                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9460
9461                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9462                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9463                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9464                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9465
9466                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9467                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9468                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9469                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9470                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9471                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9472         }
9473         else if (instruction == "OpConvertFToS")
9474         {
9475                 // Normal numbers from int8 range
9476                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xC980,                                                         true,   -11,                                                            "m11"));
9477                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC2140000,                                                     true,   -37,                                                            "m37"));
9478                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC050800000000000ull,                          true,   -66,                                                            "m66"));
9479
9480                 // Minimum int8 value
9481                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xD800,                                                         true,   -128,                                                           "min"));
9482                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC3000000,                                                     true,   -128,                                                           "min"));
9483                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC060000000000000ull,                          true,   -128,                                                           "min"));
9484
9485                 // Maximum int8 value
9486                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x57F0,                                                         true,   127,                                                            "max"));
9487                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x42FE0000,                                                     true,   127,                                                            "max"));
9488                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x405FC00000000000ull,                          true,   127,                                                            "max"));
9489
9490                 // +0
9491                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x0000,                                                         true,   0,                                                                      "p0"));
9492                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x00000000,                                                     true,   0,                                                                      "p0"));
9493                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9494
9495                 // -0
9496                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x8000,                                                         true,   0,                                                                      "m0"));
9497                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x80000000,                                                     true,   0,                                                                      "m0"));
9498                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9499
9500                 // All hexadecimal values below represent -1234.0 as 32/64-bit IEEE 754 float
9501                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9502                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9503                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9504
9505                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9506                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xF800,                                                         true,   -32768,                                                         "min"));
9507                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xF800,                                                         true,   -32768,                                                         "min"));
9508                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xF800,                                                         true,   -32768,                                                         "min"));
9509
9510                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9511                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x77FF,                                                         true,   32752,                                                          "max"));
9512                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x77FF,                                                         true,   32752,                                                          "max"));
9513                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x77FF,                                                         true,   32752,                                                          "max"));
9514
9515                 // +0
9516                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x0000,                                                         true,   0,                                                                      "p0"));
9517                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x0000,                                                         true,   0,                                                                      "p0"));
9518                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x0000,                                                         true,   0,                                                                      "p0"));
9519
9520                 // -0
9521                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x8000,                                                         true,   0,                                                                      "m0"));
9522                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x8000,                                                         true,   0,                                                                      "m0"));
9523                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x8000,                                                         true,   0,                                                                      "m0"));
9524
9525                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc49a4000,                                                     true,   -1234));
9526                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_32,            0xc49a4000,                                                     true,   -1234));
9527                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_64,            0xc49a4000,                                                     true,   -1234));
9528                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_16,            0xc093480000000000,                                     true,   -1234));
9529                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_32,            0xc093480000000000,                                     true,   -1234));
9530                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_64,            0xc093480000000000,                                     true,   -1234));
9531                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0x453b9000,                                                     true,    3001,                                                          "p3001"));
9532                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc53b9000,                                                     true,   -3001,                                                          "m3001"));
9533         }
9534         else if (instruction == "OpConvertSToF")
9535         {
9536                 // Normal numbers from int8 range
9537                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -12,                                                            true,   0xCA00,                                                         "m21"));
9538                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -21,                                                            true,   0xC1A80000,                                                     "m21"));
9539                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -99,                                                            true,   0xC058C00000000000ull,                          "m99"));
9540
9541                 // Minimum int8 value
9542                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -128,                                                           true,   0xD800,                                                         "min"));
9543                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -128,                                                           true,   0xC3000000,                                                     "min"));
9544                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -128,                                                           true,   0xC060000000000000ull,                          "min"));
9545
9546                 // Maximum int8 value
9547                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     127,                                                            true,   0x57F0,                                                         "max"));
9548                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     127,                                                            true,   0x42FE0000,                                                     "max"));
9549                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     127,                                                            true,   0x405FC00000000000ull,                          "max"));
9550
9551                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9552                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9553                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9554                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9555
9556                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9557                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9558                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9559                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9560
9561                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9562                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9563                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9564                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9565
9566                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9567                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9568                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9569                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9570                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9571                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9572         }
9573         else
9574                 DE_FATAL("Unknown instruction");
9575 }
9576
9577 const map<string, string> getConvertCaseFragments (string instruction, const ConvertCase& convertCase)
9578 {
9579         map<string, string> params = convertCase.m_asmTypes;
9580         map<string, string> fragments;
9581
9582         params["instruction"] = instruction;
9583         params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
9584
9585         const StringTemplate decoration (
9586                 "      OpDecorate %SSBOi DescriptorSet 0\n"
9587                 "      OpDecorate %SSBOo DescriptorSet 0\n"
9588                 "      OpDecorate %SSBOi Binding 0\n"
9589                 "      OpDecorate %SSBOo Binding 1\n"
9590                 "      OpDecorate %s_SSBOi Block\n"
9591                 "      OpDecorate %s_SSBOo Block\n"
9592                 "OpMemberDecorate %s_SSBOi 0 Offset 0\n"
9593                 "OpMemberDecorate %s_SSBOo 0 Offset 0\n");
9594
9595         const StringTemplate pre_main (
9596                 "${datatype_additional_decl:opt}"
9597                 "    %ptr_in = OpTypePointer StorageBuffer %${inputType}\n"
9598                 "   %ptr_out = OpTypePointer StorageBuffer %${outputType}\n"
9599                 "   %s_SSBOi = OpTypeStruct %${inputType}\n"
9600                 "   %s_SSBOo = OpTypeStruct %${outputType}\n"
9601                 " %ptr_SSBOi = OpTypePointer StorageBuffer %s_SSBOi\n"
9602                 " %ptr_SSBOo = OpTypePointer StorageBuffer %s_SSBOo\n"
9603                 "     %SSBOi = OpVariable %ptr_SSBOi StorageBuffer\n"
9604                 "     %SSBOo = OpVariable %ptr_SSBOo StorageBuffer\n");
9605
9606         const StringTemplate testfun (
9607                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9608                 "%param     = OpFunctionParameter %v4f32\n"
9609                 "%label     = OpLabel\n"
9610                 "%iLoc      = OpAccessChain %ptr_in %SSBOi %c_u32_0\n"
9611                 "%oLoc      = OpAccessChain %ptr_out %SSBOo %c_u32_0\n"
9612                 "%valIn     = OpLoad %${inputType} %iLoc\n"
9613                 "%valOut    = ${instruction} %${outputType} %valIn\n"
9614                 "             OpStore %oLoc %valOut\n"
9615                 "             OpReturnValue %param\n"
9616                 "             OpFunctionEnd\n");
9617
9618         params["datatype_extensions"] =
9619                 params["datatype_extensions"] +
9620                 "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n";
9621
9622         fragments["capability"] = params["datatype_capabilities"];
9623         fragments["extension"]  = params["datatype_extensions"];
9624         fragments["decoration"] = decoration.specialize(params);
9625         fragments["pre_main"]   = pre_main.specialize(params);
9626         fragments["testfun"]    = testfun.specialize(params);
9627
9628         return fragments;
9629 }
9630
9631 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in compute shaders
9632 tcu::TestCaseGroup* createConvertComputeTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9633 {
9634         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9635         vector<ConvertCase>                                     testCases;
9636         createConvertCases(testCases, instruction);
9637
9638         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9639         {
9640                 ComputeShaderSpec spec;
9641                 spec.assembly                   = getConvertCaseShaderStr(instruction, *test);
9642                 spec.numWorkGroups              = IVec3(1, 1, 1);
9643                 spec.inputs.push_back   (test->m_inputBuffer);
9644                 spec.outputs.push_back  (test->m_outputBuffer);
9645
9646                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, spec.requestedVulkanFeatures, spec.extensions);
9647
9648                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "", spec));
9649         }
9650         return group.release();
9651 }
9652
9653 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in graphics shaders
9654 tcu::TestCaseGroup* createConvertGraphicsTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9655 {
9656         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9657         vector<ConvertCase>                                     testCases;
9658         createConvertCases(testCases, instruction);
9659
9660         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9661         {
9662                 map<string, string>     fragments               = getConvertCaseFragments(instruction, *test);
9663                 VulkanFeatures          vulkanFeatures;
9664                 GraphicsResources       resources;
9665                 vector<string>          extensions;
9666                 SpecConstants           noSpecConstants;
9667                 PushConstants           noPushConstants;
9668                 GraphicsInterfaces      noInterfaces;
9669                 tcu::RGBA                       defaultColors[4];
9670
9671                 getDefaultColors                        (defaultColors);
9672                 resources.inputs.push_back      (Resource(test->m_inputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9673                 resources.outputs.push_back     (Resource(test->m_outputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9674                 extensions.push_back            ("VK_KHR_storage_buffer_storage_class");
9675
9676                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, vulkanFeatures, extensions);
9677
9678                 createTestsForAllStages(
9679                         test->m_name, defaultColors, defaultColors, fragments, noSpecConstants,
9680                         noPushConstants, resources, noInterfaces, extensions, vulkanFeatures, group.get());
9681         }
9682         return group.release();
9683 }
9684
9685 // Constant-Creation Instructions: OpConstant, OpConstantComposite
9686 tcu::TestCaseGroup* createOpConstantFloat16Tests(tcu::TestContext& testCtx)
9687 {
9688         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstant", "OpConstant and OpConstantComposite instruction"));
9689         RGBA                                                    inputColors[4];
9690         RGBA                                                    outputColors[4];
9691         vector<string>                                  extensions;
9692         GraphicsResources                               resources;
9693         VulkanFeatures                                  features;
9694
9695         const char                                              functionStart[]  =
9696                 "%test_code             = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9697                 "%param1                = OpFunctionParameter %v4f32\n"
9698                 "%lbl                   = OpLabel\n";
9699
9700         const char                                              functionEnd[]           =
9701                 "%transformed_param_32  = OpFConvert %v4f32 %transformed_param\n"
9702                 "                         OpReturnValue %transformed_param_32\n"
9703                 "                         OpFunctionEnd\n";
9704
9705         struct NameConstantsCode
9706         {
9707                 string name;
9708                 string constants;
9709                 string code;
9710         };
9711
9712 #define FLOAT_16_COMMON_TYPES_AND_CONSTS \
9713                         "%f16                  = OpTypeFloat 16\n"                                                 \
9714                         "%c_f16_0              = OpConstant %f16 0.0\n"                                            \
9715                         "%c_f16_0_5            = OpConstant %f16 0.5\n"                                            \
9716                         "%c_f16_1              = OpConstant %f16 1.0\n"                                            \
9717                         "%v4f16                = OpTypeVector %f16 4\n"                                            \
9718                         "%fp_f16               = OpTypePointer Function %f16\n"                                    \
9719                         "%fp_v4f16             = OpTypePointer Function %v4f16\n"                                  \
9720                         "%c_v4f16_1_1_1_1      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n" \
9721                         "%a4f16                = OpTypeArray %f16 %c_u32_4\n"                                      \
9722
9723         NameConstantsCode                               tests[] =
9724         {
9725                 {
9726                         "vec4",
9727
9728                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9729                         "%cval                 = OpConstantComposite %v4f16 %c_f16_0_5 %c_f16_0_5 %c_f16_0_5 %c_f16_0\n",
9730                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9731                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %cval\n"
9732                 },
9733                 {
9734                         "struct",
9735
9736                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9737                         "%stype                = OpTypeStruct %v4f16 %f16\n"
9738                         "%fp_stype             = OpTypePointer Function %stype\n"
9739                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9740                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9741                         "%cvec                 = OpConstantComposite %v4f16 %f16_1_5 %f16_1_5 %f16_1_5 %c_f16_1\n"
9742                         "%cval                 = OpConstantComposite %stype %cvec %f16_n_1\n",
9743
9744                         "%v                    = OpVariable %fp_stype Function %cval\n"
9745                         "%vec_ptr              = OpAccessChain %fp_v4f16 %v %c_u32_0\n"
9746                         "%f16_ptr              = OpAccessChain %fp_f16 %v %c_u32_1\n"
9747                         "%vec_val              = OpLoad %v4f16 %vec_ptr\n"
9748                         "%f16_val              = OpLoad %f16 %f16_ptr\n"
9749                         "%tmp1                 = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_1 %f16_val\n" // vec4(-1)
9750                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9751                         "%tmp2                 = OpFAdd %v4f16 %tmp1 %param1_16\n" // param1 + vec4(-1)
9752                         "%transformed_param    = OpFAdd %v4f16 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
9753                 },
9754                 {
9755                         // [1|0|0|0.5] [x] = x + 0.5
9756                         // [0|1|0|0.5] [y] = y + 0.5
9757                         // [0|0|1|0.5] [z] = z + 0.5
9758                         // [0|0|0|1  ] [1] = 1
9759                         "matrix",
9760
9761                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9762                         "%mat4x4_f16           = OpTypeMatrix %v4f16 4\n"
9763                         "%v4f16_1_0_0_0        = OpConstantComposite %v4f16 %c_f16_1 %c_f16_0 %c_f16_0 %c_f16_0\n"
9764                         "%v4f16_0_1_0_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_1 %c_f16_0 %c_f16_0\n"
9765                         "%v4f16_0_0_1_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_1 %c_f16_0\n"
9766                         "%v4f16_0_5_0_5_0_5_1  = OpConstantComposite %v4f16 %c_f16_0_5 %c_f16_0_5 %c_f16_0_5 %c_f16_1\n"
9767                         "%cval                 = OpConstantComposite %mat4x4_f16 %v4f16_1_0_0_0 %v4f16_0_1_0_0 %v4f16_0_0_1_0 %v4f16_0_5_0_5_0_5_1\n",
9768
9769                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9770                         "%transformed_param    = OpMatrixTimesVector %v4f16 %cval %param1_16\n"
9771                 },
9772                 {
9773                         "array",
9774
9775                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9776                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9777                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9778                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9779                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9780                         "%carr                 = OpConstantComposite %a4f16 %c_f16_0 %f16_n_1 %f16_1_5 %c_f16_0\n",
9781
9782                         "%v                    = OpVariable %fp_a4f16 Function %carr\n"
9783                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_0\n"
9784                         "%f1                   = OpAccessChain %fp_f16 %v %c_u32_1\n"
9785                         "%f2                   = OpAccessChain %fp_f16 %v %c_u32_2\n"
9786                         "%f3                   = OpAccessChain %fp_f16 %v %c_u32_3\n"
9787                         "%f_val                = OpLoad %f16 %f\n"
9788                         "%f1_val               = OpLoad %f16 %f1\n"
9789                         "%f2_val               = OpLoad %f16 %f2\n"
9790                         "%f3_val               = OpLoad %f16 %f3\n"
9791                         "%ftot1                = OpFAdd %f16 %f_val %f1_val\n"
9792                         "%ftot2                = OpFAdd %f16 %ftot1 %f2_val\n"
9793                         "%ftot3                = OpFAdd %f16 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
9794                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %ftot3\n"
9795                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9796                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
9797                 },
9798                 {
9799                         //
9800                         // [
9801                         //   {
9802                         //      0.0,
9803                         //      [ 1.0, 1.0, 1.0, 1.0]
9804                         //   },
9805                         //   {
9806                         //      1.0,
9807                         //      [ 0.0, 0.5, 0.0, 0.0]
9808                         //   }, //     ^^^
9809                         //   {
9810                         //      0.0,
9811                         //      [ 1.0, 1.0, 1.0, 1.0]
9812                         //   }
9813                         // ]
9814                         "array_of_struct_of_array",
9815
9816                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9817                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9818                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9819                         "%stype                = OpTypeStruct %f16 %a4f16\n"
9820                         "%a3stype              = OpTypeArray %stype %c_u32_3\n"
9821                         "%fp_a3stype           = OpTypePointer Function %a3stype\n"
9822                         "%ca4f16_0             = OpConstantComposite %a4f16 %c_f16_0 %c_f16_0_5 %c_f16_0 %c_f16_0\n"
9823                         "%ca4f16_1             = OpConstantComposite %a4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n"
9824                         "%cstype1              = OpConstantComposite %stype %c_f16_0 %ca4f16_1\n"
9825                         "%cstype2              = OpConstantComposite %stype %c_f16_1 %ca4f16_0\n"
9826                         "%carr                 = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
9827
9828                         "%v                    = OpVariable %fp_a3stype Function %carr\n"
9829                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
9830                         "%f_l                  = OpLoad %f16 %f\n"
9831                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %f_l\n"
9832                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9833                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
9834                 }
9835         };
9836
9837         getHalfColorsFullAlpha(inputColors);
9838         outputColors[0] = RGBA(255, 255, 255, 255);
9839         outputColors[1] = RGBA(255, 127, 127, 255);
9840         outputColors[2] = RGBA(127, 255, 127, 255);
9841         outputColors[3] = RGBA(127, 127, 255, 255);
9842
9843         extensions.push_back("VK_KHR_16bit_storage");
9844         extensions.push_back("VK_KHR_shader_float16_int8");
9845         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
9846
9847         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
9848         {
9849                 map<string, string> fragments;
9850
9851                 fragments["extension"]  = "OpExtension \"SPV_KHR_16bit_storage\"";
9852                 fragments["capability"] = "OpCapability Float16\n";
9853                 fragments["pre_main"]   = tests[testNdx].constants;
9854                 fragments["testfun"]    = string(functionStart) + tests[testNdx].code + functionEnd;
9855
9856                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, resources, extensions, opConstantCompositeTests.get(), features);
9857         }
9858         return opConstantCompositeTests.release();
9859 }
9860
9861 template<typename T>
9862 void finalizeTestsCreation (T&                                                  specResource,
9863                                                         const map<string, string>&      fragments,
9864                                                         tcu::TestContext&                       testCtx,
9865                                                         tcu::TestCaseGroup&                     testGroup,
9866                                                         const std::string&                      testName,
9867                                                         const VulkanFeatures&           vulkanFeatures,
9868                                                         const vector<string>&           extensions,
9869                                                         const IVec3&                            numWorkGroups);
9870
9871 template<>
9872 void finalizeTestsCreation (GraphicsResources&                  specResource,
9873                                                         const map<string, string>&      fragments,
9874                                                         tcu::TestContext&                       ,
9875                                                         tcu::TestCaseGroup&                     testGroup,
9876                                                         const std::string&                      testName,
9877                                                         const VulkanFeatures&           vulkanFeatures,
9878                                                         const vector<string>&           extensions,
9879                                                         const IVec3&                            )
9880 {
9881         RGBA defaultColors[4];
9882         getDefaultColors(defaultColors);
9883
9884         createTestsForAllStages(testName, defaultColors, defaultColors, fragments, specResource, extensions, &testGroup, vulkanFeatures);
9885 }
9886
9887 template<>
9888 void finalizeTestsCreation (ComputeShaderSpec&                  specResource,
9889                                                         const map<string, string>&      fragments,
9890                                                         tcu::TestContext&                       testCtx,
9891                                                         tcu::TestCaseGroup&                     testGroup,
9892                                                         const std::string&                      testName,
9893                                                         const VulkanFeatures&           vulkanFeatures,
9894                                                         const vector<string>&           extensions,
9895                                                         const IVec3&                            numWorkGroups)
9896 {
9897         specResource.numWorkGroups = numWorkGroups;
9898         specResource.requestedVulkanFeatures = vulkanFeatures;
9899         specResource.extensions = extensions;
9900
9901         specResource.assembly = makeComputeShaderAssembly(fragments);
9902
9903         testGroup.addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", specResource));
9904 }
9905
9906 template<class SpecResource>
9907 tcu::TestCaseGroup* createFloat16LogicalSet (tcu::TestContext& testCtx, const bool nanSupported)
9908 {
9909         const string                                            nan                                     = nanSupported ? "_nan" : "";
9910         const string                                            groupName                       = "logical" + nan;
9911         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Float 16 logical tests"));
9912
9913         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
9914         const string                                            spvCapabilities         = string("OpCapability StorageUniformBufferBlock16\n") + (nanSupported ? "OpCapability SignedZeroInfNanPreserve\n" : "");
9915         const string                                            spvExtensions           = string("OpExtension \"SPV_KHR_16bit_storage\"\n") + (nanSupported ? "OpExtension \"SPV_KHR_float_controls\"\n" : "");
9916         const string                                            spvExecutionMode        = nanSupported ? "OpExecutionMode %BP_main SignedZeroInfNanPreserve 16\n" : "";
9917         const deUint32                                          numDataPoints           = 16;
9918         const vector<deFloat16>                         float16Data                     = getFloat16s(rnd, numDataPoints);
9919         const vector<deFloat16>                         float16Data1            = squarize(float16Data, 0);
9920         const vector<deFloat16>                         float16Data2            = squarize(float16Data, 1);
9921         const vector<deFloat16>                         float16DataVec1         = squarizeVector(float16Data, 0);
9922         const vector<deFloat16>                         float16DataVec2         = squarizeVector(float16Data, 1);
9923         const vector<deFloat16>                         float16OutDummy         (float16Data1.size(), 0);
9924         const vector<deFloat16>                         float16OutVecDummy      (float16DataVec1.size(), 0);
9925
9926         struct TestOp
9927         {
9928                 const char*             opCode;
9929                 VerifyIOFunc    verifyFuncNan;
9930                 VerifyIOFunc    verifyFuncNonNan;
9931                 const deUint32  argCount;
9932         };
9933
9934         const TestOp    testOps[]       =
9935         {
9936                 { "OpIsNan"                                             ,       compareFP16Logical<fp16isNan,                           true,  false, true>,    compareFP16Logical<fp16isNan,                           true,  false, false>,   1       },
9937                 { "OpIsInf"                                             ,       compareFP16Logical<fp16isInf,                           true,  false, true>,    compareFP16Logical<fp16isInf,                           true,  false, false>,   1       },
9938                 { "OpFOrdEqual"                                 ,       compareFP16Logical<fp16isEqual,                         false, true,  true>,    compareFP16Logical<fp16isEqual,                         false, true,  false>,   2       },
9939                 { "OpFUnordEqual"                               ,       compareFP16Logical<fp16isEqual,                         false, false, true>,    compareFP16Logical<fp16isEqual,                         false, false, false>,   2       },
9940                 { "OpFOrdNotEqual"                              ,       compareFP16Logical<fp16isUnequal,                       false, true,  true>,    compareFP16Logical<fp16isUnequal,                       false, true,  false>,   2       },
9941                 { "OpFUnordNotEqual"                    ,       compareFP16Logical<fp16isUnequal,                       false, false, true>,    compareFP16Logical<fp16isUnequal,                       false, false, false>,   2       },
9942                 { "OpFOrdLessThan"                              ,       compareFP16Logical<fp16isLess,                          false, true,  true>,    compareFP16Logical<fp16isLess,                          false, true,  false>,   2       },
9943                 { "OpFUnordLessThan"                    ,       compareFP16Logical<fp16isLess,                          false, false, true>,    compareFP16Logical<fp16isLess,                          false, false, false>,   2       },
9944                 { "OpFOrdGreaterThan"                   ,       compareFP16Logical<fp16isGreater,                       false, true,  true>,    compareFP16Logical<fp16isGreater,                       false, true,  false>,   2       },
9945                 { "OpFUnordGreaterThan"                 ,       compareFP16Logical<fp16isGreater,                       false, false, true>,    compareFP16Logical<fp16isGreater,                       false, false, false>,   2       },
9946                 { "OpFOrdLessThanEqual"                 ,       compareFP16Logical<fp16isLessOrEqual,           false, true,  true>,    compareFP16Logical<fp16isLessOrEqual,           false, true,  false>,   2       },
9947                 { "OpFUnordLessThanEqual"               ,       compareFP16Logical<fp16isLessOrEqual,           false, false, true>,    compareFP16Logical<fp16isLessOrEqual,           false, false, false>,   2       },
9948                 { "OpFOrdGreaterThanEqual"              ,       compareFP16Logical<fp16isGreaterOrEqual,        false, true,  true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, true,  false>,   2       },
9949                 { "OpFUnordGreaterThanEqual"    ,       compareFP16Logical<fp16isGreaterOrEqual,        false, false, true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, false, false>,   2       },
9950         };
9951
9952         { // scalar cases
9953                 const StringTemplate preMain
9954                 (
9955                         "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
9956                         "      %f16 = OpTypeFloat 16\n"
9957                         "  %c_f16_0 = OpConstant %f16 0.0\n"
9958                         "  %c_f16_1 = OpConstant %f16 1.0\n"
9959                         "   %up_f16 = OpTypePointer Uniform %f16\n"
9960                         "   %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
9961                         "   %SSBO16 = OpTypeStruct %ra_f16\n"
9962                         "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
9963                         "%ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
9964                         "%ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
9965                         " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
9966                 );
9967
9968                 const StringTemplate decoration
9969                 (
9970                         "OpDecorate %ra_f16 ArrayStride 2\n"
9971                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
9972                         "OpDecorate %SSBO16 BufferBlock\n"
9973                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
9974                         "OpDecorate %ssbo_src0 Binding 0\n"
9975                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
9976                         "OpDecorate %ssbo_src1 Binding 1\n"
9977                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
9978                         "OpDecorate %ssbo_dst Binding 2\n"
9979                 );
9980
9981                 const StringTemplate testFun
9982                 (
9983                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9984                         "    %param = OpFunctionParameter %v4f32\n"
9985
9986                         "    %entry = OpLabel\n"
9987                         "        %i = OpVariable %fp_i32 Function\n"
9988                         "             OpStore %i %c_i32_0\n"
9989                         "             OpBranch %loop\n"
9990
9991                         "     %loop = OpLabel\n"
9992                         "    %i_cmp = OpLoad %i32 %i\n"
9993                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
9994                         "             OpLoopMerge %merge %next None\n"
9995                         "             OpBranchConditional %lt %write %merge\n"
9996
9997                         "    %write = OpLabel\n"
9998                         "      %ndx = OpLoad %i32 %i\n"
9999
10000                         "     %src0 = OpAccessChain %up_f16 %ssbo_src0 %c_i32_0 %ndx\n"
10001                         " %val_src0 = OpLoad %f16 %src0\n"
10002
10003                         "${op_arg1_calc}"
10004
10005                         " %val_bdst = ${op_code} %bool %val_src0 ${op_arg1}\n"
10006                         "  %val_dst = OpSelect %f16 %val_bdst %c_f16_1 %c_f16_0\n"
10007                         "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10008                         "             OpStore %dst %val_dst\n"
10009                         "             OpBranch %next\n"
10010
10011                         "     %next = OpLabel\n"
10012                         "    %i_cur = OpLoad %i32 %i\n"
10013                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10014                         "             OpStore %i %i_new\n"
10015                         "             OpBranch %loop\n"
10016
10017                         "    %merge = OpLabel\n"
10018                         "             OpReturnValue %param\n"
10019
10020                         "             OpFunctionEnd\n"
10021                 );
10022
10023                 const StringTemplate arg1Calc
10024                 (
10025                         "     %src1 = OpAccessChain %up_f16 %ssbo_src1 %c_i32_0 %ndx\n"
10026                         " %val_src1 = OpLoad %f16 %src1\n"
10027                 );
10028
10029                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10030                 {
10031                         const size_t            iterations              = float16Data1.size();
10032                         const TestOp&           testOp                  = testOps[testOpsIdx];
10033                         const string            testName                = de::toLower(string(testOp.opCode)) + "_scalar";
10034                         SpecResource            specResource;
10035                         map<string, string>     specs;
10036                         VulkanFeatures          features;
10037                         map<string, string>     fragments;
10038                         vector<string>          extensions;
10039
10040                         specs["num_data_points"]        = de::toString(iterations);
10041                         specs["op_code"]                        = testOp.opCode;
10042                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10043                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10044
10045                         fragments["extension"]          = spvExtensions;
10046                         fragments["capability"]         = spvCapabilities;
10047                         fragments["execution_mode"]     = spvExecutionMode;
10048                         fragments["decoration"]         = decoration.specialize(specs);
10049                         fragments["pre_main"]           = preMain.specialize(specs);
10050                         fragments["testfun"]            = testFun.specialize(specs);
10051
10052                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10053                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10054                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10055                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10056
10057                         extensions.push_back("VK_KHR_16bit_storage");
10058                         extensions.push_back("VK_KHR_shader_float16_int8");
10059
10060                         if (nanSupported)
10061                         {
10062                                 extensions.push_back("VK_KHR_shader_float_controls");
10063
10064                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10065                         }
10066
10067                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10068                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10069
10070                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10071                 }
10072         }
10073         { // vector cases
10074                 const StringTemplate preMain
10075                 (
10076                         "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10077                         "     %v2bool = OpTypeVector %bool 2\n"
10078                         "        %f16 = OpTypeFloat 16\n"
10079                         "    %c_f16_0 = OpConstant %f16 0.0\n"
10080                         "    %c_f16_1 = OpConstant %f16 1.0\n"
10081                         "      %v2f16 = OpTypeVector %f16 2\n"
10082                         "%c_v2f16_0_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10083                         "%c_v2f16_1_1 = OpConstantComposite %v2f16 %c_f16_1 %c_f16_1\n"
10084                         "   %up_v2f16 = OpTypePointer Uniform %v2f16\n"
10085                         "   %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
10086                         "     %SSBO16 = OpTypeStruct %ra_v2f16\n"
10087                         "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10088                         "  %ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
10089                         "  %ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
10090                         "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10091                 );
10092
10093                 const StringTemplate decoration
10094                 (
10095                         "OpDecorate %ra_v2f16 ArrayStride 4\n"
10096                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
10097                         "OpDecorate %SSBO16 BufferBlock\n"
10098                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
10099                         "OpDecorate %ssbo_src0 Binding 0\n"
10100                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
10101                         "OpDecorate %ssbo_src1 Binding 1\n"
10102                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
10103                         "OpDecorate %ssbo_dst Binding 2\n"
10104                 );
10105
10106                 const StringTemplate testFun
10107                 (
10108                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10109                         "    %param = OpFunctionParameter %v4f32\n"
10110
10111                         "    %entry = OpLabel\n"
10112                         "        %i = OpVariable %fp_i32 Function\n"
10113                         "             OpStore %i %c_i32_0\n"
10114                         "             OpBranch %loop\n"
10115
10116                         "     %loop = OpLabel\n"
10117                         "    %i_cmp = OpLoad %i32 %i\n"
10118                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10119                         "             OpLoopMerge %merge %next None\n"
10120                         "             OpBranchConditional %lt %write %merge\n"
10121
10122                         "    %write = OpLabel\n"
10123                         "      %ndx = OpLoad %i32 %i\n"
10124
10125                         "     %src0 = OpAccessChain %up_v2f16 %ssbo_src0 %c_i32_0 %ndx\n"
10126                         " %val_src0 = OpLoad %v2f16 %src0\n"
10127
10128                         "${op_arg1_calc}"
10129
10130                         " %val_bdst = ${op_code} %v2bool %val_src0 ${op_arg1}\n"
10131                         "  %val_dst = OpSelect %v2f16 %val_bdst %c_v2f16_1_1 %c_v2f16_0_0\n"
10132                         "      %dst = OpAccessChain %up_v2f16 %ssbo_dst %c_i32_0 %ndx\n"
10133                         "             OpStore %dst %val_dst\n"
10134                         "             OpBranch %next\n"
10135
10136                         "     %next = OpLabel\n"
10137                         "    %i_cur = OpLoad %i32 %i\n"
10138                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10139                         "             OpStore %i %i_new\n"
10140                         "             OpBranch %loop\n"
10141
10142                         "    %merge = OpLabel\n"
10143                         "             OpReturnValue %param\n"
10144
10145                         "             OpFunctionEnd\n"
10146                 );
10147
10148                 const StringTemplate arg1Calc
10149                 (
10150                         "     %src1 = OpAccessChain %up_v2f16 %ssbo_src1 %c_i32_0 %ndx\n"
10151                         " %val_src1 = OpLoad %v2f16 %src1\n"
10152                 );
10153
10154                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10155                 {
10156                         const deUint32          itemsPerVec     = 2;
10157                         const size_t            iterations      = float16DataVec1.size() / itemsPerVec;
10158                         const TestOp&           testOp          = testOps[testOpsIdx];
10159                         const string            testName        = de::toLower(string(testOp.opCode)) + "_vector";
10160                         SpecResource            specResource;
10161                         map<string, string>     specs;
10162                         vector<string>          extensions;
10163                         VulkanFeatures          features;
10164                         map<string, string>     fragments;
10165
10166                         specs["num_data_points"]        = de::toString(iterations);
10167                         specs["op_code"]                        = testOp.opCode;
10168                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10169                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10170
10171                         fragments["extension"]          = spvExtensions;
10172                         fragments["capability"]         = spvCapabilities;
10173                         fragments["execution_mode"]     = spvExecutionMode;
10174                         fragments["decoration"]         = decoration.specialize(specs);
10175                         fragments["pre_main"]           = preMain.specialize(specs);
10176                         fragments["testfun"]            = testFun.specialize(specs);
10177
10178                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10179                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10180                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutVecDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10181                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10182
10183                         extensions.push_back("VK_KHR_16bit_storage");
10184                         extensions.push_back("VK_KHR_shader_float16_int8");
10185
10186                         if (nanSupported)
10187                         {
10188                                 extensions.push_back("VK_KHR_shader_float_controls");
10189
10190                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10191                         }
10192
10193                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10194                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10195
10196                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10197                 }
10198         }
10199
10200         return testGroup.release();
10201 }
10202
10203 bool compareFP16FunctionSetFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10204 {
10205         if (inputs.size() != 1 || outputAllocs.size() != 1)
10206                 return false;
10207
10208         vector<deUint8> input1Bytes;
10209
10210         inputs[0].getBytes(input1Bytes);
10211
10212         const deUint16* const   input1AsFP16    = (const deUint16*)&input1Bytes[0];
10213         const deUint16* const   outputAsFP16    = (const deUint16*)outputAllocs[0]->getHostPtr();
10214         std::string                             error;
10215
10216         for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deUint16); ++idx)
10217         {
10218                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
10219                 {
10220                         log << TestLog::Message << error << TestLog::EndMessage;
10221
10222                         return false;
10223                 }
10224         }
10225
10226         return true;
10227 }
10228
10229 template<class SpecResource>
10230 tcu::TestCaseGroup* createFloat16FuncSet (tcu::TestContext& testCtx)
10231 {
10232         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "function", "Float 16 function call related tests"));
10233
10234         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10235         const StringTemplate                            capabilities            ("OpCapability ${cap}\n");
10236         const deUint32                                          numDataPoints           = 256;
10237         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10238         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10239         map<string, string>                                     fragments;
10240
10241         struct TestType
10242         {
10243                 const deUint32  typeComponents;
10244                 const char*             typeName;
10245                 const char*             typeDecls;
10246         };
10247
10248         const TestType  testTypes[]     =
10249         {
10250                 {
10251                         1,
10252                         "f16",
10253                         ""
10254                 },
10255                 {
10256                         2,
10257                         "v2f16",
10258                         "      %v2f16 = OpTypeVector %f16 2\n"
10259                         "  %c_v2f16_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10260                 },
10261                 {
10262                         4,
10263                         "v4f16",
10264                         "      %v4f16 = OpTypeVector %f16 4\n"
10265                         "  %c_v4f16_0 = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_0 %c_f16_0\n"
10266                 },
10267         };
10268
10269         const StringTemplate preMain
10270         (
10271                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10272                 "     %v2bool = OpTypeVector %bool 2\n"
10273                 "        %f16 = OpTypeFloat 16\n"
10274                 "    %c_f16_0 = OpConstant %f16 0.0\n"
10275
10276                 "${type_decls}"
10277
10278                 "  %${tt}_fun = OpTypeFunction %${tt} %${tt}\n"
10279                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10280                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10281                 "     %SSBO16 = OpTypeStruct %ra_${tt}\n"
10282                 "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10283                 "   %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10284                 "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10285         );
10286
10287         const StringTemplate decoration
10288         (
10289                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10290                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10291                 "OpDecorate %SSBO16 BufferBlock\n"
10292                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10293                 "OpDecorate %ssbo_src Binding 0\n"
10294                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10295                 "OpDecorate %ssbo_dst Binding 1\n"
10296         );
10297
10298         const StringTemplate testFun
10299         (
10300                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10301                 "    %param = OpFunctionParameter %v4f32\n"
10302                 "    %entry = OpLabel\n"
10303
10304                 "        %i = OpVariable %fp_i32 Function\n"
10305                 "             OpStore %i %c_i32_0\n"
10306                 "             OpBranch %loop\n"
10307
10308                 "     %loop = OpLabel\n"
10309                 "    %i_cmp = OpLoad %i32 %i\n"
10310                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10311                 "             OpLoopMerge %merge %next None\n"
10312                 "             OpBranchConditional %lt %write %merge\n"
10313
10314                 "    %write = OpLabel\n"
10315                 "      %ndx = OpLoad %i32 %i\n"
10316
10317                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10318                 "  %val_src = OpLoad %${tt} %src\n"
10319
10320                 "  %val_dst = OpFunctionCall %${tt} %pass_fun %val_src\n"
10321                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10322                 "             OpStore %dst %val_dst\n"
10323                 "             OpBranch %next\n"
10324
10325                 "     %next = OpLabel\n"
10326                 "    %i_cur = OpLoad %i32 %i\n"
10327                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10328                 "             OpStore %i %i_new\n"
10329                 "             OpBranch %loop\n"
10330
10331                 "    %merge = OpLabel\n"
10332                 "             OpReturnValue %param\n"
10333
10334                 "             OpFunctionEnd\n"
10335
10336                 " %pass_fun = OpFunction %${tt} None %${tt}_fun\n"
10337                 "   %param0 = OpFunctionParameter %${tt}\n"
10338                 " %entry_pf = OpLabel\n"
10339                 "     %res0 = OpFAdd %${tt} %param0 %c_${tt}_0\n"
10340                 "             OpReturnValue %res0\n"
10341                 "             OpFunctionEnd\n"
10342         );
10343
10344         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10345         {
10346                 const TestType&         testType                = testTypes[testTypeIdx];
10347                 const string            testName                = testType.typeName;
10348                 const deUint32          itemsPerType    = testType.typeComponents;
10349                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10350                 const size_t            typeStride              = itemsPerType * sizeof(deFloat16);
10351                 SpecResource            specResource;
10352                 map<string, string>     specs;
10353                 VulkanFeatures          features;
10354                 vector<string>          extensions;
10355
10356                 specs["cap"]                            = "StorageUniformBufferBlock16";
10357                 specs["num_data_points"]        = de::toString(iterations);
10358                 specs["tt"]                                     = testType.typeName;
10359                 specs["tt_stride"]                      = de::toString(typeStride);
10360                 specs["type_decls"]                     = testType.typeDecls;
10361
10362                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10363                 fragments["capability"]         = capabilities.specialize(specs);
10364                 fragments["decoration"]         = decoration.specialize(specs);
10365                 fragments["pre_main"]           = preMain.specialize(specs);
10366                 fragments["testfun"]            = testFun.specialize(specs);
10367
10368                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10369                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10370                 specResource.verifyIO = compareFP16FunctionSetFunc;
10371
10372                 extensions.push_back("VK_KHR_16bit_storage");
10373                 extensions.push_back("VK_KHR_shader_float16_int8");
10374
10375                 features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10376                 features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10377
10378                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10379         }
10380
10381         return testGroup.release();
10382 }
10383
10384 struct getV_    { deUint32 inline operator()(deUint32 v) const  { return v;        } getV_(){} };
10385 struct getV0    { deUint32 inline operator()(deUint32 v) const  { return v & (~1); } getV0(){} };
10386 struct getV1    { deUint32 inline operator()(deUint32 v) const  { return v | ( 1); } getV1(){} };
10387
10388 template<deUint32 R, deUint32 N>
10389 inline static deUint32 getOffset(deUint32 x, deUint32 y, deUint32 n)
10390 {
10391         return N * ((R * y) + x) + n;
10392 }
10393
10394 template<deUint32 R, deUint32 N, class X0, class X1, class Y0, class Y1>
10395 struct getFDelta
10396 {
10397         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10398         {
10399                 DE_STATIC_ASSERT(R%2 == 0);
10400                 DE_ASSERT(flavor == 0);
10401                 DE_UNREF(flavor);
10402
10403                 const X0                        x0;
10404                 const X1                        x1;
10405                 const Y0                        y0;
10406                 const Y1                        y1;
10407                 const deFloat16         v0      = data[getOffset<R, N>(x0(x), y0(y), n)];
10408                 const deFloat16         v1      = data[getOffset<R, N>(x1(x), y1(y), n)];
10409                 const tcu::Float16      f0      = tcu::Float16(v0);
10410                 const tcu::Float16      f1      = tcu::Float16(v1);
10411                 const float                     d0      = f0.asFloat();
10412                 const float                     d1      = f1.asFloat();
10413                 const float                     d       = d1 - d0;
10414
10415                 return d;
10416         }
10417
10418         getFDelta(){}
10419 };
10420
10421 template<deUint32 F, class Class0, class Class1>
10422 struct getFOneOf
10423 {
10424         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10425         {
10426                 DE_ASSERT(flavor < F);
10427
10428                 if (flavor == 0)
10429                 {
10430                         Class0 c;
10431
10432                         return c(data, x, y, n, flavor);
10433                 }
10434                 else
10435                 {
10436                         Class1 c;
10437
10438                         return c(data, x, y, n, flavor - 1);
10439                 }
10440         }
10441
10442         getFOneOf(){}
10443 };
10444
10445 template<class FineX0, class FineX1, class FineY0, class FineY1>
10446 struct calcWidthOf4
10447 {
10448         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10449         {
10450                 DE_ASSERT(flavor < 4);
10451
10452                 const deUint32                                          flavorX = (flavor & 1) == 0 ? 0 : 1;
10453                 const deUint32                                          flavorY = (flavor & 2) == 0 ? 0 : 1;
10454                 const getFOneOf<2, FineX0, FineX1>      cx;
10455                 const getFOneOf<2, FineY0, FineY1>      cy;
10456                 float                                                           v               = 0;
10457
10458                 v += fabsf(cx(data, x, y, n, flavorX));
10459                 v += fabsf(cy(data, x, y, n, flavorY));
10460
10461                 return v;
10462         }
10463
10464         calcWidthOf4(){}
10465 };
10466
10467 template<deUint32 R, deUint32 N, class Derivative>
10468 bool compareDerivativeWithFlavor (const deFloat16* inputAsFP16, const deFloat16* outputAsFP16, deUint32 flavor, std::string& error)
10469 {
10470         const deUint32          numDataPointsByAxis     = R;
10471         const Derivative        derivativeFunc;
10472
10473         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10474         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10475         for (deUint32 n = 0; n < N; ++n)
10476         {
10477                 const float             expectedFloat   = derivativeFunc(inputAsFP16, x, y, n, flavor);
10478                 deFloat16               expected                = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_NEAREST_EVEN);
10479                 const deFloat16 output                  = outputAsFP16[getOffset<R, N>(x, y, n)];
10480
10481                 bool                    reportError             = !compare16BitFloat(expected, output, error);
10482
10483                 if (reportError)
10484                 {
10485                         expected        = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_ZERO);
10486                         reportError     = !compare16BitFloat(expected, output, error);
10487                 }
10488
10489                 if (reportError)
10490                 {
10491                         error = "subcase at " + de::toString(x) + "," + de::toString(y) + "," + de::toString(n) + ": " + error;
10492
10493                         return false;
10494                 }
10495         }
10496
10497         return true;
10498 }
10499
10500 template<deUint32 R, deUint32 N, deUint32 FLAVOUR_COUNT, class Derivative>
10501 bool compareDerivative (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10502 {
10503         if (inputs.size() != 1 || outputAllocs.size() != 1)
10504                 return false;
10505
10506         deUint32                        successfulRuns                  = FLAVOUR_COUNT;
10507         std::string                     results[FLAVOUR_COUNT];
10508         vector<deUint8>         inputBytes;
10509
10510         inputs[0].getBytes(inputBytes);
10511
10512         const deFloat16*        inputAsFP16             = reinterpret_cast<deFloat16* const>(&inputBytes.front());
10513         const deFloat16*        outputAsFP16    = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
10514
10515         DE_ASSERT(inputBytes.size() ==  R * R * N * sizeof(deFloat16));
10516
10517         for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; ++flavor)
10518                 if (compareDerivativeWithFlavor<R, N, Derivative> (inputAsFP16, outputAsFP16, flavor, results[flavor]))
10519                 {
10520                         break;
10521                 }
10522                 else
10523                 {
10524                         successfulRuns--;
10525                 }
10526
10527         if (successfulRuns == 0)
10528                 for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; flavor++)
10529                         log << TestLog::Message << "At flavor #" << flavor << " " << results[flavor] << TestLog::EndMessage;
10530
10531         return successfulRuns > 0;
10532 }
10533
10534 template<deUint32 R, deUint32 N>
10535 tcu::TestCaseGroup* createDerivativeTests (tcu::TestContext& testCtx)
10536 {
10537         typedef getFDelta<R, N, getV0, getV1, getV_, getV_> getFDxFine;
10538         typedef getFDelta<R, N, getV_, getV_, getV0, getV1> getFDyFine;
10539
10540         typedef getFDelta<R, N, getV0, getV1, getV0, getV0> getFdxCoarse0;
10541         typedef getFDelta<R, N, getV0, getV1, getV1, getV1> getFdxCoarse1;
10542         typedef getFDelta<R, N, getV0, getV0, getV0, getV1> getFdyCoarse0;
10543         typedef getFDelta<R, N, getV1, getV1, getV0, getV1> getFdyCoarse1;
10544         typedef getFOneOf<2, getFdxCoarse0, getFdxCoarse1> getFDxCoarse;
10545         typedef getFOneOf<2, getFdyCoarse0, getFdyCoarse1> getFDyCoarse;
10546
10547         typedef calcWidthOf4<getFDxFine, getFDxFine, getFDyFine, getFDyFine> getFWidthFine;
10548         typedef calcWidthOf4<getFdxCoarse0, getFdxCoarse1, getFdyCoarse0, getFdyCoarse1> getFWidthCoarse;
10549
10550         typedef getFOneOf<3, getFDxFine, getFDxCoarse> getFDx;
10551         typedef getFOneOf<3, getFDyFine, getFDyCoarse> getFDy;
10552         typedef getFOneOf<5, getFWidthFine, getFWidthCoarse> getFWidth;
10553
10554         const std::string                                       testGroupName           (std::string("derivative_") + de::toString(N));
10555         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Derivative instruction tests"));
10556
10557         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10558         const deUint32                                          numDataPointsByAxis     = R;
10559         const deUint32                                          numDataPoints           = N * numDataPointsByAxis * numDataPointsByAxis;
10560         vector<deFloat16>                                       float16InputX;
10561         vector<deFloat16>                                       float16InputY;
10562         vector<deFloat16>                                       float16InputW;
10563         vector<deFloat16>                                       float16OutputDummy      (numDataPoints, 0);
10564         RGBA                                                            defaultColors[4];
10565
10566         getDefaultColors(defaultColors);
10567
10568         float16InputX.reserve(numDataPoints);
10569         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10570         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10571         for (deUint32 n = 0; n < N; ++n)
10572         {
10573                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(x * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10574
10575                 if (y%2 == 0)
10576                         float16InputX.push_back(tcu::Float16(sin(arg)).bits());
10577                 else
10578                         float16InputX.push_back(tcu::Float16(cos(arg)).bits());
10579         }
10580
10581         float16InputY.reserve(numDataPoints);
10582         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10583         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10584         for (deUint32 n = 0; n < N; ++n)
10585         {
10586                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(y * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10587
10588                 if (x%2 == 0)
10589                         float16InputY.push_back(tcu::Float16(sin(arg)).bits());
10590                 else
10591                         float16InputY.push_back(tcu::Float16(cos(arg)).bits());
10592         }
10593
10594         const deFloat16 testNumbers[]   =
10595         {
10596                 tcu::Float16( 2.0  ).bits(),
10597                 tcu::Float16( 4.0  ).bits(),
10598                 tcu::Float16( 8.0  ).bits(),
10599                 tcu::Float16( 16.0 ).bits(),
10600                 tcu::Float16( 32.0 ).bits(),
10601                 tcu::Float16( 64.0 ).bits(),
10602                 tcu::Float16( 128.0).bits(),
10603                 tcu::Float16( 256.0).bits(),
10604                 tcu::Float16( 512.0).bits(),
10605                 tcu::Float16(-2.0  ).bits(),
10606                 tcu::Float16(-4.0  ).bits(),
10607                 tcu::Float16(-8.0  ).bits(),
10608                 tcu::Float16(-16.0 ).bits(),
10609                 tcu::Float16(-32.0 ).bits(),
10610                 tcu::Float16(-64.0 ).bits(),
10611                 tcu::Float16(-128.0).bits(),
10612                 tcu::Float16(-256.0).bits(),
10613                 tcu::Float16(-512.0).bits(),
10614         };
10615
10616         float16InputW.reserve(numDataPoints);
10617         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10618         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10619         for (deUint32 n = 0; n < N; ++n)
10620                 float16InputW.push_back(testNumbers[rnd.getInt(0, DE_LENGTH_OF_ARRAY(testNumbers) - 1)]);
10621
10622         struct TestOp
10623         {
10624                 const char*                     opCode;
10625                 vector<deFloat16>&      inputData;
10626                 VerifyIOFunc            verifyFunc;
10627         };
10628
10629         const TestOp    testOps[]       =
10630         {
10631                 { "OpDPdxFine"          ,       float16InputX   ,       compareDerivative<R, N, 1, getFDxFine           >       },
10632                 { "OpDPdyFine"          ,       float16InputY   ,       compareDerivative<R, N, 1, getFDyFine           >       },
10633                 { "OpFwidthFine"        ,       float16InputW   ,       compareDerivative<R, N, 1, getFWidthFine        >       },
10634                 { "OpDPdxCoarse"        ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10635                 { "OpDPdyCoarse"        ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10636                 { "OpFwidthCoarse"      ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10637                 { "OpDPdx"                      ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10638                 { "OpDPdy"                      ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10639                 { "OpFwidth"            ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10640         };
10641
10642         struct TestType
10643         {
10644                 const deUint32  typeComponents;
10645                 const char*             typeName;
10646                 const char*             typeDecls;
10647         };
10648
10649         const TestType  testTypes[]     =
10650         {
10651                 {
10652                         1,
10653                         "f16",
10654                         ""
10655                 },
10656                 {
10657                         2,
10658                         "v2f16",
10659                         "      %v2f16 = OpTypeVector %f16 2\n"
10660                 },
10661                 {
10662                         4,
10663                         "v4f16",
10664                         "      %v4f16 = OpTypeVector %f16 4\n"
10665                 },
10666         };
10667
10668         const deUint32  testTypeNdx     = (N == 1) ? 0
10669                                                                 : (N == 2) ? 1
10670                                                                 : (N == 4) ? 2
10671                                                                 : DE_LENGTH_OF_ARRAY(testTypes);
10672         const TestType& testType        =       testTypes[testTypeNdx];
10673
10674         DE_ASSERT(testTypeNdx < DE_LENGTH_OF_ARRAY(testTypes));
10675         DE_ASSERT(testType.typeComponents == N);
10676
10677         const StringTemplate preMain
10678         (
10679                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10680                 " %c_u32_xw = OpConstant %u32 ${items_by_x}\n"
10681                 "      %f16 = OpTypeFloat 16\n"
10682                 "${type_decls}"
10683                 " %up_${tt} = OpTypePointer Uniform %${tt}\n"
10684                 " %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10685                 "   %SSBO16 = OpTypeStruct %ra_${tt}\n"
10686                 "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10687                 " %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10688                 " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10689         );
10690
10691         const StringTemplate decoration
10692         (
10693                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10694                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10695                 "OpDecorate %SSBO16 BufferBlock\n"
10696                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10697                 "OpDecorate %ssbo_src Binding 0\n"
10698                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10699                 "OpDecorate %ssbo_dst Binding 1\n"
10700         );
10701
10702         const StringTemplate testFun
10703         (
10704                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10705                 "    %param = OpFunctionParameter %v4f32\n"
10706                 "    %entry = OpLabel\n"
10707
10708                 "  %loc_x_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_0\n"
10709                 "  %loc_y_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_1\n"
10710                 "      %x_c = OpLoad %f32 %loc_x_c\n"
10711                 "      %y_c = OpLoad %f32 %loc_y_c\n"
10712                 "    %x_idx = OpConvertFToU %u32 %x_c\n"
10713                 "    %y_idx = OpConvertFToU %u32 %y_c\n"
10714                 "    %ndx_y = OpIMul %u32 %y_idx %c_u32_xw\n"
10715                 "      %ndx = OpIAdd %u32 %ndx_y %x_idx\n"
10716
10717                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10718                 "  %val_src = OpLoad %${tt} %src\n"
10719                 "  %val_dst = ${op_code} %${tt} %val_src\n"
10720                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10721                 "             OpStore %dst %val_dst\n"
10722                 "             OpBranch %merge\n"
10723
10724                 "    %merge = OpLabel\n"
10725                 "             OpReturnValue %param\n"
10726
10727                 "             OpFunctionEnd\n"
10728         );
10729
10730         for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10731         {
10732                 const TestOp&           testOp                  = testOps[testOpsIdx];
10733                 const string            testName                = de::toLower(string(testOp.opCode));
10734                 const size_t            typeStride              = N * sizeof(deFloat16);
10735                 GraphicsResources       specResource;
10736                 map<string, string>     specs;
10737                 VulkanFeatures          features;
10738                 vector<string>          extensions;
10739                 map<string, string>     fragments;
10740                 SpecConstants           noSpecConstants;
10741                 PushConstants           noPushConstants;
10742                 GraphicsInterfaces      noInterfaces;
10743
10744                 specs["op_code"]                        = testOp.opCode;
10745                 specs["num_data_points"]        = de::toString(testOp.inputData.size() / N);
10746                 specs["items_by_x"]                     = de::toString(numDataPointsByAxis);
10747                 specs["tt"]                                     = testType.typeName;
10748                 specs["tt_stride"]                      = de::toString(typeStride);
10749                 specs["type_decls"]                     = testType.typeDecls;
10750
10751                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10752                 fragments["capability"]         = "OpCapability DerivativeControl\nOpCapability StorageUniformBufferBlock16\n";
10753                 fragments["decoration"]         = decoration.specialize(specs);
10754                 fragments["pre_main"]           = preMain.specialize(specs);
10755                 fragments["testfun"]            = testFun.specialize(specs);
10756
10757                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(testOp.inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10758                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10759                 specResource.verifyIO = testOp.verifyFunc;
10760
10761                 extensions.push_back("VK_KHR_16bit_storage");
10762                 extensions.push_back("VK_KHR_shader_float16_int8");
10763
10764                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10765                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10766
10767                 createTestForStage(VK_SHADER_STAGE_FRAGMENT_BIT, testName.c_str(), defaultColors, defaultColors, fragments, noSpecConstants,
10768                                                         noPushConstants, specResource, noInterfaces, extensions, features, testGroup.get(), QP_TEST_RESULT_FAIL, string(), true);
10769         }
10770
10771         return testGroup.release();
10772 }
10773
10774 bool compareFP16VectorExtractFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10775 {
10776         if (inputs.size() != 2 || outputAllocs.size() != 1)
10777                 return false;
10778
10779         vector<deUint8> input1Bytes;
10780         vector<deUint8> input2Bytes;
10781
10782         inputs[0].getBytes(input1Bytes);
10783         inputs[1].getBytes(input2Bytes);
10784
10785         DE_ASSERT(input1Bytes.size() > 0);
10786         DE_ASSERT(input2Bytes.size() > 0);
10787         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
10788
10789         const size_t                    iterations              = input2Bytes.size() / sizeof(deUint32);
10790         const size_t                    components              = input1Bytes.size() / (sizeof(deFloat16) * iterations);
10791         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
10792         const deUint32* const   inputIndices    = (const deUint32*)&input2Bytes[0];
10793         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
10794         std::string                             error;
10795
10796         DE_ASSERT(components == 2 || components == 4);
10797         DE_ASSERT(input1Bytes.size() == iterations * components * sizeof(deFloat16));
10798
10799         for (size_t idx = 0; idx < iterations; ++idx)
10800         {
10801                 const deUint32  componentNdx    = inputIndices[idx];
10802
10803                 DE_ASSERT(componentNdx < components);
10804
10805                 const deFloat16 expected                = input1AsFP16[components * idx + componentNdx];
10806
10807                 if (!compare16BitFloat(expected, outputAsFP16[idx], error))
10808                 {
10809                         log << TestLog::Message << "At " << idx << error << TestLog::EndMessage;
10810
10811                         return false;
10812                 }
10813         }
10814
10815         return true;
10816 }
10817
10818 template<class SpecResource>
10819 tcu::TestCaseGroup* createFloat16VectorExtractSet (tcu::TestContext& testCtx)
10820 {
10821         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorextractdynamic", "OpVectorExtractDynamic tests"));
10822
10823         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10824         const deUint32                                          numDataPoints           = 256;
10825         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10826         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10827
10828         struct TestType
10829         {
10830                 const deUint32  typeComponents;
10831                 const size_t    typeStride;
10832                 const char*             typeName;
10833                 const char*             typeDecls;
10834         };
10835
10836         const TestType  testTypes[]     =
10837         {
10838                 {
10839                         2,
10840                         2 * sizeof(deFloat16),
10841                         "v2f16",
10842                         "      %v2f16 = OpTypeVector %f16 2\n"
10843                 },
10844                 {
10845                         3,
10846                         4 * sizeof(deFloat16),
10847                         "v3f16",
10848                         "      %v3f16 = OpTypeVector %f16 3\n"
10849                 },
10850                 {
10851                         4,
10852                         4 * sizeof(deFloat16),
10853                         "v4f16",
10854                         "      %v4f16 = OpTypeVector %f16 4\n"
10855                 },
10856         };
10857
10858         const StringTemplate preMain
10859         (
10860                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10861                 "        %f16 = OpTypeFloat 16\n"
10862
10863                 "${type_decl}"
10864
10865                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10866                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10867                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
10868                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
10869
10870                 "     %up_u32 = OpTypePointer Uniform %u32\n"
10871                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
10872                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
10873                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
10874
10875                 "     %up_f16 = OpTypePointer Uniform %f16\n"
10876                 "     %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
10877                 "   %SSBO_DST = OpTypeStruct %ra_f16\n"
10878                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
10879
10880                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
10881                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
10882                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
10883         );
10884
10885         const StringTemplate decoration
10886         (
10887                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10888                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
10889                 "OpDecorate %SSBO_SRC BufferBlock\n"
10890                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10891                 "OpDecorate %ssbo_src Binding 0\n"
10892
10893                 "OpDecorate %ra_u32 ArrayStride 4\n"
10894                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
10895                 "OpDecorate %SSBO_IDX BufferBlock\n"
10896                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
10897                 "OpDecorate %ssbo_idx Binding 1\n"
10898
10899                 "OpDecorate %ra_f16 ArrayStride 2\n"
10900                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
10901                 "OpDecorate %SSBO_DST BufferBlock\n"
10902                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10903                 "OpDecorate %ssbo_dst Binding 2\n"
10904         );
10905
10906         const StringTemplate testFun
10907         (
10908                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10909                 "    %param = OpFunctionParameter %v4f32\n"
10910                 "    %entry = OpLabel\n"
10911
10912                 "        %i = OpVariable %fp_i32 Function\n"
10913                 "             OpStore %i %c_i32_0\n"
10914
10915                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
10916                 "             OpSelectionMerge %end_if None\n"
10917                 "             OpBranchConditional %will_run %run_test %end_if\n"
10918
10919                 " %run_test = OpLabel\n"
10920                 "             OpBranch %loop\n"
10921
10922                 "     %loop = OpLabel\n"
10923                 "    %i_cmp = OpLoad %i32 %i\n"
10924                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10925                 "             OpLoopMerge %merge %next None\n"
10926                 "             OpBranchConditional %lt %write %merge\n"
10927
10928                 "    %write = OpLabel\n"
10929                 "      %ndx = OpLoad %i32 %i\n"
10930
10931                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10932                 "  %val_src = OpLoad %${tt} %src\n"
10933
10934                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
10935                 "  %val_idx = OpLoad %u32 %src_idx\n"
10936
10937                 "  %val_dst = OpVectorExtractDynamic %f16 %val_src %val_idx\n"
10938                 "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10939
10940                 "             OpStore %dst %val_dst\n"
10941                 "             OpBranch %next\n"
10942
10943                 "     %next = OpLabel\n"
10944                 "    %i_cur = OpLoad %i32 %i\n"
10945                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10946                 "             OpStore %i %i_new\n"
10947                 "             OpBranch %loop\n"
10948
10949                 "    %merge = OpLabel\n"
10950                 "             OpBranch %end_if\n"
10951                 "   %end_if = OpLabel\n"
10952                 "             OpReturnValue %param\n"
10953
10954                 "             OpFunctionEnd\n"
10955         );
10956
10957         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10958         {
10959                 const TestType&         testType                = testTypes[testTypeIdx];
10960                 const string            testName                = testType.typeName;
10961                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
10962                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10963                 SpecResource            specResource;
10964                 map<string, string>     specs;
10965                 VulkanFeatures          features;
10966                 vector<deUint32>        inputDataNdx;
10967                 map<string, string>     fragments;
10968                 vector<string>          extensions;
10969
10970                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
10971                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
10972
10973                 specs["num_data_points"]        = de::toString(iterations);
10974                 specs["tt"]                                     = testType.typeName;
10975                 specs["tt_stride"]                      = de::toString(testType.typeStride);
10976                 specs["type_decl"]                      = testType.typeDecls;
10977
10978                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10979                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
10980                 fragments["decoration"]         = decoration.specialize(specs);
10981                 fragments["pre_main"]           = preMain.specialize(specs);
10982                 fragments["testfun"]            = testFun.specialize(specs);
10983
10984                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10985                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10986                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10987                 specResource.verifyIO = compareFP16VectorExtractFunc;
10988
10989                 extensions.push_back("VK_KHR_16bit_storage");
10990                 extensions.push_back("VK_KHR_shader_float16_int8");
10991
10992                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10993                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10994
10995                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10996         }
10997
10998         return testGroup.release();
10999 }
11000
11001 template<deUint32 COMPONENTS_COUNT, deUint32 REPLACEMENT>
11002 bool compareFP16VectorInsertFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11003 {
11004         if (inputs.size() != 2 || outputAllocs.size() != 1)
11005                 return false;
11006
11007         vector<deUint8> input1Bytes;
11008         vector<deUint8> input2Bytes;
11009
11010         inputs[0].getBytes(input1Bytes);
11011         inputs[1].getBytes(input2Bytes);
11012
11013         DE_ASSERT(input1Bytes.size() > 0);
11014         DE_ASSERT(input2Bytes.size() > 0);
11015         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
11016
11017         const size_t                    iterations                      = input2Bytes.size() / sizeof(deUint32);
11018         const size_t                    componentsStride        = input1Bytes.size() / (sizeof(deFloat16) * iterations);
11019         const deFloat16* const  input1AsFP16            = (const deFloat16*)&input1Bytes[0];
11020         const deUint32* const   inputIndices            = (const deUint32*)&input2Bytes[0];
11021         const deFloat16* const  outputAsFP16            = (const deFloat16*)outputAllocs[0]->getHostPtr();
11022         const deFloat16                 magic                           = tcu::Float16(float(REPLACEMENT)).bits();
11023         std::string                             error;
11024
11025         DE_ASSERT(componentsStride == 2 || componentsStride == 4);
11026         DE_ASSERT(input1Bytes.size() == iterations * componentsStride * sizeof(deFloat16));
11027
11028         for (size_t idx = 0; idx < iterations; ++idx)
11029         {
11030                 const deFloat16*        inputVec                = &input1AsFP16[componentsStride * idx];
11031                 const deFloat16*        outputVec               = &outputAsFP16[componentsStride * idx];
11032                 const deUint32          replacedCompNdx = inputIndices[idx];
11033
11034                 DE_ASSERT(replacedCompNdx < COMPONENTS_COUNT);
11035
11036                 for (size_t compNdx = 0; compNdx < COMPONENTS_COUNT; ++compNdx)
11037                 {
11038                         const deFloat16 expected        = (compNdx == replacedCompNdx) ? magic : inputVec[compNdx];
11039
11040                         if (!compare16BitFloat(expected, outputVec[compNdx], error))
11041                         {
11042                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11043
11044                                 return false;
11045                         }
11046                 }
11047         }
11048
11049         return true;
11050 }
11051
11052 template<class SpecResource>
11053 tcu::TestCaseGroup* createFloat16VectorInsertSet (tcu::TestContext& testCtx)
11054 {
11055         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorinsertdynamic", "OpVectorInsertDynamic tests"));
11056
11057         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
11058         const deUint32                                          replacement                     = 42;
11059         const deUint32                                          numDataPoints           = 256;
11060         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
11061         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
11062
11063         struct TestType
11064         {
11065                 const deUint32  typeComponents;
11066                 const size_t    typeStride;
11067                 const char*             typeName;
11068                 const char*             typeDecls;
11069                 VerifyIOFunc    verifyIOFunc;
11070         };
11071
11072         const TestType  testTypes[]     =
11073         {
11074                 {
11075                         2,
11076                         2 * sizeof(deFloat16),
11077                         "v2f16",
11078                         "      %v2f16 = OpTypeVector %f16 2\n",
11079                         compareFP16VectorInsertFunc<2, replacement>
11080                 },
11081                 {
11082                         3,
11083                         4 * sizeof(deFloat16),
11084                         "v3f16",
11085                         "      %v3f16 = OpTypeVector %f16 3\n",
11086                         compareFP16VectorInsertFunc<3, replacement>
11087                 },
11088                 {
11089                         4,
11090                         4 * sizeof(deFloat16),
11091                         "v4f16",
11092                         "      %v4f16 = OpTypeVector %f16 4\n",
11093                         compareFP16VectorInsertFunc<4, replacement>
11094                 },
11095         };
11096
11097         const StringTemplate preMain
11098         (
11099                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11100                 "        %f16 = OpTypeFloat 16\n"
11101                 "  %c_f16_ins = OpConstant %f16 ${replacement}\n"
11102
11103                 "${type_decl}"
11104
11105                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
11106                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
11107                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
11108                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
11109
11110                 "     %up_u32 = OpTypePointer Uniform %u32\n"
11111                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
11112                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
11113                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
11114
11115                 "   %SSBO_DST = OpTypeStruct %ra_${tt}\n"
11116                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
11117
11118                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
11119                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
11120                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
11121         );
11122
11123         const StringTemplate decoration
11124         (
11125                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
11126                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
11127                 "OpDecorate %SSBO_SRC BufferBlock\n"
11128                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11129                 "OpDecorate %ssbo_src Binding 0\n"
11130
11131                 "OpDecorate %ra_u32 ArrayStride 4\n"
11132                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
11133                 "OpDecorate %SSBO_IDX BufferBlock\n"
11134                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
11135                 "OpDecorate %ssbo_idx Binding 1\n"
11136
11137                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
11138                 "OpDecorate %SSBO_DST BufferBlock\n"
11139                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11140                 "OpDecorate %ssbo_dst Binding 2\n"
11141         );
11142
11143         const StringTemplate testFun
11144         (
11145                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11146                 "    %param = OpFunctionParameter %v4f32\n"
11147                 "    %entry = OpLabel\n"
11148
11149                 "        %i = OpVariable %fp_i32 Function\n"
11150                 "             OpStore %i %c_i32_0\n"
11151
11152                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11153                 "             OpSelectionMerge %end_if None\n"
11154                 "             OpBranchConditional %will_run %run_test %end_if\n"
11155
11156                 " %run_test = OpLabel\n"
11157                 "             OpBranch %loop\n"
11158
11159                 "     %loop = OpLabel\n"
11160                 "    %i_cmp = OpLoad %i32 %i\n"
11161                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11162                 "             OpLoopMerge %merge %next None\n"
11163                 "             OpBranchConditional %lt %write %merge\n"
11164
11165                 "    %write = OpLabel\n"
11166                 "      %ndx = OpLoad %i32 %i\n"
11167
11168                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
11169                 "  %val_src = OpLoad %${tt} %src\n"
11170
11171                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
11172                 "  %val_idx = OpLoad %u32 %src_idx\n"
11173
11174                 "  %val_dst = OpVectorInsertDynamic %${tt} %val_src %c_f16_ins %val_idx\n"
11175                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
11176
11177                 "             OpStore %dst %val_dst\n"
11178                 "             OpBranch %next\n"
11179
11180                 "     %next = OpLabel\n"
11181                 "    %i_cur = OpLoad %i32 %i\n"
11182                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11183                 "             OpStore %i %i_new\n"
11184                 "             OpBranch %loop\n"
11185
11186                 "    %merge = OpLabel\n"
11187                 "             OpBranch %end_if\n"
11188                 "   %end_if = OpLabel\n"
11189                 "             OpReturnValue %param\n"
11190
11191                 "             OpFunctionEnd\n"
11192         );
11193
11194         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
11195         {
11196                 const TestType&         testType                = testTypes[testTypeIdx];
11197                 const string            testName                = testType.typeName;
11198                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
11199                 const size_t            iterations              = float16InputData.size() / itemsPerType;
11200                 SpecResource            specResource;
11201                 map<string, string>     specs;
11202                 VulkanFeatures          features;
11203                 vector<deUint32>        inputDataNdx;
11204                 map<string, string>     fragments;
11205                 vector<string>          extensions;
11206
11207                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
11208                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
11209
11210                 specs["num_data_points"]        = de::toString(iterations);
11211                 specs["tt"]                                     = testType.typeName;
11212                 specs["tt_stride"]                      = de::toString(testType.typeStride);
11213                 specs["type_decl"]                      = testType.typeDecls;
11214                 specs["replacement"]            = de::toString(replacement);
11215
11216                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11217                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11218                 fragments["decoration"]         = decoration.specialize(specs);
11219                 fragments["pre_main"]           = preMain.specialize(specs);
11220                 fragments["testfun"]            = testFun.specialize(specs);
11221
11222                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11223                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11224                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11225                 specResource.verifyIO = testType.verifyIOFunc;
11226
11227                 extensions.push_back("VK_KHR_16bit_storage");
11228                 extensions.push_back("VK_KHR_shader_float16_int8");
11229
11230                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11231                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11232
11233                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11234         }
11235
11236         return testGroup.release();
11237 }
11238
11239 inline deFloat16 getShuffledComponent (const size_t iteration, const size_t componentNdx, const deFloat16* input1Vec, const deFloat16* input2Vec, size_t vec1Len, size_t vec2Len, bool& validate)
11240 {
11241         const size_t    compNdxCount    = (vec1Len + vec2Len + 1);
11242         const size_t    compNdxLimited  = iteration % (compNdxCount * compNdxCount);
11243         size_t                  comp;
11244
11245         switch (componentNdx)
11246         {
11247                 case 0: comp = compNdxLimited / compNdxCount; break;
11248                 case 1: comp = compNdxLimited % compNdxCount; break;
11249                 case 2: comp = 0; break;
11250                 case 3: comp = 1; break;
11251                 default: TCU_THROW(InternalError, "Impossible");
11252         }
11253
11254         if (comp >= vec1Len + vec2Len)
11255         {
11256                 validate = false;
11257                 return 0;
11258         }
11259         else
11260         {
11261                 validate = true;
11262                 return (comp < vec1Len) ? input1Vec[comp] : input2Vec[comp - vec1Len];
11263         }
11264 }
11265
11266 template<deUint32 DST_COMPONENTS_COUNT, deUint32 SRC0_COMPONENTS_COUNT, deUint32 SRC1_COMPONENTS_COUNT>
11267 bool compareFP16VectorShuffleFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11268 {
11269         DE_STATIC_ASSERT(DST_COMPONENTS_COUNT == 2 || DST_COMPONENTS_COUNT == 3 || DST_COMPONENTS_COUNT == 4);
11270         DE_STATIC_ASSERT(SRC0_COMPONENTS_COUNT == 2 || SRC0_COMPONENTS_COUNT == 3 || SRC0_COMPONENTS_COUNT == 4);
11271         DE_STATIC_ASSERT(SRC1_COMPONENTS_COUNT == 2 || SRC1_COMPONENTS_COUNT == 3 || SRC1_COMPONENTS_COUNT == 4);
11272
11273         if (inputs.size() != 2 || outputAllocs.size() != 1)
11274                 return false;
11275
11276         vector<deUint8> input1Bytes;
11277         vector<deUint8> input2Bytes;
11278
11279         inputs[0].getBytes(input1Bytes);
11280         inputs[1].getBytes(input2Bytes);
11281
11282         DE_ASSERT(input1Bytes.size() > 0);
11283         DE_ASSERT(input2Bytes.size() > 0);
11284         DE_ASSERT(input2Bytes.size() % sizeof(deFloat16) == 0);
11285
11286         const size_t                    componentsStrideDst             = (DST_COMPONENTS_COUNT == 3) ? 4 : DST_COMPONENTS_COUNT;
11287         const size_t                    componentsStrideSrc0    = (SRC0_COMPONENTS_COUNT == 3) ? 4 : SRC0_COMPONENTS_COUNT;
11288         const size_t                    componentsStrideSrc1    = (SRC1_COMPONENTS_COUNT == 3) ? 4 : SRC1_COMPONENTS_COUNT;
11289         const size_t                    iterations                              = input1Bytes.size() / (componentsStrideSrc0 * sizeof(deFloat16));
11290         const deFloat16* const  input1AsFP16                    = (const deFloat16*)&input1Bytes[0];
11291         const deFloat16* const  input2AsFP16                    = (const deFloat16*)&input2Bytes[0];
11292         const deFloat16* const  outputAsFP16                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11293         std::string                             error;
11294
11295         DE_ASSERT(input1Bytes.size() == iterations * componentsStrideSrc0 * sizeof(deFloat16));
11296         DE_ASSERT(input2Bytes.size() == iterations * componentsStrideSrc1 * sizeof(deFloat16));
11297
11298         for (size_t idx = 0; idx < iterations; ++idx)
11299         {
11300                 const deFloat16*        input1Vec       = &input1AsFP16[componentsStrideSrc0 * idx];
11301                 const deFloat16*        input2Vec       = &input2AsFP16[componentsStrideSrc1 * idx];
11302                 const deFloat16*        outputVec       = &outputAsFP16[componentsStrideDst * idx];
11303
11304                 for (size_t compNdx = 0; compNdx < DST_COMPONENTS_COUNT; ++compNdx)
11305                 {
11306                         bool            validate        = true;
11307                         deFloat16       expected        = getShuffledComponent(idx, compNdx, input1Vec, input2Vec, SRC0_COMPONENTS_COUNT, SRC1_COMPONENTS_COUNT, validate);
11308
11309                         if (validate && !compare16BitFloat(expected, outputVec[compNdx], error))
11310                         {
11311                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11312
11313                                 return false;
11314                         }
11315                 }
11316         }
11317
11318         return true;
11319 }
11320
11321 VerifyIOFunc getFloat16VectorShuffleVerifyIOFunc (deUint32 dstComponentsCount, deUint32 src0ComponentsCount, deUint32 src1ComponentsCount)
11322 {
11323         DE_ASSERT(dstComponentsCount <= 4);
11324         DE_ASSERT(src0ComponentsCount <= 4);
11325         DE_ASSERT(src1ComponentsCount <= 4);
11326         deUint32 funcCode = 100 * dstComponentsCount + 10 * src0ComponentsCount + src1ComponentsCount;
11327
11328         switch (funcCode)
11329         {
11330                 case 222:return compareFP16VectorShuffleFunc<2, 2, 2>;
11331                 case 223:return compareFP16VectorShuffleFunc<2, 2, 3>;
11332                 case 224:return compareFP16VectorShuffleFunc<2, 2, 4>;
11333                 case 232:return compareFP16VectorShuffleFunc<2, 3, 2>;
11334                 case 233:return compareFP16VectorShuffleFunc<2, 3, 3>;
11335                 case 234:return compareFP16VectorShuffleFunc<2, 3, 4>;
11336                 case 242:return compareFP16VectorShuffleFunc<2, 4, 2>;
11337                 case 243:return compareFP16VectorShuffleFunc<2, 4, 3>;
11338                 case 244:return compareFP16VectorShuffleFunc<2, 4, 4>;
11339                 case 322:return compareFP16VectorShuffleFunc<3, 2, 2>;
11340                 case 323:return compareFP16VectorShuffleFunc<3, 2, 3>;
11341                 case 324:return compareFP16VectorShuffleFunc<3, 2, 4>;
11342                 case 332:return compareFP16VectorShuffleFunc<3, 3, 2>;
11343                 case 333:return compareFP16VectorShuffleFunc<3, 3, 3>;
11344                 case 334:return compareFP16VectorShuffleFunc<3, 3, 4>;
11345                 case 342:return compareFP16VectorShuffleFunc<3, 4, 2>;
11346                 case 343:return compareFP16VectorShuffleFunc<3, 4, 3>;
11347                 case 344:return compareFP16VectorShuffleFunc<3, 4, 4>;
11348                 case 422:return compareFP16VectorShuffleFunc<4, 2, 2>;
11349                 case 423:return compareFP16VectorShuffleFunc<4, 2, 3>;
11350                 case 424:return compareFP16VectorShuffleFunc<4, 2, 4>;
11351                 case 432:return compareFP16VectorShuffleFunc<4, 3, 2>;
11352                 case 433:return compareFP16VectorShuffleFunc<4, 3, 3>;
11353                 case 434:return compareFP16VectorShuffleFunc<4, 3, 4>;
11354                 case 442:return compareFP16VectorShuffleFunc<4, 4, 2>;
11355                 case 443:return compareFP16VectorShuffleFunc<4, 4, 3>;
11356                 case 444:return compareFP16VectorShuffleFunc<4, 4, 4>;
11357                 default: TCU_THROW(InternalError, "Invalid number of components specified.");
11358         }
11359 }
11360
11361 template<class SpecResource>
11362 tcu::TestCaseGroup* createFloat16VectorShuffleSet (tcu::TestContext& testCtx)
11363 {
11364         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorshuffle", "OpVectorShuffle tests"));
11365         const int                                                       testSpecificSeed        = deStringHash(testGroup->getName());
11366         const int                                                       seed                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
11367         de::Random                                                      rnd                                     (seed);
11368         const deUint32                                          numDataPoints           = 128;
11369         map<string, string>                                     fragments;
11370
11371         struct TestType
11372         {
11373                 const deUint32  typeComponents;
11374                 const char*             typeName;
11375         };
11376
11377         const TestType  testTypes[]     =
11378         {
11379                 {
11380                         2,
11381                         "v2f16",
11382                 },
11383                 {
11384                         3,
11385                         "v3f16",
11386                 },
11387                 {
11388                         4,
11389                         "v4f16",
11390                 },
11391         };
11392
11393         const StringTemplate preMain
11394         (
11395                 "    %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11396                 "     %c_i32_cc = OpConstant %i32 ${case_count}\n"
11397                 "          %f16 = OpTypeFloat 16\n"
11398                 "        %v2f16 = OpTypeVector %f16 2\n"
11399                 "        %v3f16 = OpTypeVector %f16 3\n"
11400                 "        %v4f16 = OpTypeVector %f16 4\n"
11401
11402                 "     %up_v2f16 = OpTypePointer Uniform %v2f16\n"
11403                 "     %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
11404                 "   %SSBO_v2f16 = OpTypeStruct %ra_v2f16\n"
11405                 "%up_SSBO_v2f16 = OpTypePointer Uniform %SSBO_v2f16\n"
11406
11407                 "     %up_v3f16 = OpTypePointer Uniform %v3f16\n"
11408                 "     %ra_v3f16 = OpTypeArray %v3f16 %c_i32_ndp\n"
11409                 "   %SSBO_v3f16 = OpTypeStruct %ra_v3f16\n"
11410                 "%up_SSBO_v3f16 = OpTypePointer Uniform %SSBO_v3f16\n"
11411
11412                 "     %up_v4f16 = OpTypePointer Uniform %v4f16\n"
11413                 "     %ra_v4f16 = OpTypeArray %v4f16 %c_i32_ndp\n"
11414                 "   %SSBO_v4f16 = OpTypeStruct %ra_v4f16\n"
11415                 "%up_SSBO_v4f16 = OpTypePointer Uniform %SSBO_v4f16\n"
11416
11417                 "        %fun_t = OpTypeFunction %${tt_dst} %${tt_src0} %${tt_src1} %i32\n"
11418
11419                 "    %ssbo_src0 = OpVariable %up_SSBO_${tt_src0} Uniform\n"
11420                 "    %ssbo_src1 = OpVariable %up_SSBO_${tt_src1} Uniform\n"
11421                 "     %ssbo_dst = OpVariable %up_SSBO_${tt_dst} Uniform\n"
11422         );
11423
11424         const StringTemplate decoration
11425         (
11426                 "OpDecorate %ra_v2f16 ArrayStride 4\n"
11427                 "OpDecorate %ra_v3f16 ArrayStride 8\n"
11428                 "OpDecorate %ra_v4f16 ArrayStride 8\n"
11429
11430                 "OpMemberDecorate %SSBO_v2f16 0 Offset 0\n"
11431                 "OpDecorate %SSBO_v2f16 BufferBlock\n"
11432
11433                 "OpMemberDecorate %SSBO_v3f16 0 Offset 0\n"
11434                 "OpDecorate %SSBO_v3f16 BufferBlock\n"
11435
11436                 "OpMemberDecorate %SSBO_v4f16 0 Offset 0\n"
11437                 "OpDecorate %SSBO_v4f16 BufferBlock\n"
11438
11439                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
11440                 "OpDecorate %ssbo_src0 Binding 0\n"
11441                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
11442                 "OpDecorate %ssbo_src1 Binding 1\n"
11443                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11444                 "OpDecorate %ssbo_dst Binding 2\n"
11445         );
11446
11447         const StringTemplate testFun
11448         (
11449                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11450                 "    %param = OpFunctionParameter %v4f32\n"
11451                 "    %entry = OpLabel\n"
11452
11453                 "        %i = OpVariable %fp_i32 Function\n"
11454                 "             OpStore %i %c_i32_0\n"
11455
11456                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11457                 "             OpSelectionMerge %end_if None\n"
11458                 "             OpBranchConditional %will_run %run_test %end_if\n"
11459
11460                 " %run_test = OpLabel\n"
11461                 "             OpBranch %loop\n"
11462
11463                 "     %loop = OpLabel\n"
11464                 "    %i_cmp = OpLoad %i32 %i\n"
11465                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11466                 "             OpLoopMerge %merge %next None\n"
11467                 "             OpBranchConditional %lt %write %merge\n"
11468
11469                 "    %write = OpLabel\n"
11470                 "      %ndx = OpLoad %i32 %i\n"
11471                 "     %src0 = OpAccessChain %up_${tt_src0} %ssbo_src0 %c_i32_0 %ndx\n"
11472                 " %val_src0 = OpLoad %${tt_src0} %src0\n"
11473                 "     %src1 = OpAccessChain %up_${tt_src1} %ssbo_src1 %c_i32_0 %ndx\n"
11474                 " %val_src1 = OpLoad %${tt_src1} %src1\n"
11475                 "  %val_dst = OpFunctionCall %${tt_dst} %sw_fun %val_src0 %val_src1 %ndx\n"
11476                 "      %dst = OpAccessChain %up_${tt_dst} %ssbo_dst %c_i32_0 %ndx\n"
11477                 "             OpStore %dst %val_dst\n"
11478                 "             OpBranch %next\n"
11479
11480                 "     %next = OpLabel\n"
11481                 "    %i_cur = OpLoad %i32 %i\n"
11482                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11483                 "             OpStore %i %i_new\n"
11484                 "             OpBranch %loop\n"
11485
11486                 "    %merge = OpLabel\n"
11487                 "             OpBranch %end_if\n"
11488                 "   %end_if = OpLabel\n"
11489                 "             OpReturnValue %param\n"
11490                 "             OpFunctionEnd\n"
11491                 "\n"
11492
11493                 "   %sw_fun = OpFunction %${tt_dst} None %fun_t\n"
11494                 "%sw_param0 = OpFunctionParameter %${tt_src0}\n"
11495                 "%sw_param1 = OpFunctionParameter %${tt_src1}\n"
11496                 "%sw_paramn = OpFunctionParameter %i32\n"
11497                 " %sw_entry = OpLabel\n"
11498                 "   %modulo = OpSMod %i32 %sw_paramn %c_i32_cc\n"
11499                 "             OpSelectionMerge %switch_e None\n"
11500                 "             OpSwitch %modulo %default ${case_list}\n"
11501                 "${case_bodies}"
11502                 "%default   = OpLabel\n"
11503                 "             OpUnreachable\n" // Unreachable default case for switch statement
11504                 "%switch_e  = OpLabel\n"
11505                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11506                 "             OpFunctionEnd\n"
11507         );
11508
11509         const StringTemplate testCaseBody
11510         (
11511                 "%case_${case_ndx}    = OpLabel\n"
11512                 "%val_dst_${case_ndx} = OpVectorShuffle %${tt_dst} %sw_param0 %sw_param1 ${shuffle}\n"
11513                 "             OpReturnValue %val_dst_${case_ndx}\n"
11514         );
11515
11516         for (deUint32 dstTypeIdx = 0; dstTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++dstTypeIdx)
11517         {
11518                 const TestType& dstType                 = testTypes[dstTypeIdx];
11519
11520                 for (deUint32 comp0Idx = 0; comp0Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp0Idx)
11521                 {
11522                         const TestType& src0Type        = testTypes[comp0Idx];
11523
11524                         for (deUint32 comp1Idx = 0; comp1Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp1Idx)
11525                         {
11526                                 const TestType&                 src1Type                        = testTypes[comp1Idx];
11527                                 const deUint32                  input0Stride            = (src0Type.typeComponents == 3) ? 4 : src0Type.typeComponents;
11528                                 const deUint32                  input1Stride            = (src1Type.typeComponents == 3) ? 4 : src1Type.typeComponents;
11529                                 const deUint32                  outputStride            = (dstType.typeComponents == 3) ? 4 : dstType.typeComponents;
11530                                 const vector<deFloat16> float16Input0Data       = getFloat16s(rnd, input0Stride * numDataPoints);
11531                                 const vector<deFloat16> float16Input1Data       = getFloat16s(rnd, input1Stride * numDataPoints);
11532                                 const vector<deFloat16> float16OutputDummy      (outputStride * numDataPoints, 0);
11533                                 const string                    testName                        = de::toString(dstType.typeComponents) + de::toString(src0Type.typeComponents) + de::toString(src1Type.typeComponents);
11534                                 deUint32                                caseCount                       = 0;
11535                                 SpecResource                    specResource;
11536                                 map<string, string>             specs;
11537                                 vector<string>                  extensions;
11538                                 VulkanFeatures                  features;
11539                                 string                                  caseBodies;
11540                                 string                                  caseList;
11541
11542                                 // Generate case
11543                                 {
11544                                         vector<string>  componentList;
11545
11546                                         // Generate component possible indices for OpVectorShuffle for components 0 and 1 in output vector
11547                                         {
11548                                                 deUint32                caseNo          = 0;
11549
11550                                                 for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < src0Type.typeComponents; ++comp0IdxLocal)
11551                                                         componentList.push_back(de::toString(caseNo++));
11552                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < src1Type.typeComponents; ++comp1IdxLocal)
11553                                                         componentList.push_back(de::toString(caseNo++));
11554                                                 componentList.push_back("0xFFFFFFFF");
11555                                         }
11556
11557                                         for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < componentList.size(); ++comp0IdxLocal)
11558                                         {
11559                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < componentList.size(); ++comp1IdxLocal)
11560                                                 {
11561                                                         map<string, string>     specCase;
11562                                                         string                          shuffle         = componentList[comp0IdxLocal] + " " + componentList[comp1IdxLocal];
11563
11564                                                         for (deUint32 compIdx = 2; compIdx < dstType.typeComponents; ++compIdx)
11565                                                                 shuffle += " " + de::toString(compIdx - 2);
11566
11567                                                         specCase["case_ndx"]    = de::toString(caseCount);
11568                                                         specCase["shuffle"]             = shuffle;
11569                                                         specCase["tt_dst"]              = dstType.typeName;
11570
11571                                                         caseBodies      += testCaseBody.specialize(specCase);
11572                                                         caseList        += de::toString(caseCount) + " %case_" + de::toString(caseCount) + " ";
11573
11574                                                         caseCount++;
11575                                                 }
11576                                         }
11577                                 }
11578
11579                                 specs["num_data_points"]        = de::toString(numDataPoints);
11580                                 specs["tt_dst"]                         = dstType.typeName;
11581                                 specs["tt_src0"]                        = src0Type.typeName;
11582                                 specs["tt_src1"]                        = src1Type.typeName;
11583                                 specs["case_bodies"]            = caseBodies;
11584                                 specs["case_list"]                      = caseList;
11585                                 specs["case_count"]                     = de::toString(caseCount);
11586
11587                                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11588                                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11589                                 fragments["decoration"]         = decoration.specialize(specs);
11590                                 fragments["pre_main"]           = preMain.specialize(specs);
11591                                 fragments["testfun"]            = testFun.specialize(specs);
11592
11593                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input0Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11594                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input1Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11595                                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11596                                 specResource.verifyIO = getFloat16VectorShuffleVerifyIOFunc(dstType.typeComponents, src0Type.typeComponents, src1Type.typeComponents);
11597
11598                                 extensions.push_back("VK_KHR_16bit_storage");
11599                                 extensions.push_back("VK_KHR_shader_float16_int8");
11600
11601                                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11602                                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11603
11604                                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11605                         }
11606                 }
11607         }
11608
11609         return testGroup.release();
11610 }
11611
11612 bool compareFP16CompositeFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11613 {
11614         if (inputs.size() != 1 || outputAllocs.size() != 1)
11615                 return false;
11616
11617         vector<deUint8> input1Bytes;
11618
11619         inputs[0].getBytes(input1Bytes);
11620
11621         DE_ASSERT(input1Bytes.size() > 0);
11622         DE_ASSERT(input1Bytes.size() % sizeof(deFloat16) == 0);
11623
11624         const size_t                    iterations              = input1Bytes.size() / sizeof(deFloat16);
11625         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
11626         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11627         const deFloat16                 exceptionValue  = tcu::Float16(-1.0).bits();
11628         std::string                             error;
11629
11630         for (size_t idx = 0; idx < iterations; ++idx)
11631         {
11632                 if (input1AsFP16[idx] == exceptionValue)
11633                         continue;
11634
11635                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
11636                 {
11637                         log << TestLog::Message << "At " << idx << ":" << error << TestLog::EndMessage;
11638
11639                         return false;
11640                 }
11641         }
11642
11643         return true;
11644 }
11645
11646 template<class SpecResource>
11647 tcu::TestCaseGroup* createFloat16CompositeConstructSet (tcu::TestContext& testCtx)
11648 {
11649         de::MovePtr<tcu::TestCaseGroup>         testGroup                               (new tcu::TestCaseGroup(testCtx, "opcompositeconstruct", "OpCompositeConstruct tests"));
11650         const deUint32                                          numElements                             = 8;
11651         const string                                            testName                                = "struct";
11652         const deUint32                                          structItemsCount                = 88;
11653         const deUint32                                          exceptionIndices[]              = { 1, 7, 15, 17, 25, 33, 51, 55, 59, 63, 67, 71, 84, 85, 86, 87 };
11654         const deFloat16                                         exceptionValue                  = tcu::Float16(-1.0).bits();
11655         const deUint32                                          fieldModifier                   = 2;
11656         const deUint32                                          fieldModifiedMulIndex   = 60;
11657         const deUint32                                          fieldModifiedAddIndex   = 66;
11658
11659         const StringTemplate preMain
11660         (
11661                 "    %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11662                 "          %f16 = OpTypeFloat 16\n"
11663                 "        %v2f16 = OpTypeVector %f16 2\n"
11664                 "        %v3f16 = OpTypeVector %f16 3\n"
11665                 "        %v4f16 = OpTypeVector %f16 4\n"
11666                 "    %c_f16_mod = OpConstant %f16 ${field_modifier}\n"
11667
11668                 "${consts}"
11669
11670                 "      %c_u32_5 = OpConstant %u32 5\n"
11671
11672                 " %f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11673                 " %v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11674                 " %v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11675                 " %v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11676                 " %v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11677                 " %struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11678                 " %struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11679                 " %st_test      = OpTypeStruct %f16 %v2f16 %v3f16 %v4f16 %f16arr3 %struct16arr3 %v2f16arr5 %f16 %v3f16arr5 %v4f16arr3\n"
11680
11681                 "        %up_st = OpTypePointer Uniform %st_test\n"
11682                 "        %ra_st = OpTypeArray %st_test %c_i32_ndp\n"
11683                 "      %SSBO_st = OpTypeStruct %ra_st\n"
11684                 "   %up_SSBO_st = OpTypePointer Uniform %SSBO_st\n"
11685
11686                 "     %ssbo_dst = OpVariable %up_SSBO_st Uniform\n"
11687         );
11688
11689         const StringTemplate decoration
11690         (
11691                 "OpDecorate %SSBO_st BufferBlock\n"
11692                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11693                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11694                 "OpDecorate %ssbo_dst Binding 1\n"
11695
11696                 "OpMemberDecorate %SSBO_st 0 Offset 0\n"
11697
11698                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11699                 "OpMemberDecorate %struct16 0 Offset 0\n"
11700                 "OpMemberDecorate %struct16 1 Offset 4\n"
11701                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11702                 "OpDecorate %f16arr3 ArrayStride 2\n"
11703                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11704                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11705                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11706
11707                 "OpMemberDecorate %st_test 0 Offset 0\n"
11708                 "OpMemberDecorate %st_test 1 Offset 4\n"
11709                 "OpMemberDecorate %st_test 2 Offset 8\n"
11710                 "OpMemberDecorate %st_test 3 Offset 16\n"
11711                 "OpMemberDecorate %st_test 4 Offset 24\n"
11712                 "OpMemberDecorate %st_test 5 Offset 32\n"
11713                 "OpMemberDecorate %st_test 6 Offset 80\n"
11714                 "OpMemberDecorate %st_test 7 Offset 100\n"
11715                 "OpMemberDecorate %st_test 8 Offset 104\n"
11716                 "OpMemberDecorate %st_test 9 Offset 144\n"
11717         );
11718
11719         const StringTemplate testFun
11720         (
11721                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11722                 "     %param = OpFunctionParameter %v4f32\n"
11723                 "     %entry = OpLabel\n"
11724
11725                 "         %i = OpVariable %fp_i32 Function\n"
11726                 "              OpStore %i %c_i32_0\n"
11727
11728                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11729                 "              OpSelectionMerge %end_if None\n"
11730                 "              OpBranchConditional %will_run %run_test %end_if\n"
11731
11732                 "  %run_test = OpLabel\n"
11733                 "              OpBranch %loop\n"
11734
11735                 "      %loop = OpLabel\n"
11736                 "     %i_cmp = OpLoad %i32 %i\n"
11737                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11738                 "              OpLoopMerge %merge %next None\n"
11739                 "              OpBranchConditional %lt %write %merge\n"
11740
11741                 "     %write = OpLabel\n"
11742                 "       %ndx = OpLoad %i32 %i\n"
11743
11744                 "      %fld1 = OpCompositeConstruct %v2f16 %c_f16_2 %c_f16_3\n"
11745                 "      %fld2 = OpCompositeConstruct %v3f16 %c_f16_4 %c_f16_5 %c_f16_6\n"
11746                 "      %fld3 = OpCompositeConstruct %v4f16 %c_f16_8 %c_f16_9 %c_f16_10 %c_f16_11\n"
11747
11748                 "      %fld4 = OpCompositeConstruct %f16arr3 %c_f16_12 %c_f16_13 %c_f16_14\n"
11749
11750                 "%fld5_0_1_0 = OpCompositeConstruct %v2f16 %c_f16_18 %c_f16_19\n"
11751                 "%fld5_0_1_1 = OpCompositeConstruct %v2f16 %c_f16_20 %c_f16_21\n"
11752                 "%fld5_0_1_2 = OpCompositeConstruct %v2f16 %c_f16_22 %c_f16_23\n"
11753                 "  %fld5_0_1 = OpCompositeConstruct %v2f16arr3 %fld5_0_1_0 %fld5_0_1_1 %fld5_0_1_2\n"
11754                 "    %fld5_0 = OpCompositeConstruct %struct16 %c_f16_16 %fld5_0_1\n"
11755
11756                 "%fld5_1_1_0 = OpCompositeConstruct %v2f16 %c_f16_26 %c_f16_27\n"
11757                 "%fld5_1_1_1 = OpCompositeConstruct %v2f16 %c_f16_28 %c_f16_29\n"
11758                 "%fld5_1_1_2 = OpCompositeConstruct %v2f16 %c_f16_30 %c_f16_31\n"
11759                 "  %fld5_1_1 = OpCompositeConstruct %v2f16arr3 %fld5_1_1_0 %fld5_1_1_1 %fld5_1_1_2\n"
11760                 "    %fld5_1 = OpCompositeConstruct %struct16 %c_f16_24 %fld5_1_1\n"
11761
11762                 "%fld5_2_1_0 = OpCompositeConstruct %v2f16 %c_f16_34 %c_f16_35\n"
11763                 "%fld5_2_1_1 = OpCompositeConstruct %v2f16 %c_f16_36 %c_f16_37\n"
11764                 "%fld5_2_1_2 = OpCompositeConstruct %v2f16 %c_f16_38 %c_f16_39\n"
11765                 "  %fld5_2_1 = OpCompositeConstruct %v2f16arr3 %fld5_2_1_0 %fld5_2_1_1 %fld5_2_1_2\n"
11766                 "    %fld5_2 = OpCompositeConstruct %struct16 %c_f16_32 %fld5_2_1\n"
11767
11768                 "      %fld5 = OpCompositeConstruct %struct16arr3 %fld5_0 %fld5_1 %fld5_2\n"
11769
11770                 "    %fld6_0 = OpCompositeConstruct %v2f16 %c_f16_40 %c_f16_41\n"
11771                 "    %fld6_1 = OpCompositeConstruct %v2f16 %c_f16_42 %c_f16_43\n"
11772                 "    %fld6_2 = OpCompositeConstruct %v2f16 %c_f16_44 %c_f16_45\n"
11773                 "    %fld6_3 = OpCompositeConstruct %v2f16 %c_f16_46 %c_f16_47\n"
11774                 "    %fld6_4 = OpCompositeConstruct %v2f16 %c_f16_48 %c_f16_49\n"
11775                 "      %fld6 = OpCompositeConstruct %v2f16arr5 %fld6_0 %fld6_1 %fld6_2 %fld6_3 %fld6_4\n"
11776
11777                 "      %fndx = OpConvertSToF %f16 %ndx\n"
11778                 "  %fld8_2a0 = OpFMul %f16 %fndx %c_f16_mod\n"
11779                 "  %fld8_3b1 = OpFAdd %f16 %fndx %c_f16_mod\n"
11780
11781                 "   %fld8_2a = OpCompositeConstruct %v2f16 %fld8_2a0 %c_f16_61\n"
11782                 "   %fld8_3b = OpCompositeConstruct %v2f16 %c_f16_65 %fld8_3b1\n"
11783                 "    %fld8_0 = OpCompositeConstruct %v3f16 %c_f16_52 %c_f16_53 %c_f16_54\n"
11784                 "    %fld8_1 = OpCompositeConstruct %v3f16 %c_f16_56 %c_f16_57 %c_f16_58\n"
11785                 "    %fld8_2 = OpCompositeConstruct %v3f16 %fld8_2a %c_f16_62\n"
11786                 "    %fld8_3 = OpCompositeConstruct %v3f16 %c_f16_64 %fld8_3b\n"
11787                 "    %fld8_4 = OpCompositeConstruct %v3f16 %c_f16_68 %c_f16_69 %c_f16_70\n"
11788                 "      %fld8 = OpCompositeConstruct %v3f16arr5 %fld8_0 %fld8_1 %fld8_2 %fld8_3 %fld8_4\n"
11789
11790                 "    %fld9_0 = OpCompositeConstruct %v4f16 %c_f16_72 %c_f16_73 %c_f16_74 %c_f16_75\n"
11791                 "    %fld9_1 = OpCompositeConstruct %v4f16 %c_f16_76 %c_f16_77 %c_f16_78 %c_f16_79\n"
11792                 "    %fld9_2 = OpCompositeConstruct %v4f16 %c_f16_80 %c_f16_81 %c_f16_82 %c_f16_83\n"
11793                 "      %fld9 = OpCompositeConstruct %v4f16arr3 %fld9_0 %fld9_1 %fld9_2\n"
11794
11795                 "    %st_val = OpCompositeConstruct %st_test %c_f16_0 %fld1 %fld2 %fld3 %fld4 %fld5 %fld6 %c_f16_50 %fld8 %fld9\n"
11796                 "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %ndx\n"
11797                 "              OpStore %dst %st_val\n"
11798
11799                 "              OpBranch %next\n"
11800
11801                 "      %next = OpLabel\n"
11802                 "     %i_cur = OpLoad %i32 %i\n"
11803                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11804                 "              OpStore %i %i_new\n"
11805                 "              OpBranch %loop\n"
11806
11807                 "     %merge = OpLabel\n"
11808                 "              OpBranch %end_if\n"
11809                 "    %end_if = OpLabel\n"
11810                 "              OpReturnValue %param\n"
11811                 "              OpFunctionEnd\n"
11812         );
11813
11814         {
11815                 SpecResource            specResource;
11816                 map<string, string>     specs;
11817                 VulkanFeatures          features;
11818                 map<string, string>     fragments;
11819                 vector<string>          extensions;
11820                 vector<deFloat16>       expectedOutput;
11821                 string                          consts;
11822
11823                 for (deUint32 elementNdx = 0; elementNdx < numElements; ++elementNdx)
11824                 {
11825                         vector<deFloat16>       expectedIterationOutput;
11826
11827                         for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
11828                                 expectedIterationOutput.push_back(tcu::Float16(float(structItemNdx)).bits());
11829
11830                         for (deUint32 structItemNdx = 0; structItemNdx < DE_LENGTH_OF_ARRAY(exceptionIndices); ++structItemNdx)
11831                                 expectedIterationOutput[exceptionIndices[structItemNdx]] = exceptionValue;
11832
11833                         expectedIterationOutput[fieldModifiedMulIndex] = tcu::Float16(float(elementNdx * fieldModifier)).bits();
11834                         expectedIterationOutput[fieldModifiedAddIndex] = tcu::Float16(float(elementNdx + fieldModifier)).bits();
11835
11836                         expectedOutput.insert(expectedOutput.end(), expectedIterationOutput.begin(), expectedIterationOutput.end());
11837                 }
11838
11839                 for (deUint32 i = 0; i < structItemsCount; ++i)
11840                         consts += "     %c_f16_" + de::toString(i) + " = OpConstant %f16 "  + de::toString(i) + "\n";
11841
11842                 specs["num_elements"]           = de::toString(numElements);
11843                 specs["struct_item_size"]       = de::toString(structItemsCount * sizeof(deFloat16));
11844                 specs["field_modifier"]         = de::toString(fieldModifier);
11845                 specs["consts"]                         = consts;
11846
11847                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11848                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11849                 fragments["decoration"]         = decoration.specialize(specs);
11850                 fragments["pre_main"]           = preMain.specialize(specs);
11851                 fragments["testfun"]            = testFun.specialize(specs);
11852
11853                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11854                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11855                 specResource.verifyIO = compareFP16CompositeFunc;
11856
11857                 extensions.push_back("VK_KHR_16bit_storage");
11858                 extensions.push_back("VK_KHR_shader_float16_int8");
11859
11860                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11861                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11862
11863                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11864         }
11865
11866         return testGroup.release();
11867 }
11868
11869 template<class SpecResource>
11870 tcu::TestCaseGroup* createFloat16CompositeInsertExtractSet (tcu::TestContext& testCtx, const char* op)
11871 {
11872         de::MovePtr<tcu::TestCaseGroup>         testGroup               (new tcu::TestCaseGroup(testCtx, de::toLower(op).c_str(), op));
11873         const deFloat16                                         exceptionValue  = tcu::Float16(-1.0).bits();
11874         const string                                            opName                  (op);
11875         const deUint32                                          opIndex                 = (opName == "OpCompositeInsert") ? 0
11876                                                                                                                 : (opName == "OpCompositeExtract") ? 1
11877                                                                                                                 : -1;
11878
11879         const StringTemplate preMain
11880         (
11881                 "   %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11882                 "         %f16 = OpTypeFloat 16\n"
11883                 "       %v2f16 = OpTypeVector %f16 2\n"
11884                 "       %v3f16 = OpTypeVector %f16 3\n"
11885                 "       %v4f16 = OpTypeVector %f16 4\n"
11886                 "    %c_f16_na = OpConstant %f16 -1.0\n"
11887                 "     %c_u32_5 = OpConstant %u32 5\n"
11888
11889                 "%f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11890                 "%v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11891                 "%v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11892                 "%v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11893                 "%v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11894                 "%struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11895                 "%struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11896                 "%st_test      = OpTypeStruct %${field_type}\n"
11897
11898                 "      %up_f16 = OpTypePointer Uniform %f16\n"
11899                 "       %up_st = OpTypePointer Uniform %st_test\n"
11900                 "      %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
11901                 "       %ra_st = OpTypeArray %st_test %c_i32_1\n"
11902
11903                 "${op_premain_decls}"
11904
11905                 " %up_SSBO_src = OpTypePointer Uniform %SSBO_src\n"
11906                 " %up_SSBO_dst = OpTypePointer Uniform %SSBO_dst\n"
11907
11908                 "    %ssbo_src = OpVariable %up_SSBO_src Uniform\n"
11909                 "    %ssbo_dst = OpVariable %up_SSBO_dst Uniform\n"
11910         );
11911
11912         const StringTemplate decoration
11913         (
11914                 "OpDecorate %SSBO_src BufferBlock\n"
11915                 "OpDecorate %SSBO_dst BufferBlock\n"
11916                 "OpDecorate %ra_f16 ArrayStride 2\n"
11917                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11918                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11919                 "OpDecorate %ssbo_src Binding 0\n"
11920                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11921                 "OpDecorate %ssbo_dst Binding 1\n"
11922
11923                 "OpMemberDecorate %SSBO_src 0 Offset 0\n"
11924                 "OpMemberDecorate %SSBO_dst 0 Offset 0\n"
11925
11926                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11927                 "OpMemberDecorate %struct16 0 Offset 0\n"
11928                 "OpMemberDecorate %struct16 1 Offset 4\n"
11929                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11930                 "OpDecorate %f16arr3 ArrayStride 2\n"
11931                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11932                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11933                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11934
11935                 "OpMemberDecorate %st_test 0 Offset 0\n"
11936         );
11937
11938         const StringTemplate testFun
11939         (
11940                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11941                 "     %param = OpFunctionParameter %v4f32\n"
11942                 "     %entry = OpLabel\n"
11943
11944                 "         %i = OpVariable %fp_i32 Function\n"
11945                 "              OpStore %i %c_i32_0\n"
11946
11947                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11948                 "              OpSelectionMerge %end_if None\n"
11949                 "              OpBranchConditional %will_run %run_test %end_if\n"
11950
11951                 "  %run_test = OpLabel\n"
11952                 "              OpBranch %loop\n"
11953
11954                 "      %loop = OpLabel\n"
11955                 "     %i_cmp = OpLoad %i32 %i\n"
11956                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11957                 "              OpLoopMerge %merge %next None\n"
11958                 "              OpBranchConditional %lt %write %merge\n"
11959
11960                 "     %write = OpLabel\n"
11961                 "       %ndx = OpLoad %i32 %i\n"
11962
11963                 "${op_sw_fun_call}"
11964
11965                 "              OpStore %dst %val_dst\n"
11966                 "              OpBranch %next\n"
11967
11968                 "      %next = OpLabel\n"
11969                 "     %i_cur = OpLoad %i32 %i\n"
11970                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11971                 "              OpStore %i %i_new\n"
11972                 "              OpBranch %loop\n"
11973
11974                 "     %merge = OpLabel\n"
11975                 "              OpBranch %end_if\n"
11976                 "    %end_if = OpLabel\n"
11977                 "              OpReturnValue %param\n"
11978                 "              OpFunctionEnd\n"
11979
11980                 "${op_sw_fun_header}"
11981                 " %sw_param = OpFunctionParameter %st_test\n"
11982                 "%sw_paramn = OpFunctionParameter %i32\n"
11983                 " %sw_entry = OpLabel\n"
11984                 "             OpSelectionMerge %switch_e None\n"
11985                 "             OpSwitch %sw_paramn %default ${case_list}\n"
11986
11987                 "${case_bodies}"
11988
11989                 "%default   = OpLabel\n"
11990                 "             OpReturnValue ${op_case_default_value}\n"
11991                 "%switch_e  = OpLabel\n"
11992                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11993                 "             OpFunctionEnd\n"
11994         );
11995
11996         const StringTemplate testCaseBody
11997         (
11998                 "%case_${case_ndx}    = OpLabel\n"
11999                 "%val_ret_${case_ndx} = ${op_name} ${op_args_part} ${access_path}\n"
12000                 "             OpReturnValue %val_ret_${case_ndx}\n"
12001         );
12002
12003         struct OpParts
12004         {
12005                 const char*     premainDecls;
12006                 const char*     swFunCall;
12007                 const char*     swFunHeader;
12008                 const char*     caseDefaultValue;
12009                 const char*     argsPartial;
12010         };
12011
12012         OpParts                                                         opPartsArray[]                  =
12013         {
12014                 // OpCompositeInsert
12015                 {
12016                         "       %fun_t = OpTypeFunction %st_test %f16 %st_test %i32\n"
12017                         "    %SSBO_src = OpTypeStruct %ra_f16\n"
12018                         "    %SSBO_dst = OpTypeStruct %ra_st\n",
12019
12020                         "       %src = OpAccessChain %up_f16 %ssbo_src %c_i32_0 %ndx\n"
12021                         "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %c_i32_0\n"
12022                         "   %val_new = OpLoad %f16 %src\n"
12023                         "   %val_old = OpLoad %st_test %dst\n"
12024                         "   %val_dst = OpFunctionCall %st_test %sw_fun %val_new %val_old %ndx\n",
12025
12026                         "   %sw_fun = OpFunction %st_test None %fun_t\n"
12027                         "%sw_paramv = OpFunctionParameter %f16\n",
12028
12029                         "%sw_param",
12030
12031                         "%st_test %sw_paramv %sw_param",
12032                 },
12033                 // OpCompositeExtract
12034                 {
12035                         "       %fun_t = OpTypeFunction %f16 %st_test %i32\n"
12036                         "    %SSBO_src = OpTypeStruct %ra_st\n"
12037                         "    %SSBO_dst = OpTypeStruct %ra_f16\n",
12038
12039                         "       %src = OpAccessChain %up_st %ssbo_src %c_i32_0 %c_i32_0\n"
12040                         "       %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
12041                         "   %val_src = OpLoad %st_test %src\n"
12042                         "   %val_dst = OpFunctionCall %f16 %sw_fun %val_src %ndx\n",
12043
12044                         "   %sw_fun = OpFunction %f16 None %fun_t\n",
12045
12046                         "%c_f16_na",
12047
12048                         "%f16 %sw_param",
12049                 },
12050         };
12051
12052         DE_ASSERT(opIndex >= 0 && opIndex < DE_LENGTH_OF_ARRAY(opPartsArray));
12053
12054         const char*     accessPathF16[] =
12055         {
12056                 "0",                    // %f16
12057                 DE_NULL,
12058         };
12059         const char*     accessPathV2F16[] =
12060         {
12061                 "0 0",                  // %v2f16
12062                 "0 1",
12063         };
12064         const char*     accessPathV3F16[] =
12065         {
12066                 "0 0",                  // %v3f16
12067                 "0 1",
12068                 "0 2",
12069                 DE_NULL,
12070         };
12071         const char*     accessPathV4F16[] =
12072         {
12073                 "0 0",                  // %v4f16"
12074                 "0 1",
12075                 "0 2",
12076                 "0 3",
12077         };
12078         const char*     accessPathF16Arr3[] =
12079         {
12080                 "0 0",                  // %f16arr3
12081                 "0 1",
12082                 "0 2",
12083                 DE_NULL,
12084         };
12085         const char*     accessPathStruct16Arr3[] =
12086         {
12087                 "0 0 0",                // %struct16arr3
12088                 DE_NULL,
12089                 "0 0 1 0 0",
12090                 "0 0 1 0 1",
12091                 "0 0 1 1 0",
12092                 "0 0 1 1 1",
12093                 "0 0 1 2 0",
12094                 "0 0 1 2 1",
12095                 "0 1 0",
12096                 DE_NULL,
12097                 "0 1 1 0 0",
12098                 "0 1 1 0 1",
12099                 "0 1 1 1 0",
12100                 "0 1 1 1 1",
12101                 "0 1 1 2 0",
12102                 "0 1 1 2 1",
12103                 "0 2 0",
12104                 DE_NULL,
12105                 "0 2 1 0 0",
12106                 "0 2 1 0 1",
12107                 "0 2 1 1 0",
12108                 "0 2 1 1 1",
12109                 "0 2 1 2 0",
12110                 "0 2 1 2 1",
12111         };
12112         const char*     accessPathV2F16Arr5[] =
12113         {
12114                 "0 0 0",                // %v2f16arr5
12115                 "0 0 1",
12116                 "0 1 0",
12117                 "0 1 1",
12118                 "0 2 0",
12119                 "0 2 1",
12120                 "0 3 0",
12121                 "0 3 1",
12122                 "0 4 0",
12123                 "0 4 1",
12124         };
12125         const char*     accessPathV3F16Arr5[] =
12126         {
12127                 "0 0 0",                // %v3f16arr5
12128                 "0 0 1",
12129                 "0 0 2",
12130                 DE_NULL,
12131                 "0 1 0",
12132                 "0 1 1",
12133                 "0 1 2",
12134                 DE_NULL,
12135                 "0 2 0",
12136                 "0 2 1",
12137                 "0 2 2",
12138                 DE_NULL,
12139                 "0 3 0",
12140                 "0 3 1",
12141                 "0 3 2",
12142                 DE_NULL,
12143                 "0 4 0",
12144                 "0 4 1",
12145                 "0 4 2",
12146                 DE_NULL,
12147         };
12148         const char*     accessPathV4F16Arr3[] =
12149         {
12150                 "0 0 0",                // %v4f16arr3
12151                 "0 0 1",
12152                 "0 0 2",
12153                 "0 0 3",
12154                 "0 1 0",
12155                 "0 1 1",
12156                 "0 1 2",
12157                 "0 1 3",
12158                 "0 2 0",
12159                 "0 2 1",
12160                 "0 2 2",
12161                 "0 2 3",
12162                 DE_NULL,
12163                 DE_NULL,
12164                 DE_NULL,
12165                 DE_NULL,
12166         };
12167
12168         struct TypeTestParameters
12169         {
12170                 const char*             name;
12171                 size_t                  accessPathLength;
12172                 const char**    accessPath;
12173         };
12174
12175         const TypeTestParameters typeTestParameters[] =
12176         {
12177                 {       "f16",                  DE_LENGTH_OF_ARRAY(accessPathF16),                      accessPathF16                   },
12178                 {       "v2f16",                DE_LENGTH_OF_ARRAY(accessPathV2F16),            accessPathV2F16                 },
12179                 {       "v3f16",                DE_LENGTH_OF_ARRAY(accessPathV3F16),            accessPathV3F16                 },
12180                 {       "v4f16",                DE_LENGTH_OF_ARRAY(accessPathV4F16),            accessPathV4F16                 },
12181                 {       "f16arr3",              DE_LENGTH_OF_ARRAY(accessPathF16Arr3),          accessPathF16Arr3               },
12182                 {       "v2f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV2F16Arr5),        accessPathV2F16Arr5             },
12183                 {       "v3f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV3F16Arr5),        accessPathV3F16Arr5             },
12184                 {       "v4f16arr3",    DE_LENGTH_OF_ARRAY(accessPathV4F16Arr3),        accessPathV4F16Arr3             },
12185                 {       "struct16arr3", DE_LENGTH_OF_ARRAY(accessPathStruct16Arr3),     accessPathStruct16Arr3  },
12186         };
12187
12188         for (size_t typeTestNdx = 0; typeTestNdx < DE_LENGTH_OF_ARRAY(typeTestParameters); ++typeTestNdx)
12189         {
12190                 const OpParts           opParts                         = opPartsArray[opIndex];
12191                 const string            testName                        = typeTestParameters[typeTestNdx].name;
12192                 const size_t            structItemsCount        = typeTestParameters[typeTestNdx].accessPathLength;
12193                 const char**            accessPath                      = typeTestParameters[typeTestNdx].accessPath;
12194                 SpecResource            specResource;
12195                 map<string, string>     specs;
12196                 VulkanFeatures          features;
12197                 map<string, string>     fragments;
12198                 vector<string>          extensions;
12199                 vector<deFloat16>       inputFP16;
12200                 vector<deFloat16>       dummyFP16Output;
12201
12202                 // Generate values for input
12203                 inputFP16.reserve(structItemsCount);
12204                 for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
12205                         inputFP16.push_back((accessPath[structItemNdx] == DE_NULL) ? exceptionValue : tcu::Float16(float(structItemNdx)).bits());
12206
12207                 dummyFP16Output.resize(structItemsCount);
12208
12209                 // Generate cases for OpSwitch
12210                 {
12211                         string  caseBodies;
12212                         string  caseList;
12213
12214                         for (deUint32 caseNdx = 0; caseNdx < structItemsCount; ++caseNdx)
12215                                 if (accessPath[caseNdx] != DE_NULL)
12216                                 {
12217                                         map<string, string>     specCase;
12218
12219                                         specCase["case_ndx"]            = de::toString(caseNdx);
12220                                         specCase["access_path"]         = accessPath[caseNdx];
12221                                         specCase["op_args_part"]        = opParts.argsPartial;
12222                                         specCase["op_name"]                     = opName;
12223
12224                                         caseBodies      += testCaseBody.specialize(specCase);
12225                                         caseList        += de::toString(caseNdx) + " %case_" + de::toString(caseNdx) + " ";
12226                                 }
12227
12228                         specs["case_bodies"]    = caseBodies;
12229                         specs["case_list"]              = caseList;
12230                 }
12231
12232                 specs["num_elements"]                   = de::toString(structItemsCount);
12233                 specs["field_type"]                             = typeTestParameters[typeTestNdx].name;
12234                 specs["struct_item_size"]               = de::toString(structItemsCount * sizeof(deFloat16));
12235                 specs["op_premain_decls"]               = opParts.premainDecls;
12236                 specs["op_sw_fun_call"]                 = opParts.swFunCall;
12237                 specs["op_sw_fun_header"]               = opParts.swFunHeader;
12238                 specs["op_case_default_value"]  = opParts.caseDefaultValue;
12239
12240                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
12241                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
12242                 fragments["decoration"]         = decoration.specialize(specs);
12243                 fragments["pre_main"]           = preMain.specialize(specs);
12244                 fragments["testfun"]            = testFun.specialize(specs);
12245
12246                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputFP16)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12247                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(dummyFP16Output)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12248                 specResource.verifyIO = compareFP16CompositeFunc;
12249
12250                 extensions.push_back("VK_KHR_16bit_storage");
12251                 extensions.push_back("VK_KHR_shader_float16_int8");
12252
12253                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
12254                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
12255
12256                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
12257         }
12258
12259         return testGroup.release();
12260 }
12261
12262 struct fp16PerComponent
12263 {
12264         fp16PerComponent()
12265                 : flavor(0)
12266                 , floatFormat16 (-14, 15, 10, true)
12267                 , outCompCount(0)
12268                 , argCompCount(3, 0)
12269         {
12270         }
12271
12272         bool                    callOncePerComponent    ()                                                                      { return true; }
12273         deUint32                getComponentValidity    ()                                                                      { return static_cast<deUint32>(-1); }
12274
12275         virtual double  getULPs                                 (vector<const deFloat16*>&)                     { return 1.0; }
12276         virtual double  getMin                                  (double value, double ulps)                     { return value - floatFormat16.ulp(deAbs(value), ulps); }
12277         virtual double  getMax                                  (double value, double ulps)                     { return value + floatFormat16.ulp(deAbs(value), ulps); }
12278
12279         virtual size_t  getFlavorCount                  ()                                                                      { return flavorNames.empty() ? 1 : flavorNames.size(); }
12280         virtual void    setFlavor                               (size_t flavorNo)                                       { DE_ASSERT(flavorNo < getFlavorCount()); flavor = flavorNo; }
12281         virtual size_t  getFlavor                               ()                                                                      { return flavor; }
12282         virtual string  getCurrentFlavorName    ()                                                                      { return flavorNames.empty() ? string("") : flavorNames[getFlavor()]; }
12283
12284         virtual void    setOutCompCount                 (size_t compCount)                                      { outCompCount = compCount; }
12285         virtual size_t  getOutCompCount                 ()                                                                      { return outCompCount; }
12286
12287         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)        { argCompCount[argNo] = compCount; }
12288         virtual size_t  getArgCompCount                 (size_t argNo)                                          { return argCompCount[argNo]; }
12289
12290 protected:
12291         size_t                          flavor;
12292         tcu::FloatFormat        floatFormat16;
12293         size_t                          outCompCount;
12294         vector<size_t>          argCompCount;
12295         vector<string>          flavorNames;
12296 };
12297
12298 struct fp16OpFNegate : public fp16PerComponent
12299 {
12300         template <class fp16type>
12301         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12302         {
12303                 const fp16type  x               (*in[0]);
12304                 const double    d               (x.asDouble());
12305                 const double    result  (0.0 - d);
12306
12307                 out[0] = fp16type(result).bits();
12308                 min[0] = getMin(result, getULPs(in));
12309                 max[0] = getMax(result, getULPs(in));
12310
12311                 return true;
12312         }
12313 };
12314
12315 struct fp16Round : public fp16PerComponent
12316 {
12317         fp16Round() : fp16PerComponent()
12318         {
12319                 flavorNames.push_back("Floor(x+0.5)");
12320                 flavorNames.push_back("Floor(x-0.5)");
12321                 flavorNames.push_back("RoundEven");
12322         }
12323
12324         template<class fp16type>
12325         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12326         {
12327                 const fp16type  x               (*in[0]);
12328                 const double    d               (x.asDouble());
12329                 double                  result  (0.0);
12330
12331                 switch (flavor)
12332                 {
12333                         case 0:         result = deRound(d);            break;
12334                         case 1:         result = deFloor(d - 0.5);      break;
12335                         case 2:         result = deRoundEven(d);        break;
12336                         default:        TCU_THROW(InternalError, "Invalid flavor specified");
12337                 }
12338
12339                 out[0] = fp16type(result).bits();
12340                 min[0] = getMin(result, getULPs(in));
12341                 max[0] = getMax(result, getULPs(in));
12342
12343                 return true;
12344         }
12345 };
12346
12347 struct fp16RoundEven : public fp16PerComponent
12348 {
12349         template<class fp16type>
12350         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12351         {
12352                 const fp16type  x               (*in[0]);
12353                 const double    d               (x.asDouble());
12354                 const double    result  (deRoundEven(d));
12355
12356                 out[0] = fp16type(result).bits();
12357                 min[0] = getMin(result, getULPs(in));
12358                 max[0] = getMax(result, getULPs(in));
12359
12360                 return true;
12361         }
12362 };
12363
12364 struct fp16Trunc : public fp16PerComponent
12365 {
12366         template<class fp16type>
12367         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12368         {
12369                 const fp16type  x               (*in[0]);
12370                 const double    d               (x.asDouble());
12371                 const double    result  (deTrunc(d));
12372
12373                 out[0] = fp16type(result).bits();
12374                 min[0] = getMin(result, getULPs(in));
12375                 max[0] = getMax(result, getULPs(in));
12376
12377                 return true;
12378         }
12379 };
12380
12381 struct fp16FAbs : public fp16PerComponent
12382 {
12383         template<class fp16type>
12384         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12385         {
12386                 const fp16type  x               (*in[0]);
12387                 const double    d               (x.asDouble());
12388                 const double    result  (deAbs(d));
12389
12390                 out[0] = fp16type(result).bits();
12391                 min[0] = getMin(result, getULPs(in));
12392                 max[0] = getMax(result, getULPs(in));
12393
12394                 return true;
12395         }
12396 };
12397
12398 struct fp16FSign : public fp16PerComponent
12399 {
12400         template<class fp16type>
12401         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12402         {
12403                 const fp16type  x               (*in[0]);
12404                 const double    d               (x.asDouble());
12405                 const double    result  (deSign(d));
12406
12407                 if (x.isNaN())
12408                         return false;
12409
12410                 out[0] = fp16type(result).bits();
12411                 min[0] = getMin(result, getULPs(in));
12412                 max[0] = getMax(result, getULPs(in));
12413
12414                 return true;
12415         }
12416 };
12417
12418 struct fp16Floor : public fp16PerComponent
12419 {
12420         template<class fp16type>
12421         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12422         {
12423                 const fp16type  x               (*in[0]);
12424                 const double    d               (x.asDouble());
12425                 const double    result  (deFloor(d));
12426
12427                 out[0] = fp16type(result).bits();
12428                 min[0] = getMin(result, getULPs(in));
12429                 max[0] = getMax(result, getULPs(in));
12430
12431                 return true;
12432         }
12433 };
12434
12435 struct fp16Ceil : public fp16PerComponent
12436 {
12437         template<class fp16type>
12438         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12439         {
12440                 const fp16type  x               (*in[0]);
12441                 const double    d               (x.asDouble());
12442                 const double    result  (deCeil(d));
12443
12444                 out[0] = fp16type(result).bits();
12445                 min[0] = getMin(result, getULPs(in));
12446                 max[0] = getMax(result, getULPs(in));
12447
12448                 return true;
12449         }
12450 };
12451
12452 struct fp16Fract : public fp16PerComponent
12453 {
12454         template<class fp16type>
12455         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12456         {
12457                 const fp16type  x               (*in[0]);
12458                 const double    d               (x.asDouble());
12459                 const double    result  (deFrac(d));
12460
12461                 out[0] = fp16type(result).bits();
12462                 min[0] = getMin(result, getULPs(in));
12463                 max[0] = getMax(result, getULPs(in));
12464
12465                 return true;
12466         }
12467 };
12468
12469 struct fp16Radians : public fp16PerComponent
12470 {
12471         virtual double getULPs (vector<const deFloat16*>& in)
12472         {
12473                 DE_UNREF(in);
12474
12475                 return 2.5;
12476         }
12477
12478         template<class fp16type>
12479         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12480         {
12481                 const fp16type  x               (*in[0]);
12482                 const float             d               (x.asFloat());
12483                 const float             result  (deFloatRadians(d));
12484
12485                 out[0] = fp16type(result).bits();
12486                 min[0] = getMin(result, getULPs(in));
12487                 max[0] = getMax(result, getULPs(in));
12488
12489                 return true;
12490         }
12491 };
12492
12493 struct fp16Degrees : public fp16PerComponent
12494 {
12495         virtual double getULPs (vector<const deFloat16*>& in)
12496         {
12497                 DE_UNREF(in);
12498
12499                 return 2.5;
12500         }
12501
12502         template<class fp16type>
12503         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12504         {
12505                 const fp16type  x               (*in[0]);
12506                 const float             d               (x.asFloat());
12507                 const float             result  (deFloatDegrees(d));
12508
12509                 out[0] = fp16type(result).bits();
12510                 min[0] = getMin(result, getULPs(in));
12511                 max[0] = getMax(result, getULPs(in));
12512
12513                 return true;
12514         }
12515 };
12516
12517 struct fp16Sin : public fp16PerComponent
12518 {
12519         template<class fp16type>
12520         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12521         {
12522                 const fp16type  x                       (*in[0]);
12523                 const double    d                       (x.asDouble());
12524                 const double    result          (deSin(d));
12525                 const double    unspecUlp       (16.0);
12526                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12527
12528                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12529                         return false;
12530
12531                 out[0] = fp16type(result).bits();
12532                 min[0] = result - err;
12533                 max[0] = result + err;
12534
12535                 return true;
12536         }
12537 };
12538
12539 struct fp16Cos : public fp16PerComponent
12540 {
12541         template<class fp16type>
12542         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12543         {
12544                 const fp16type  x                       (*in[0]);
12545                 const double    d                       (x.asDouble());
12546                 const double    result          (deCos(d));
12547                 const double    unspecUlp       (16.0);
12548                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12549
12550                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12551                         return false;
12552
12553                 out[0] = fp16type(result).bits();
12554                 min[0] = result - err;
12555                 max[0] = result + err;
12556
12557                 return true;
12558         }
12559 };
12560
12561 struct fp16Tan : public fp16PerComponent
12562 {
12563         template<class fp16type>
12564         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12565         {
12566                 const fp16type  x               (*in[0]);
12567                 const double    d               (x.asDouble());
12568                 const double    result  (deTan(d));
12569
12570                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12571                         return false;
12572
12573                 out[0] = fp16type(result).bits();
12574                 {
12575                         const double    err                     = deLdExp(1.0, -7);
12576                         const double    s1                      = deSin(d) + err;
12577                         const double    s2                      = deSin(d) - err;
12578                         const double    c1                      = deCos(d) + err;
12579                         const double    c2                      = deCos(d) - err;
12580                         const double    edgeVals[]      = {s1/c1, s1/c2, s2/c1, s2/c2};
12581                         double                  edgeLeft        = out[0];
12582                         double                  edgeRight       = out[0];
12583
12584                         if (deSign(c1 * c2) < 0.0)
12585                         {
12586                                 edgeLeft        = -std::numeric_limits<double>::infinity();
12587                                 edgeRight       = +std::numeric_limits<double>::infinity();
12588                         }
12589                         else
12590                         {
12591                                 edgeLeft        = *std::min_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12592                                 edgeRight       = *std::max_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12593                         }
12594
12595                         min[0] = edgeLeft;
12596                         max[0] = edgeRight;
12597                 }
12598
12599                 return true;
12600         }
12601 };
12602
12603 struct fp16Asin : public fp16PerComponent
12604 {
12605         template<class fp16type>
12606         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12607         {
12608                 const fp16type  x               (*in[0]);
12609                 const double    d               (x.asDouble());
12610                 const double    result  (deAsin(d));
12611                 const double    error   (deAtan2(d, sqrt(1.0 - d * d)));
12612
12613                 if (!x.isNaN() && deAbs(d) > 1.0)
12614                         return false;
12615
12616                 out[0] = fp16type(result).bits();
12617                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12618                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12619
12620                 return true;
12621         }
12622 };
12623
12624 struct fp16Acos : public fp16PerComponent
12625 {
12626         template<class fp16type>
12627         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12628         {
12629                 const fp16type  x               (*in[0]);
12630                 const double    d               (x.asDouble());
12631                 const double    result  (deAcos(d));
12632                 const double    error   (deAtan2(sqrt(1.0 - d * d), d));
12633
12634                 if (!x.isNaN() && deAbs(d) > 1.0)
12635                         return false;
12636
12637                 out[0] = fp16type(result).bits();
12638                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12639                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12640
12641                 return true;
12642         }
12643 };
12644
12645 struct fp16Atan : public fp16PerComponent
12646 {
12647         virtual double getULPs(vector<const deFloat16*>& in)
12648         {
12649                 DE_UNREF(in);
12650
12651                 return 2 * 5.0; // This is not a precision test. Value is not from spec
12652         }
12653
12654         template<class fp16type>
12655         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12656         {
12657                 const fp16type  x               (*in[0]);
12658                 const double    d               (x.asDouble());
12659                 const double    result  (deAtanOver(d));
12660
12661                 out[0] = fp16type(result).bits();
12662                 min[0] = getMin(result, getULPs(in));
12663                 max[0] = getMax(result, getULPs(in));
12664
12665                 return true;
12666         }
12667 };
12668
12669 struct fp16Sinh : public fp16PerComponent
12670 {
12671         fp16Sinh() : fp16PerComponent()
12672         {
12673                 flavorNames.push_back("Double");
12674                 flavorNames.push_back("ExpFP16");
12675         }
12676
12677         template<class fp16type>
12678         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12679         {
12680                 const fp16type  x               (*in[0]);
12681                 const double    d               (x.asDouble());
12682                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12683                 double                  result  (0.0);
12684                 double                  error   (0.0);
12685
12686                 if (getFlavor() == 0)
12687                 {
12688                         result  = deSinh(d);
12689                         error   = floatFormat16.ulp(deAbs(result), ulps);
12690                 }
12691                 else if (getFlavor() == 1)
12692                 {
12693                         const fp16type  epx     (deExp(d));
12694                         const fp16type  enx     (deExp(-d));
12695                         const fp16type  esx     (epx.asDouble() - enx.asDouble());
12696                         const fp16type  sx2     (esx.asDouble() / 2.0);
12697
12698                         result  = sx2.asDouble();
12699                         error   = deAbs(floatFormat16.ulp(epx.asDouble(), ulps)) + deAbs(floatFormat16.ulp(enx.asDouble(), ulps));
12700                 }
12701                 else
12702                 {
12703                         TCU_THROW(InternalError, "Unknown flavor");
12704                 }
12705
12706                 out[0] = fp16type(result).bits();
12707                 min[0] = result - error;
12708                 max[0] = result + error;
12709
12710                 return true;
12711         }
12712 };
12713
12714 struct fp16Cosh : public fp16PerComponent
12715 {
12716         fp16Cosh() : fp16PerComponent()
12717         {
12718                 flavorNames.push_back("Double");
12719                 flavorNames.push_back("ExpFP16");
12720         }
12721
12722         template<class fp16type>
12723         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12724         {
12725                 const fp16type  x               (*in[0]);
12726                 const double    d               (x.asDouble());
12727                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12728                 double                  result  (0.0);
12729
12730                 if (getFlavor() == 0)
12731                 {
12732                         result = deCosh(d);
12733                 }
12734                 else if (getFlavor() == 1)
12735                 {
12736                         const fp16type  epx     (deExp(d));
12737                         const fp16type  enx     (deExp(-d));
12738                         const fp16type  esx     (epx.asDouble() + enx.asDouble());
12739                         const fp16type  sx2     (esx.asDouble() / 2.0);
12740
12741                         result = sx2.asDouble();
12742                 }
12743                 else
12744                 {
12745                         TCU_THROW(InternalError, "Unknown flavor");
12746                 }
12747
12748                 out[0] = fp16type(result).bits();
12749                 min[0] = result - floatFormat16.ulp(deAbs(result), ulps);
12750                 max[0] = result + floatFormat16.ulp(deAbs(result), ulps);
12751
12752                 return true;
12753         }
12754 };
12755
12756 struct fp16Tanh : public fp16PerComponent
12757 {
12758         fp16Tanh() : fp16PerComponent()
12759         {
12760                 flavorNames.push_back("Tanh");
12761                 flavorNames.push_back("SinhCosh");
12762                 flavorNames.push_back("SinhCoshFP16");
12763                 flavorNames.push_back("PolyFP16");
12764         }
12765
12766         virtual double getULPs (vector<const deFloat16*>& in)
12767         {
12768                 const tcu::Float16      x       (*in[0]);
12769                 const double            d       (x.asDouble());
12770
12771                 return 2 * (1.0 + 2 * deAbs(d)); // This is not a precision test. Value is not from spec
12772         }
12773
12774         template<class fp16type>
12775         inline double calcPoly (const fp16type& espx, const fp16type& esnx, const fp16type& ecpx, const fp16type& ecnx)
12776         {
12777                 const fp16type  esx     (espx.asDouble() - esnx.asDouble());
12778                 const fp16type  sx2     (esx.asDouble() / 2.0);
12779                 const fp16type  ecx     (ecpx.asDouble() + ecnx.asDouble());
12780                 const fp16type  cx2     (ecx.asDouble() / 2.0);
12781                 const fp16type  tg      (sx2.asDouble() / cx2.asDouble());
12782                 const double    rez     (tg.asDouble());
12783
12784                 return rez;
12785         }
12786
12787         template<class fp16type>
12788         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12789         {
12790                 const fp16type  x               (*in[0]);
12791                 const double    d               (x.asDouble());
12792                 double                  result  (0.0);
12793
12794                 if (getFlavor() == 0)
12795                 {
12796                         result  = deTanh(d);
12797                         min[0]  = getMin(result, getULPs(in));
12798                         max[0]  = getMax(result, getULPs(in));
12799                 }
12800                 else if (getFlavor() == 1)
12801                 {
12802                         result  = deSinh(d) / deCosh(d);
12803                         min[0]  = getMin(result, getULPs(in));
12804                         max[0]  = getMax(result, getULPs(in));
12805                 }
12806                 else if (getFlavor() == 2)
12807                 {
12808                         const fp16type  s       (deSinh(d));
12809                         const fp16type  c       (deCosh(d));
12810
12811                         result  = s.asDouble() / c.asDouble();
12812                         min[0]  = getMin(result, getULPs(in));
12813                         max[0]  = getMax(result, getULPs(in));
12814                 }
12815                 else if (getFlavor() == 3)
12816                 {
12817                         const double    ulps    (getULPs(in));
12818                         const double    epxm    (deExp( d));
12819                         const double    enxm    (deExp(-d));
12820                         const double    epxmerr = floatFormat16.ulp(epxm, ulps);
12821                         const double    enxmerr = floatFormat16.ulp(enxm, ulps);
12822                         const fp16type  epx[]   = { fp16type(epxm - epxmerr), fp16type(epxm + epxmerr) };
12823                         const fp16type  enx[]   = { fp16type(enxm - enxmerr), fp16type(enxm + enxmerr) };
12824                         const fp16type  epxm16  (epxm);
12825                         const fp16type  enxm16  (enxm);
12826                         vector<double>  tgs;
12827
12828                         for (size_t spNdx = 0; spNdx < DE_LENGTH_OF_ARRAY(epx); ++spNdx)
12829                         for (size_t snNdx = 0; snNdx < DE_LENGTH_OF_ARRAY(enx); ++snNdx)
12830                         for (size_t cpNdx = 0; cpNdx < DE_LENGTH_OF_ARRAY(epx); ++cpNdx)
12831                         for (size_t cnNdx = 0; cnNdx < DE_LENGTH_OF_ARRAY(enx); ++cnNdx)
12832                         {
12833                                 const double tgh = calcPoly(epx[spNdx], enx[snNdx], epx[cpNdx], enx[cnNdx]);
12834
12835                                 tgs.push_back(tgh);
12836                         }
12837
12838                         result = calcPoly(epxm16, enxm16, epxm16, enxm16);
12839                         min[0] = *std::min_element(tgs.begin(), tgs.end());
12840                         max[0] = *std::max_element(tgs.begin(), tgs.end());
12841                 }
12842                 else
12843                 {
12844                         TCU_THROW(InternalError, "Unknown flavor");
12845                 }
12846
12847                 out[0] = fp16type(result).bits();
12848
12849                 return true;
12850         }
12851 };
12852
12853 struct fp16Asinh : public fp16PerComponent
12854 {
12855         fp16Asinh() : fp16PerComponent()
12856         {
12857                 flavorNames.push_back("Double");
12858                 flavorNames.push_back("PolyFP16Wiki");
12859                 flavorNames.push_back("PolyFP16Abs");
12860         }
12861
12862         virtual double getULPs (vector<const deFloat16*>& in)
12863         {
12864                 DE_UNREF(in);
12865
12866                 return 256.0; // This is not a precision test. Value is not from spec
12867         }
12868
12869         template<class fp16type>
12870         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12871         {
12872                 const fp16type  x               (*in[0]);
12873                 const double    d               (x.asDouble());
12874                 double                  result  (0.0);
12875
12876                 if (getFlavor() == 0)
12877                 {
12878                         result = deAsinh(d);
12879                 }
12880                 else if (getFlavor() == 1)
12881                 {
12882                         const fp16type  x2              (d * d);
12883                         const fp16type  x2p1    (x2.asDouble() + 1.0);
12884                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
12885                         const fp16type  sxsq    (d + sq.asDouble());
12886                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12887
12888                         if (lsxsq.isInf())
12889                                 return false;
12890
12891                         result = lsxsq.asDouble();
12892                 }
12893                 else if (getFlavor() == 2)
12894                 {
12895                         const fp16type  x2              (d * d);
12896                         const fp16type  x2p1    (x2.asDouble() + 1.0);
12897                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
12898                         const fp16type  sxsq    (deAbs(d) + sq.asDouble());
12899                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12900
12901                         result = deSign(d) * lsxsq.asDouble();
12902                 }
12903                 else
12904                 {
12905                         TCU_THROW(InternalError, "Unknown flavor");
12906                 }
12907
12908                 out[0] = fp16type(result).bits();
12909                 min[0] = getMin(result, getULPs(in));
12910                 max[0] = getMax(result, getULPs(in));
12911
12912                 return true;
12913         }
12914 };
12915
12916 struct fp16Acosh : public fp16PerComponent
12917 {
12918         fp16Acosh() : fp16PerComponent()
12919         {
12920                 flavorNames.push_back("Double");
12921                 flavorNames.push_back("PolyFP16");
12922         }
12923
12924         virtual double getULPs (vector<const deFloat16*>& in)
12925         {
12926                 DE_UNREF(in);
12927
12928                 return 16.0; // This is not a precision test. Value is not from spec
12929         }
12930
12931         template<class fp16type>
12932         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12933         {
12934                 const fp16type  x               (*in[0]);
12935                 const double    d               (x.asDouble());
12936                 double                  result  (0.0);
12937
12938                 if (!x.isNaN() && d < 1.0)
12939                         return false;
12940
12941                 if (getFlavor() == 0)
12942                 {
12943                         result = deAcosh(d);
12944                 }
12945                 else if (getFlavor() == 1)
12946                 {
12947                         const fp16type  x2              (d * d);
12948                         const fp16type  x2m1    (x2.asDouble() - 1.0);
12949                         const fp16type  sq              (deSqrt(x2m1.asDouble()));
12950                         const fp16type  sxsq    (d + sq.asDouble());
12951                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12952
12953                         result = lsxsq.asDouble();
12954                 }
12955                 else
12956                 {
12957                         TCU_THROW(InternalError, "Unknown flavor");
12958                 }
12959
12960                 out[0] = fp16type(result).bits();
12961                 min[0] = getMin(result, getULPs(in));
12962                 max[0] = getMax(result, getULPs(in));
12963
12964                 return true;
12965         }
12966 };
12967
12968 struct fp16Atanh : public fp16PerComponent
12969 {
12970         fp16Atanh() : fp16PerComponent()
12971         {
12972                 flavorNames.push_back("Double");
12973                 flavorNames.push_back("PolyFP16");
12974         }
12975
12976         template<class fp16type>
12977         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12978         {
12979                 const fp16type  x               (*in[0]);
12980                 const double    d               (x.asDouble());
12981                 double                  result  (0.0);
12982
12983                 if (deAbs(d) >= 1.0)
12984                         return false;
12985
12986                 if (getFlavor() == 0)
12987                 {
12988                         const double    ulps    (16.0); // This is not a precision test. Value is not from spec
12989
12990                         result = deAtanh(d);
12991                         min[0] = getMin(result, ulps);
12992                         max[0] = getMax(result, ulps);
12993                 }
12994                 else if (getFlavor() == 1)
12995                 {
12996                         const fp16type  x1a             (1.0 + d);
12997                         const fp16type  x1b             (1.0 - d);
12998                         const fp16type  x1d             (x1a.asDouble() / x1b.asDouble());
12999                         const fp16type  lx1d    (deLog(x1d.asDouble()));
13000                         const fp16type  lx1d2   (0.5 * lx1d.asDouble());
13001                         const double    error   (2 * (de::inRange(deAbs(x1d.asDouble()), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(x1d.asDouble()), 3.0)));
13002
13003                         result = lx1d2.asDouble();
13004                         min[0] = result - error;
13005                         max[0] = result + error;
13006                 }
13007                 else
13008                 {
13009                         TCU_THROW(InternalError, "Unknown flavor");
13010                 }
13011
13012                 out[0] = fp16type(result).bits();
13013
13014                 return true;
13015         }
13016 };
13017
13018 struct fp16Exp : public fp16PerComponent
13019 {
13020         template<class fp16type>
13021         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13022         {
13023                 const fp16type  x               (*in[0]);
13024                 const double    d               (x.asDouble());
13025                 const double    ulps    (10.0 * (1.0 + 2.0 * deAbs(d)));
13026                 const double    result  (deExp(d));
13027
13028                 out[0] = fp16type(result).bits();
13029                 min[0] = getMin(result, ulps);
13030                 max[0] = getMax(result, ulps);
13031
13032                 return true;
13033         }
13034 };
13035
13036 struct fp16Log : public fp16PerComponent
13037 {
13038         template<class fp16type>
13039         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13040         {
13041                 const fp16type  x               (*in[0]);
13042                 const double    d               (x.asDouble());
13043                 const double    result  (deLog(d));
13044                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13045
13046                 if (d <= 0.0)
13047                         return false;
13048
13049                 out[0] = fp16type(result).bits();
13050                 min[0] = result - error;
13051                 max[0] = result + error;
13052
13053                 return true;
13054         }
13055 };
13056
13057 struct fp16Exp2 : public fp16PerComponent
13058 {
13059         template<class fp16type>
13060         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13061         {
13062                 const fp16type  x               (*in[0]);
13063                 const double    d               (x.asDouble());
13064                 const double    result  (deExp2(d));
13065                 const double    ulps    (1.0 + 2.0 * deAbs(fp16type(in[0][0]).asDouble()));
13066
13067                 out[0] = fp16type(result).bits();
13068                 min[0] = getMin(result, ulps);
13069                 max[0] = getMax(result, ulps);
13070
13071                 return true;
13072         }
13073 };
13074
13075 struct fp16Log2 : public fp16PerComponent
13076 {
13077         template<class fp16type>
13078         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13079         {
13080                 const fp16type  x               (*in[0]);
13081                 const double    d               (x.asDouble());
13082                 const double    result  (deLog2(d));
13083                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13084
13085                 if (d <= 0.0)
13086                         return false;
13087
13088                 out[0] = fp16type(result).bits();
13089                 min[0] = result - error;
13090                 max[0] = result + error;
13091
13092                 return true;
13093         }
13094 };
13095
13096 struct fp16Sqrt : public fp16PerComponent
13097 {
13098         virtual double getULPs (vector<const deFloat16*>& in)
13099         {
13100                 DE_UNREF(in);
13101
13102                 return 6.0;
13103         }
13104
13105         template<class fp16type>
13106         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13107         {
13108                 const fp16type  x               (*in[0]);
13109                 const double    d               (x.asDouble());
13110                 const double    result  (deSqrt(d));
13111
13112                 if (!x.isNaN() && d < 0.0)
13113                         return false;
13114
13115                 out[0] = fp16type(result).bits();
13116                 min[0] = getMin(result, getULPs(in));
13117                 max[0] = getMax(result, getULPs(in));
13118
13119                 return true;
13120         }
13121 };
13122
13123 struct fp16InverseSqrt : public fp16PerComponent
13124 {
13125         virtual double getULPs (vector<const deFloat16*>& in)
13126         {
13127                 DE_UNREF(in);
13128
13129                 return 2.0;
13130         }
13131
13132         template<class fp16type>
13133         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13134         {
13135                 const fp16type  x               (*in[0]);
13136                 const double    d               (x.asDouble());
13137                 const double    result  (1.0/deSqrt(d));
13138
13139                 if (!x.isNaN() && d <= 0.0)
13140                         return false;
13141
13142                 out[0] = fp16type(result).bits();
13143                 min[0] = getMin(result, getULPs(in));
13144                 max[0] = getMax(result, getULPs(in));
13145
13146                 return true;
13147         }
13148 };
13149
13150 struct fp16ModfFrac : public fp16PerComponent
13151 {
13152         template<class fp16type>
13153         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13154         {
13155                 const fp16type  x               (*in[0]);
13156                 const double    d               (x.asDouble());
13157                 double                  i               (0.0);
13158                 const double    result  (deModf(d, &i));
13159
13160                 if (x.isInf() || x.isNaN())
13161                         return false;
13162
13163                 out[0] = fp16type(result).bits();
13164                 min[0] = getMin(result, getULPs(in));
13165                 max[0] = getMax(result, getULPs(in));
13166
13167                 return true;
13168         }
13169 };
13170
13171 struct fp16ModfInt : public fp16PerComponent
13172 {
13173         template<class fp16type>
13174         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13175         {
13176                 const fp16type  x               (*in[0]);
13177                 const double    d               (x.asDouble());
13178                 double                  i               (0.0);
13179                 const double    dummy   (deModf(d, &i));
13180                 const double    result  (i);
13181
13182                 DE_UNREF(dummy);
13183
13184                 if (x.isInf() || x.isNaN())
13185                         return false;
13186
13187                 out[0] = fp16type(result).bits();
13188                 min[0] = getMin(result, getULPs(in));
13189                 max[0] = getMax(result, getULPs(in));
13190
13191                 return true;
13192         }
13193 };
13194
13195 struct fp16FrexpS : public fp16PerComponent
13196 {
13197         template<class fp16type>
13198         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13199         {
13200                 const fp16type  x               (*in[0]);
13201                 const double    d               (x.asDouble());
13202                 int                             e               (0);
13203                 const double    result  (deFrExp(d, &e));
13204
13205                 if (x.isNaN() || x.isInf())
13206                         return false;
13207
13208                 out[0] = fp16type(result).bits();
13209                 min[0] = getMin(result, getULPs(in));
13210                 max[0] = getMax(result, getULPs(in));
13211
13212                 return true;
13213         }
13214 };
13215
13216 struct fp16FrexpE : public fp16PerComponent
13217 {
13218         template<class fp16type>
13219         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13220         {
13221                 const fp16type  x               (*in[0]);
13222                 const double    d               (x.asDouble());
13223                 int                             e               (0);
13224                 const double    dummy   (deFrExp(d, &e));
13225                 const double    result  (static_cast<double>(e));
13226
13227                 DE_UNREF(dummy);
13228
13229                 if (x.isNaN() || x.isInf())
13230                         return false;
13231
13232                 out[0] = fp16type(result).bits();
13233                 min[0] = getMin(result, getULPs(in));
13234                 max[0] = getMax(result, getULPs(in));
13235
13236                 return true;
13237         }
13238 };
13239
13240 struct fp16OpFAdd : public fp16PerComponent
13241 {
13242         template<class fp16type>
13243         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13244         {
13245                 const fp16type  x               (*in[0]);
13246                 const fp16type  y               (*in[1]);
13247                 const double    xd              (x.asDouble());
13248                 const double    yd              (y.asDouble());
13249                 const double    result  (xd + yd);
13250
13251                 out[0] = fp16type(result).bits();
13252                 min[0] = getMin(result, getULPs(in));
13253                 max[0] = getMax(result, getULPs(in));
13254
13255                 return true;
13256         }
13257 };
13258
13259 struct fp16OpFSub : public fp16PerComponent
13260 {
13261         template<class fp16type>
13262         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13263         {
13264                 const fp16type  x               (*in[0]);
13265                 const fp16type  y               (*in[1]);
13266                 const double    xd              (x.asDouble());
13267                 const double    yd              (y.asDouble());
13268                 const double    result  (xd - yd);
13269
13270                 out[0] = fp16type(result).bits();
13271                 min[0] = getMin(result, getULPs(in));
13272                 max[0] = getMax(result, getULPs(in));
13273
13274                 return true;
13275         }
13276 };
13277
13278 struct fp16OpFMul : public fp16PerComponent
13279 {
13280         template<class fp16type>
13281         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13282         {
13283                 const fp16type  x               (*in[0]);
13284                 const fp16type  y               (*in[1]);
13285                 const double    xd              (x.asDouble());
13286                 const double    yd              (y.asDouble());
13287                 const double    result  (xd * yd);
13288
13289                 out[0] = fp16type(result).bits();
13290                 min[0] = getMin(result, getULPs(in));
13291                 max[0] = getMax(result, getULPs(in));
13292
13293                 return true;
13294         }
13295 };
13296
13297 struct fp16OpFDiv : public fp16PerComponent
13298 {
13299         fp16OpFDiv() : fp16PerComponent()
13300         {
13301                 flavorNames.push_back("DirectDiv");
13302                 flavorNames.push_back("InverseDiv");
13303         }
13304
13305         template<class fp16type>
13306         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13307         {
13308                 const fp16type  x                       (*in[0]);
13309                 const fp16type  y                       (*in[1]);
13310                 const double    xd                      (x.asDouble());
13311                 const double    yd                      (y.asDouble());
13312                 const double    unspecUlp       (16.0);
13313                 const double    ulpCnt          (de::inRange(deAbs(yd), deLdExp(1, -14), deLdExp(1, 14)) ? 2.5 : unspecUlp);
13314                 double                  result          (0.0);
13315
13316                 if (y.isZero())
13317                         return false;
13318
13319                 if (getFlavor() == 0)
13320                 {
13321                         result = (xd / yd);
13322                 }
13323                 else if (getFlavor() == 1)
13324                 {
13325                         const double    invyd   (1.0 / yd);
13326                         const fp16type  invy    (invyd);
13327
13328                         result = (xd * invy.asDouble());
13329                 }
13330                 else
13331                 {
13332                         TCU_THROW(InternalError, "Unknown flavor");
13333                 }
13334
13335                 out[0] = fp16type(result).bits();
13336                 min[0] = getMin(result, ulpCnt);
13337                 max[0] = getMax(result, ulpCnt);
13338
13339                 return true;
13340         }
13341 };
13342
13343 struct fp16Atan2 : public fp16PerComponent
13344 {
13345         fp16Atan2() : fp16PerComponent()
13346         {
13347                 flavorNames.push_back("DoubleCalc");
13348                 flavorNames.push_back("DoubleCalc_PI");
13349         }
13350
13351         virtual double getULPs(vector<const deFloat16*>& in)
13352         {
13353                 DE_UNREF(in);
13354
13355                 return 2 * 5.0; // This is not a precision test. Value is not from spec
13356         }
13357
13358         template<class fp16type>
13359         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13360         {
13361                 const fp16type  x               (*in[0]);
13362                 const fp16type  y               (*in[1]);
13363                 const double    xd              (x.asDouble());
13364                 const double    yd              (y.asDouble());
13365                 double                  result  (0.0);
13366
13367                 if (x.isZero() && y.isZero())
13368                         return false;
13369
13370                 if (getFlavor() == 0)
13371                 {
13372                         result  = deAtan2(xd, yd);
13373                 }
13374                 else if (getFlavor() == 1)
13375                 {
13376                         const double    ulps    (2.0 * 5.0); // This is not a precision test. Value is not from spec
13377                         const double    eps             (floatFormat16.ulp(DE_PI_DOUBLE, ulps));
13378
13379                         result  = deAtan2(xd, yd);
13380
13381                         if (de::inRange(deAbs(result), DE_PI_DOUBLE - eps, DE_PI_DOUBLE + eps))
13382                                 result  = -result;
13383                 }
13384                 else
13385                 {
13386                         TCU_THROW(InternalError, "Unknown flavor");
13387                 }
13388
13389                 out[0] = fp16type(result).bits();
13390                 min[0] = getMin(result, getULPs(in));
13391                 max[0] = getMax(result, getULPs(in));
13392
13393                 return true;
13394         }
13395 };
13396
13397 struct fp16Pow : public fp16PerComponent
13398 {
13399         fp16Pow() : fp16PerComponent()
13400         {
13401                 flavorNames.push_back("Pow");
13402                 flavorNames.push_back("PowLog2");
13403                 flavorNames.push_back("PowLog2FP16");
13404         }
13405
13406         template<class fp16type>
13407         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13408         {
13409                 const fp16type  x               (*in[0]);
13410                 const fp16type  y               (*in[1]);
13411                 const double    xd              (x.asDouble());
13412                 const double    yd              (y.asDouble());
13413                 const double    logxeps (de::inRange(deAbs(xd), 0.5, 2.0) ? deLdExp(1.0, -7) : floatFormat16.ulp(deLog2(xd), 3.0));
13414                 const double    ulps1   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) - logxeps)));
13415                 const double    ulps2   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) + logxeps)));
13416                 const double    ulps    (deMax(deAbs(ulps1), deAbs(ulps2)));
13417                 double                  result  (0.0);
13418
13419                 if (xd < 0.0)
13420                         return false;
13421
13422                 if (x.isZero() && yd <= 0.0)
13423                         return false;
13424
13425                 if (getFlavor() == 0)
13426                 {
13427                         result = dePow(xd, yd);
13428                 }
13429                 else if (getFlavor() == 1)
13430                 {
13431                         const double    l2d     (deLog2(xd));
13432                         const double    e2d     (deExp2(yd * l2d));
13433
13434                         result = e2d;
13435                 }
13436                 else if (getFlavor() == 2)
13437                 {
13438                         const double    l2d     (deLog2(xd));
13439                         const fp16type  l2      (l2d);
13440                         const double    e2d     (deExp2(yd * l2.asDouble()));
13441                         const fp16type  e2      (e2d);
13442
13443                         result = e2.asDouble();
13444                 }
13445                 else
13446                 {
13447                         TCU_THROW(InternalError, "Unknown flavor");
13448                 }
13449
13450                 out[0] = fp16type(result).bits();
13451                 min[0] = getMin(result, ulps);
13452                 max[0] = getMax(result, ulps);
13453
13454                 return true;
13455         }
13456 };
13457
13458 struct fp16FMin : public fp16PerComponent
13459 {
13460         template<class fp16type>
13461         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13462         {
13463                 const fp16type  x               (*in[0]);
13464                 const fp16type  y               (*in[1]);
13465                 const double    xd              (x.asDouble());
13466                 const double    yd              (y.asDouble());
13467                 const double    result  (deMin(xd, yd));
13468
13469                 if (x.isNaN() || y.isNaN())
13470                         return false;
13471
13472                 out[0] = fp16type(result).bits();
13473                 min[0] = getMin(result, getULPs(in));
13474                 max[0] = getMax(result, getULPs(in));
13475
13476                 return true;
13477         }
13478 };
13479
13480 struct fp16FMax : public fp16PerComponent
13481 {
13482         template<class fp16type>
13483         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13484         {
13485                 const fp16type  x               (*in[0]);
13486                 const fp16type  y               (*in[1]);
13487                 const double    xd              (x.asDouble());
13488                 const double    yd              (y.asDouble());
13489                 const double    result  (deMax(xd, yd));
13490
13491                 if (x.isNaN() || y.isNaN())
13492                         return false;
13493
13494                 out[0] = fp16type(result).bits();
13495                 min[0] = getMin(result, getULPs(in));
13496                 max[0] = getMax(result, getULPs(in));
13497
13498                 return true;
13499         }
13500 };
13501
13502 struct fp16Step : public fp16PerComponent
13503 {
13504         template<class fp16type>
13505         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13506         {
13507                 const fp16type  edge    (*in[0]);
13508                 const fp16type  x               (*in[1]);
13509                 const double    edged   (edge.asDouble());
13510                 const double    xd              (x.asDouble());
13511                 const double    result  (deStep(edged, xd));
13512
13513                 out[0] = fp16type(result).bits();
13514                 min[0] = getMin(result, getULPs(in));
13515                 max[0] = getMax(result, getULPs(in));
13516
13517                 return true;
13518         }
13519 };
13520
13521 struct fp16Ldexp : public fp16PerComponent
13522 {
13523         template<class fp16type>
13524         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13525         {
13526                 const fp16type  x               (*in[0]);
13527                 const fp16type  y               (*in[1]);
13528                 const double    xd              (x.asDouble());
13529                 const int               yd              (static_cast<int>(deTrunc(y.asDouble())));
13530                 const double    result  (deLdExp(xd, yd));
13531
13532                 if (y.isNaN() || y.isInf() || y.isDenorm() || yd < -14 || yd > 15)
13533                         return false;
13534
13535                 // Spec: "If this product is too large to be represented in the floating-point type, the result is undefined."
13536                 if (fp16type(result).isInf())
13537                         return false;
13538
13539                 out[0] = fp16type(result).bits();
13540                 min[0] = getMin(result, getULPs(in));
13541                 max[0] = getMax(result, getULPs(in));
13542
13543                 return true;
13544         }
13545 };
13546
13547 struct fp16FClamp : public fp16PerComponent
13548 {
13549         template<class fp16type>
13550         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13551         {
13552                 const fp16type  x               (*in[0]);
13553                 const fp16type  minVal  (*in[1]);
13554                 const fp16type  maxVal  (*in[2]);
13555                 const double    xd              (x.asDouble());
13556                 const double    minVald (minVal.asDouble());
13557                 const double    maxVald (maxVal.asDouble());
13558                 const double    result  (deClamp(xd, minVald, maxVald));
13559
13560                 if (minVal.isNaN() || maxVal.isNaN() || minVald > maxVald)
13561                         return false;
13562
13563                 out[0] = fp16type(result).bits();
13564                 min[0] = getMin(result, getULPs(in));
13565                 max[0] = getMax(result, getULPs(in));
13566
13567                 return true;
13568         }
13569 };
13570
13571 struct fp16FMix : public fp16PerComponent
13572 {
13573         fp16FMix() : fp16PerComponent()
13574         {
13575                 flavorNames.push_back("DoubleCalc");
13576                 flavorNames.push_back("EmulatingFP16");
13577                 flavorNames.push_back("EmulatingFP16YminusX");
13578         }
13579
13580         template<class fp16type>
13581         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13582         {
13583                 const fp16type  x               (*in[0]);
13584                 const fp16type  y               (*in[1]);
13585                 const fp16type  a               (*in[2]);
13586                 const double    ulps    (8.0); // This is not a precision test. Value is not from spec
13587                 double                  result  (0.0);
13588
13589                 if (getFlavor() == 0)
13590                 {
13591                         const double    xd              (x.asDouble());
13592                         const double    yd              (y.asDouble());
13593                         const double    ad              (a.asDouble());
13594                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13595                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13596                         const double    eps             (xeps + yeps);
13597
13598                         result = deMix(xd, yd, ad);
13599                         min[0] = result - eps;
13600                         max[0] = result + eps;
13601                 }
13602                 else if (getFlavor() == 1)
13603                 {
13604                         const double    xd              (x.asDouble());
13605                         const double    yd              (y.asDouble());
13606                         const double    ad              (a.asDouble());
13607                         const fp16type  am              (1.0 - ad);
13608                         const double    amd             (am.asDouble());
13609                         const fp16type  xam             (xd * amd);
13610                         const double    xamd    (xam.asDouble());
13611                         const fp16type  ya              (yd * ad);
13612                         const double    yad             (ya.asDouble());
13613                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13614                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13615                         const double    eps             (xeps + yeps);
13616
13617                         result = xamd + yad;
13618                         min[0] = result - eps;
13619                         max[0] = result + eps;
13620                 }
13621                 else if (getFlavor() == 2)
13622                 {
13623                         const double    xd              (x.asDouble());
13624                         const double    yd              (y.asDouble());
13625                         const double    ad              (a.asDouble());
13626                         const fp16type  ymx             (yd - xd);
13627                         const double    ymxd    (ymx.asDouble());
13628                         const fp16type  ymxa    (ymxd * ad);
13629                         const double    ymxad   (ymxa.asDouble());
13630                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13631                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13632                         const double    eps             (xeps + yeps);
13633
13634                         result = xd + ymxad;
13635                         min[0] = result - eps;
13636                         max[0] = result + eps;
13637                 }
13638                 else
13639                 {
13640                         TCU_THROW(InternalError, "Unknown flavor");
13641                 }
13642
13643                 out[0] = fp16type(result).bits();
13644
13645                 return true;
13646         }
13647 };
13648
13649 struct fp16SmoothStep : public fp16PerComponent
13650 {
13651         fp16SmoothStep() : fp16PerComponent()
13652         {
13653                 flavorNames.push_back("FloatCalc");
13654                 flavorNames.push_back("EmulatingFP16");
13655                 flavorNames.push_back("EmulatingFP16WClamp");
13656         }
13657
13658         virtual double getULPs(vector<const deFloat16*>& in)
13659         {
13660                 DE_UNREF(in);
13661
13662                 return 4.0; // This is not a precision test. Value is not from spec
13663         }
13664
13665         template<class fp16type>
13666         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13667         {
13668                 const fp16type  edge0   (*in[0]);
13669                 const fp16type  edge1   (*in[1]);
13670                 const fp16type  x               (*in[2]);
13671                 double                  result  (0.0);
13672
13673                 if (edge0.isNaN() || edge1.isNaN() || x.isNaN() || edge0.asDouble() >= edge1.asDouble())
13674                         return false;
13675
13676                 if (edge0.isInf() || edge1.isInf() || x.isInf())
13677                         return false;
13678
13679                 if (getFlavor() == 0)
13680                 {
13681                         const float     edge0d  (edge0.asFloat());
13682                         const float     edge1d  (edge1.asFloat());
13683                         const float     xd              (x.asFloat());
13684                         const float     sstep   (deFloatSmoothStep(edge0d, edge1d, xd));
13685
13686                         result = sstep;
13687                 }
13688                 else if (getFlavor() == 1)
13689                 {
13690                         const double    edge0d  (edge0.asDouble());
13691                         const double    edge1d  (edge1.asDouble());
13692                         const double    xd              (x.asDouble());
13693
13694                         if (xd <= edge0d)
13695                                 result = 0.0;
13696                         else if (xd >= edge1d)
13697                                 result = 1.0;
13698                         else
13699                         {
13700                                 const fp16type  a       (xd - edge0d);
13701                                 const fp16type  b       (edge1d - edge0d);
13702                                 const fp16type  t       (a.asDouble() / b.asDouble());
13703                                 const fp16type  t2      (2.0 * t.asDouble());
13704                                 const fp16type  t3      (3.0 - t2.asDouble());
13705                                 const fp16type  t4      (t.asDouble() * t3.asDouble());
13706                                 const fp16type  t5      (t.asDouble() * t4.asDouble());
13707
13708                                 result = t5.asDouble();
13709                         }
13710                 }
13711                 else if (getFlavor() == 2)
13712                 {
13713                         const double    edge0d  (edge0.asDouble());
13714                         const double    edge1d  (edge1.asDouble());
13715                         const double    xd              (x.asDouble());
13716                         const fp16type  a       (xd - edge0d);
13717                         const fp16type  b       (edge1d - edge0d);
13718                         const fp16type  bi      (1.0 / b.asDouble());
13719                         const fp16type  t0      (a.asDouble() * bi.asDouble());
13720                         const double    tc      (deClamp(t0.asDouble(), 0.0, 1.0));
13721                         const fp16type  t       (tc);
13722                         const fp16type  t2      (2.0 * t.asDouble());
13723                         const fp16type  t3      (3.0 - t2.asDouble());
13724                         const fp16type  t4      (t.asDouble() * t3.asDouble());
13725                         const fp16type  t5      (t.asDouble() * t4.asDouble());
13726
13727                         result = t5.asDouble();
13728                 }
13729                 else
13730                 {
13731                         TCU_THROW(InternalError, "Unknown flavor");
13732                 }
13733
13734                 out[0] = fp16type(result).bits();
13735                 min[0] = getMin(result, getULPs(in));
13736                 max[0] = getMax(result, getULPs(in));
13737
13738                 return true;
13739         }
13740 };
13741
13742 struct fp16Fma : public fp16PerComponent
13743 {
13744         virtual double getULPs(vector<const deFloat16*>& in)
13745         {
13746                 DE_UNREF(in);
13747
13748                 return 16.0;
13749         }
13750
13751         template<class fp16type>
13752         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13753         {
13754                 DE_ASSERT(in.size() == 3);
13755                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13756                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
13757                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
13758                 DE_ASSERT(getOutCompCount() > 0);
13759
13760                 const fp16type  a               (*in[0]);
13761                 const fp16type  b               (*in[1]);
13762                 const fp16type  c               (*in[2]);
13763                 const double    ad              (a.asDouble());
13764                 const double    bd              (b.asDouble());
13765                 const double    cd              (c.asDouble());
13766                 const double    result  (deMadd(ad, bd, cd));
13767
13768                 out[0] = fp16type(result).bits();
13769                 min[0] = getMin(result, getULPs(in));
13770                 max[0] = getMax(result, getULPs(in));
13771
13772                 return true;
13773         }
13774 };
13775
13776
13777 struct fp16AllComponents : public fp16PerComponent
13778 {
13779         bool            callOncePerComponent    ()      { return false; }
13780 };
13781
13782 struct fp16Length : public fp16AllComponents
13783 {
13784         fp16Length() : fp16AllComponents()
13785         {
13786                 flavorNames.push_back("EmulatingFP16");
13787                 flavorNames.push_back("DoubleCalc");
13788         }
13789
13790         virtual double getULPs(vector<const deFloat16*>& in)
13791         {
13792                 DE_UNREF(in);
13793
13794                 return 4.0;
13795         }
13796
13797         template<class fp16type>
13798         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13799         {
13800                 DE_ASSERT(getOutCompCount() == 1);
13801                 DE_ASSERT(in.size() == 1);
13802
13803                 double  result  (0.0);
13804
13805                 if (getFlavor() == 0)
13806                 {
13807                         fp16type        r       (0.0);
13808
13809                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13810                         {
13811                                 const fp16type  x       (in[0][componentNdx]);
13812                                 const fp16type  q       (x.asDouble() * x.asDouble());
13813
13814                                 r = fp16type(r.asDouble() + q.asDouble());
13815                         }
13816
13817                         result = deSqrt(r.asDouble());
13818
13819                         out[0] = fp16type(result).bits();
13820                 }
13821                 else if (getFlavor() == 1)
13822                 {
13823                         double  r       (0.0);
13824
13825                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13826                         {
13827                                 const fp16type  x       (in[0][componentNdx]);
13828                                 const double    q       (x.asDouble() * x.asDouble());
13829
13830                                 r += q;
13831                         }
13832
13833                         result = deSqrt(r);
13834
13835                         out[0] = fp16type(result).bits();
13836                 }
13837                 else
13838                 {
13839                         TCU_THROW(InternalError, "Unknown flavor");
13840                 }
13841
13842                 min[0] = getMin(result, getULPs(in));
13843                 max[0] = getMax(result, getULPs(in));
13844
13845                 return true;
13846         }
13847 };
13848
13849 struct fp16Distance : public fp16AllComponents
13850 {
13851         fp16Distance() : fp16AllComponents()
13852         {
13853                 flavorNames.push_back("EmulatingFP16");
13854                 flavorNames.push_back("DoubleCalc");
13855         }
13856
13857         virtual double getULPs(vector<const deFloat16*>& in)
13858         {
13859                 DE_UNREF(in);
13860
13861                 return 4.0;
13862         }
13863
13864         template<class fp16type>
13865         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13866         {
13867                 DE_ASSERT(getOutCompCount() == 1);
13868                 DE_ASSERT(in.size() == 2);
13869                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
13870
13871                 double  result  (0.0);
13872
13873                 if (getFlavor() == 0)
13874                 {
13875                         fp16type        r       (0.0);
13876
13877                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13878                         {
13879                                 const fp16type  x       (in[0][componentNdx]);
13880                                 const fp16type  y       (in[1][componentNdx]);
13881                                 const fp16type  d       (x.asDouble() - y.asDouble());
13882                                 const fp16type  q       (d.asDouble() * d.asDouble());
13883
13884                                 r = fp16type(r.asDouble() + q.asDouble());
13885                         }
13886
13887                         result = deSqrt(r.asDouble());
13888                 }
13889                 else if (getFlavor() == 1)
13890                 {
13891                         double  r       (0.0);
13892
13893                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13894                         {
13895                                 const fp16type  x       (in[0][componentNdx]);
13896                                 const fp16type  y       (in[1][componentNdx]);
13897                                 const double    d       (x.asDouble() - y.asDouble());
13898                                 const double    q       (d * d);
13899
13900                                 r += q;
13901                         }
13902
13903                         result = deSqrt(r);
13904                 }
13905                 else
13906                 {
13907                         TCU_THROW(InternalError, "Unknown flavor");
13908                 }
13909
13910                 out[0] = fp16type(result).bits();
13911                 min[0] = getMin(result, getULPs(in));
13912                 max[0] = getMax(result, getULPs(in));
13913
13914                 return true;
13915         }
13916 };
13917
13918 struct fp16Cross : public fp16AllComponents
13919 {
13920         fp16Cross() : fp16AllComponents()
13921         {
13922                 flavorNames.push_back("EmulatingFP16");
13923                 flavorNames.push_back("DoubleCalc");
13924         }
13925
13926         virtual double getULPs(vector<const deFloat16*>& in)
13927         {
13928                 DE_UNREF(in);
13929
13930                 return 4.0;
13931         }
13932
13933         template<class fp16type>
13934         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13935         {
13936                 DE_ASSERT(getOutCompCount() == 3);
13937                 DE_ASSERT(in.size() == 2);
13938                 DE_ASSERT(getArgCompCount(0) == 3);
13939                 DE_ASSERT(getArgCompCount(1) == 3);
13940
13941                 if (getFlavor() == 0)
13942                 {
13943                         const fp16type  x0              (in[0][0]);
13944                         const fp16type  x1              (in[0][1]);
13945                         const fp16type  x2              (in[0][2]);
13946                         const fp16type  y0              (in[1][0]);
13947                         const fp16type  y1              (in[1][1]);
13948                         const fp16type  y2              (in[1][2]);
13949                         const fp16type  x1y2    (x1.asDouble() * y2.asDouble());
13950                         const fp16type  y1x2    (y1.asDouble() * x2.asDouble());
13951                         const fp16type  x2y0    (x2.asDouble() * y0.asDouble());
13952                         const fp16type  y2x0    (y2.asDouble() * x0.asDouble());
13953                         const fp16type  x0y1    (x0.asDouble() * y1.asDouble());
13954                         const fp16type  y0x1    (y0.asDouble() * x1.asDouble());
13955
13956                         out[0] = fp16type(x1y2.asDouble() - y1x2.asDouble()).bits();
13957                         out[1] = fp16type(x2y0.asDouble() - y2x0.asDouble()).bits();
13958                         out[2] = fp16type(x0y1.asDouble() - y0x1.asDouble()).bits();
13959                 }
13960                 else if (getFlavor() == 1)
13961                 {
13962                         const fp16type  x0              (in[0][0]);
13963                         const fp16type  x1              (in[0][1]);
13964                         const fp16type  x2              (in[0][2]);
13965                         const fp16type  y0              (in[1][0]);
13966                         const fp16type  y1              (in[1][1]);
13967                         const fp16type  y2              (in[1][2]);
13968                         const double    x1y2    (x1.asDouble() * y2.asDouble());
13969                         const double    y1x2    (y1.asDouble() * x2.asDouble());
13970                         const double    x2y0    (x2.asDouble() * y0.asDouble());
13971                         const double    y2x0    (y2.asDouble() * x0.asDouble());
13972                         const double    x0y1    (x0.asDouble() * y1.asDouble());
13973                         const double    y0x1    (y0.asDouble() * x1.asDouble());
13974
13975                         out[0] = fp16type(x1y2 - y1x2).bits();
13976                         out[1] = fp16type(x2y0 - y2x0).bits();
13977                         out[2] = fp16type(x0y1 - y0x1).bits();
13978                 }
13979                 else
13980                 {
13981                         TCU_THROW(InternalError, "Unknown flavor");
13982                 }
13983
13984                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
13985                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
13986                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
13987                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
13988
13989                 return true;
13990         }
13991 };
13992
13993 struct fp16Normalize : public fp16AllComponents
13994 {
13995         fp16Normalize() : fp16AllComponents()
13996         {
13997                 flavorNames.push_back("EmulatingFP16");
13998                 flavorNames.push_back("DoubleCalc");
13999
14000                 // flavorNames will be extended later
14001         }
14002
14003         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14004         {
14005                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14006
14007                 if (argNo == 0 && argCompCount[argNo] == 0)
14008                 {
14009                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14010                         std::vector<int>        indices;
14011
14012                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14013                                 indices.push_back(static_cast<int>(componentNdx));
14014
14015                         m_permutations.reserve(maxPermutationsCount);
14016
14017                         permutationsFlavorStart = flavorNames.size();
14018
14019                         do
14020                         {
14021                                 tcu::UVec4      permutation;
14022                                 std::string     name            = "Permutted_";
14023
14024                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14025                                 {
14026                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14027                                         name += de::toString(indices[componentNdx]);
14028                                 }
14029
14030                                 m_permutations.push_back(permutation);
14031                                 flavorNames.push_back(name);
14032
14033                         } while(std::next_permutation(indices.begin(), indices.end()));
14034
14035                         permutationsFlavorEnd = flavorNames.size();
14036                 }
14037
14038                 fp16AllComponents::setArgCompCount(argNo, compCount);
14039         }
14040         virtual double getULPs(vector<const deFloat16*>& in)
14041         {
14042                 DE_UNREF(in);
14043
14044                 return 8.0;
14045         }
14046
14047         template<class fp16type>
14048         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14049         {
14050                 DE_ASSERT(in.size() == 1);
14051                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14052
14053                 if (getFlavor() == 0)
14054                 {
14055                         fp16type        r(0.0);
14056
14057                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14058                         {
14059                                 const fp16type  x       (in[0][componentNdx]);
14060                                 const fp16type  q       (x.asDouble() * x.asDouble());
14061
14062                                 r = fp16type(r.asDouble() + q.asDouble());
14063                         }
14064
14065                         r = fp16type(deSqrt(r.asDouble()));
14066
14067                         if (r.isZero())
14068                                 return false;
14069
14070                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14071                         {
14072                                 const fp16type  x       (in[0][componentNdx]);
14073
14074                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14075                         }
14076                 }
14077                 else if (getFlavor() == 1)
14078                 {
14079                         double  r(0.0);
14080
14081                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14082                         {
14083                                 const fp16type  x       (in[0][componentNdx]);
14084                                 const double    q       (x.asDouble() * x.asDouble());
14085
14086                                 r += q;
14087                         }
14088
14089                         r = deSqrt(r);
14090
14091                         if (r == 0)
14092                                 return false;
14093
14094                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14095                         {
14096                                 const fp16type  x       (in[0][componentNdx]);
14097
14098                                 out[componentNdx] = fp16type(x.asDouble() / r).bits();
14099                         }
14100                 }
14101                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14102                 {
14103                         const int                       compCount               (static_cast<int>(getArgCompCount(0)));
14104                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14105                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14106                         fp16type                        r                               (0.0);
14107
14108                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14109                         {
14110                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14111                                 const fp16type  x                               (in[0][componentNdx]);
14112                                 const fp16type  q                               (x.asDouble() * x.asDouble());
14113
14114                                 r = fp16type(r.asDouble() + q.asDouble());
14115                         }
14116
14117                         r = fp16type(deSqrt(r.asDouble()));
14118
14119                         if (r.isZero())
14120                                 return false;
14121
14122                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14123                         {
14124                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14125                                 const fp16type  x                               (in[0][componentNdx]);
14126
14127                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14128                         }
14129                 }
14130                 else
14131                 {
14132                         TCU_THROW(InternalError, "Unknown flavor");
14133                 }
14134
14135                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14136                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14137                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14138                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14139
14140                 return true;
14141         }
14142
14143 private:
14144         std::vector<tcu::UVec4> m_permutations;
14145         size_t                                  permutationsFlavorStart;
14146         size_t                                  permutationsFlavorEnd;
14147 };
14148
14149 struct fp16FaceForward : public fp16AllComponents
14150 {
14151         virtual double getULPs(vector<const deFloat16*>& in)
14152         {
14153                 DE_UNREF(in);
14154
14155                 return 4.0;
14156         }
14157
14158         template<class fp16type>
14159         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14160         {
14161                 DE_ASSERT(in.size() == 3);
14162                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14163                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14164                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
14165
14166                 fp16type        dp(0.0);
14167
14168                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14169                 {
14170                         const fp16type  x       (in[1][componentNdx]);
14171                         const fp16type  y       (in[2][componentNdx]);
14172                         const double    xd      (x.asDouble());
14173                         const double    yd      (y.asDouble());
14174                         const fp16type  q       (xd * yd);
14175
14176                         dp = fp16type(dp.asDouble() + q.asDouble());
14177                 }
14178
14179                 if (dp.isNaN() || dp.isZero())
14180                         return false;
14181
14182                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14183                 {
14184                         const fp16type  n       (in[0][componentNdx]);
14185
14186                         out[componentNdx] = (dp.signBit() == 1) ? n.bits() : fp16type(-n.asDouble()).bits();
14187                 }
14188
14189                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14190                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14191                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14192                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14193
14194                 return true;
14195         }
14196 };
14197
14198 struct fp16Reflect : public fp16AllComponents
14199 {
14200         fp16Reflect() : fp16AllComponents()
14201         {
14202                 flavorNames.push_back("EmulatingFP16");
14203                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14204                 flavorNames.push_back("FloatCalc");
14205                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14206                 flavorNames.push_back("EmulatingFP16+2Nfirst");
14207                 flavorNames.push_back("EmulatingFP16+2Ifirst");
14208         }
14209
14210         virtual double getULPs(vector<const deFloat16*>& in)
14211         {
14212                 DE_UNREF(in);
14213
14214                 return 256.0; // This is not a precision test. Value is not from spec
14215         }
14216
14217         template<class fp16type>
14218         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14219         {
14220                 DE_ASSERT(in.size() == 2);
14221                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14222                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14223
14224                 if (getFlavor() < 4)
14225                 {
14226                         const bool      keepZeroSign    ((flavor & 1) != 0 ? true : false);
14227                         const bool      floatCalc               ((flavor & 2) != 0 ? true : false);
14228
14229                         if (floatCalc)
14230                         {
14231                                 float   dp(0.0f);
14232
14233                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14234                                 {
14235                                         const fp16type  i       (in[0][componentNdx]);
14236                                         const fp16type  n       (in[1][componentNdx]);
14237                                         const float             id      (i.asFloat());
14238                                         const float             nd      (n.asFloat());
14239                                         const float             qd      (id * nd);
14240
14241                                         if (keepZeroSign)
14242                                                 dp = (componentNdx == 0) ? qd : dp + qd;
14243                                         else
14244                                                 dp = dp + qd;
14245                                 }
14246
14247                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14248                                 {
14249                                         const fp16type  i               (in[0][componentNdx]);
14250                                         const fp16type  n               (in[1][componentNdx]);
14251                                         const float             dpnd    (dp * n.asFloat());
14252                                         const float             dpn2d   (2.0f * dpnd);
14253                                         const float             idpn2d  (i.asFloat() - dpn2d);
14254                                         const fp16type  result  (idpn2d);
14255
14256                                         out[componentNdx] = result.bits();
14257                                 }
14258                         }
14259                         else
14260                         {
14261                                 fp16type        dp(0.0);
14262
14263                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14264                                 {
14265                                         const fp16type  i       (in[0][componentNdx]);
14266                                         const fp16type  n       (in[1][componentNdx]);
14267                                         const double    id      (i.asDouble());
14268                                         const double    nd      (n.asDouble());
14269                                         const fp16type  q       (id * nd);
14270
14271                                         if (keepZeroSign)
14272                                                 dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14273                                         else
14274                                                 dp = fp16type(dp.asDouble() + q.asDouble());
14275                                 }
14276
14277                                 if (dp.isNaN())
14278                                         return false;
14279
14280                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14281                                 {
14282                                         const fp16type  i               (in[0][componentNdx]);
14283                                         const fp16type  n               (in[1][componentNdx]);
14284                                         const fp16type  dpn             (dp.asDouble() * n.asDouble());
14285                                         const fp16type  dpn2    (2 * dpn.asDouble());
14286                                         const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14287
14288                                         out[componentNdx] = idpn2.bits();
14289                                 }
14290                         }
14291                 }
14292                 else if (getFlavor() == 4)
14293                 {
14294                         fp16type        dp(0.0);
14295
14296                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14297                         {
14298                                 const fp16type  i       (in[0][componentNdx]);
14299                                 const fp16type  n       (in[1][componentNdx]);
14300                                 const double    id      (i.asDouble());
14301                                 const double    nd      (n.asDouble());
14302                                 const fp16type  q       (id * nd);
14303
14304                                 dp = fp16type(dp.asDouble() + q.asDouble());
14305                         }
14306
14307                         if (dp.isNaN())
14308                                 return false;
14309
14310                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14311                         {
14312                                 const fp16type  i               (in[0][componentNdx]);
14313                                 const fp16type  n               (in[1][componentNdx]);
14314                                 const fp16type  n2              (2 * n.asDouble());
14315                                 const fp16type  dpn2    (dp.asDouble() * n2.asDouble());
14316                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14317
14318                                 out[componentNdx] = idpn2.bits();
14319                         }
14320                 }
14321                 else if (getFlavor() == 5)
14322                 {
14323                         fp16type        dp2(0.0);
14324
14325                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14326                         {
14327                                 const fp16type  i       (in[0][componentNdx]);
14328                                 const fp16type  n       (in[1][componentNdx]);
14329                                 const fp16type  i2      (2.0 * i.asDouble());
14330                                 const double    i2d     (i2.asDouble());
14331                                 const double    nd      (n.asDouble());
14332                                 const fp16type  q       (i2d * nd);
14333
14334                                 dp2 = fp16type(dp2.asDouble() + q.asDouble());
14335                         }
14336
14337                         if (dp2.isNaN())
14338                                 return false;
14339
14340                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14341                         {
14342                                 const fp16type  i               (in[0][componentNdx]);
14343                                 const fp16type  n               (in[1][componentNdx]);
14344                                 const fp16type  dpn2    (dp2.asDouble() * n.asDouble());
14345                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14346
14347                                 out[componentNdx] = idpn2.bits();
14348                         }
14349                 }
14350                 else
14351                 {
14352                         TCU_THROW(InternalError, "Unknown flavor");
14353                 }
14354
14355                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14356                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14357                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14358                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14359
14360                 return true;
14361         }
14362 };
14363
14364 struct fp16Refract : public fp16AllComponents
14365 {
14366         fp16Refract() : fp16AllComponents()
14367         {
14368                 flavorNames.push_back("EmulatingFP16");
14369                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14370                 flavorNames.push_back("FloatCalc");
14371                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14372         }
14373
14374         virtual double getULPs(vector<const deFloat16*>& in)
14375         {
14376                 DE_UNREF(in);
14377
14378                 return 8192.0; // This is not a precision test. Value is not from spec
14379         }
14380
14381         template<class fp16type>
14382         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14383         {
14384                 DE_ASSERT(in.size() == 3);
14385                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14386                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14387                 DE_ASSERT(getArgCompCount(2) == 1);
14388
14389                 const bool              keepZeroSign    ((flavor & 1) != 0 ? true : false);
14390                 const bool              doubleCalc              ((flavor & 2) != 0 ? true : false);
14391                 const fp16type  eta                             (*in[2]);
14392
14393                 if (doubleCalc)
14394                 {
14395                         double  dp      (0.0);
14396
14397                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14398                         {
14399                                 const fp16type  i       (in[0][componentNdx]);
14400                                 const fp16type  n       (in[1][componentNdx]);
14401                                 const double    id      (i.asDouble());
14402                                 const double    nd      (n.asDouble());
14403                                 const double    qd      (id * nd);
14404
14405                                 if (keepZeroSign)
14406                                         dp = (componentNdx == 0) ? qd : dp + qd;
14407                                 else
14408                                         dp = dp + qd;
14409                         }
14410
14411                         const double    eta2    (eta.asDouble() * eta.asDouble());
14412                         const double    dp2             (dp * dp);
14413                         const double    dp1             (1.0 - dp2);
14414                         const double    dpe             (eta2 * dp1);
14415                         const double    k               (1.0 - dpe);
14416
14417                         if (k < 0.0)
14418                         {
14419                                 const fp16type  zero    (0.0);
14420
14421                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14422                                         out[componentNdx] = zero.bits();
14423                         }
14424                         else
14425                         {
14426                                 const double    sk      (deSqrt(k));
14427
14428                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14429                                 {
14430                                         const fp16type  i               (in[0][componentNdx]);
14431                                         const fp16type  n               (in[1][componentNdx]);
14432                                         const double    etai    (i.asDouble() * eta.asDouble());
14433                                         const double    etadp   (eta.asDouble() * dp);
14434                                         const double    etadpk  (etadp + sk);
14435                                         const double    etadpkn (etadpk * n.asDouble());
14436                                         const double    full    (etai - etadpkn);
14437                                         const fp16type  result  (full);
14438
14439                                         if (result.isInf())
14440                                                 return false;
14441
14442                                         out[componentNdx] = result.bits();
14443                                 }
14444                         }
14445                 }
14446                 else
14447                 {
14448                         fp16type        dp      (0.0);
14449
14450                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14451                         {
14452                                 const fp16type  i       (in[0][componentNdx]);
14453                                 const fp16type  n       (in[1][componentNdx]);
14454                                 const double    id      (i.asDouble());
14455                                 const double    nd      (n.asDouble());
14456                                 const fp16type  q       (id * nd);
14457
14458                                 if (keepZeroSign)
14459                                         dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14460                                 else
14461                                         dp = fp16type(dp.asDouble() + q.asDouble());
14462                         }
14463
14464                         if (dp.isNaN())
14465                                 return false;
14466
14467                         const fp16type  eta2(eta.asDouble() * eta.asDouble());
14468                         const fp16type  dp2     (dp.asDouble() * dp.asDouble());
14469                         const fp16type  dp1     (1.0 - dp2.asDouble());
14470                         const fp16type  dpe     (eta2.asDouble() * dp1.asDouble());
14471                         const fp16type  k       (1.0 - dpe.asDouble());
14472
14473                         if (k.asDouble() < 0.0)
14474                         {
14475                                 const fp16type  zero    (0.0);
14476
14477                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14478                                         out[componentNdx] = zero.bits();
14479                         }
14480                         else
14481                         {
14482                                 const fp16type  sk      (deSqrt(k.asDouble()));
14483
14484                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14485                                 {
14486                                         const fp16type  i               (in[0][componentNdx]);
14487                                         const fp16type  n               (in[1][componentNdx]);
14488                                         const fp16type  etai    (i.asDouble() * eta.asDouble());
14489                                         const fp16type  etadp   (eta.asDouble() * dp.asDouble());
14490                                         const fp16type  etadpk  (etadp.asDouble() + sk.asDouble());
14491                                         const fp16type  etadpkn (etadpk.asDouble() * n.asDouble());
14492                                         const fp16type  full    (etai.asDouble() - etadpkn.asDouble());
14493
14494                                         if (full.isNaN() || full.isInf())
14495                                                 return false;
14496
14497                                         out[componentNdx] = full.bits();
14498                                 }
14499                         }
14500                 }
14501
14502                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14503                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14504                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14505                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14506
14507                 return true;
14508         }
14509 };
14510
14511 struct fp16Dot : public fp16AllComponents
14512 {
14513         fp16Dot() : fp16AllComponents()
14514         {
14515                 flavorNames.push_back("EmulatingFP16");
14516                 flavorNames.push_back("FloatCalc");
14517                 flavorNames.push_back("DoubleCalc");
14518
14519                 // flavorNames will be extended later
14520         }
14521
14522         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14523         {
14524                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14525
14526                 if (argNo == 0 && argCompCount[argNo] == 0)
14527                 {
14528                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14529                         std::vector<int>        indices;
14530
14531                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14532                                 indices.push_back(static_cast<int>(componentNdx));
14533
14534                         m_permutations.reserve(maxPermutationsCount);
14535
14536                         permutationsFlavorStart = flavorNames.size();
14537
14538                         do
14539                         {
14540                                 tcu::UVec4      permutation;
14541                                 std::string     name            = "Permutted_";
14542
14543                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14544                                 {
14545                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14546                                         name += de::toString(indices[componentNdx]);
14547                                 }
14548
14549                                 m_permutations.push_back(permutation);
14550                                 flavorNames.push_back(name);
14551
14552                         } while(std::next_permutation(indices.begin(), indices.end()));
14553
14554                         permutationsFlavorEnd = flavorNames.size();
14555                 }
14556
14557                 fp16AllComponents::setArgCompCount(argNo, compCount);
14558         }
14559
14560         virtual double  getULPs(vector<const deFloat16*>& in)
14561         {
14562                 DE_UNREF(in);
14563
14564                 return 16.0; // This is not a precision test. Value is not from spec
14565         }
14566
14567         template<class fp16type>
14568         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14569         {
14570                 DE_ASSERT(in.size() == 2);
14571                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
14572                 DE_ASSERT(getOutCompCount() == 1);
14573
14574                 double  result  (0.0);
14575                 double  eps             (0.0);
14576
14577                 if (getFlavor() == 0)
14578                 {
14579                         fp16type        dp      (0.0);
14580
14581                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14582                         {
14583                                 const fp16type  x       (in[0][componentNdx]);
14584                                 const fp16type  y       (in[1][componentNdx]);
14585                                 const fp16type  q       (x.asDouble() * y.asDouble());
14586
14587                                 dp = fp16type(dp.asDouble() + q.asDouble());
14588                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14589                         }
14590
14591                         result = dp.asDouble();
14592                 }
14593                 else if (getFlavor() == 1)
14594                 {
14595                         float   dp      (0.0);
14596
14597                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14598                         {
14599                                 const fp16type  x       (in[0][componentNdx]);
14600                                 const fp16type  y       (in[1][componentNdx]);
14601                                 const float             q       (x.asFloat() * y.asFloat());
14602
14603                                 dp += q;
14604                                 eps += floatFormat16.ulp(static_cast<double>(q), 2.0);
14605                         }
14606
14607                         result = dp;
14608                 }
14609                 else if (getFlavor() == 2)
14610                 {
14611                         double  dp      (0.0);
14612
14613                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14614                         {
14615                                 const fp16type  x       (in[0][componentNdx]);
14616                                 const fp16type  y       (in[1][componentNdx]);
14617                                 const double    q       (x.asDouble() * y.asDouble());
14618
14619                                 dp += q;
14620                                 eps += floatFormat16.ulp(q, 2.0);
14621                         }
14622
14623                         result = dp;
14624                 }
14625                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14626                 {
14627                         const int                       compCount               (static_cast<int>(getArgCompCount(1)));
14628                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14629                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14630                         fp16type                        dp                              (0.0);
14631
14632                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14633                         {
14634                                 const size_t            componentNdx    (permutation[permComponentNdx]);
14635                                 const fp16type          x                               (in[0][componentNdx]);
14636                                 const fp16type          y                               (in[1][componentNdx]);
14637                                 const fp16type          q                               (x.asDouble() * y.asDouble());
14638
14639                                 dp = fp16type(dp.asDouble() + q.asDouble());
14640                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14641                         }
14642
14643                         result = dp.asDouble();
14644                 }
14645                 else
14646                 {
14647                         TCU_THROW(InternalError, "Unknown flavor");
14648                 }
14649
14650                 out[0] = fp16type(result).bits();
14651                 min[0] = result - eps;
14652                 max[0] = result + eps;
14653
14654                 return true;
14655         }
14656
14657 private:
14658         std::vector<tcu::UVec4> m_permutations;
14659         size_t                                  permutationsFlavorStart;
14660         size_t                                  permutationsFlavorEnd;
14661 };
14662
14663 struct fp16VectorTimesScalar : public fp16AllComponents
14664 {
14665         virtual double getULPs(vector<const deFloat16*>& in)
14666         {
14667                 DE_UNREF(in);
14668
14669                 return 2.0;
14670         }
14671
14672         template<class fp16type>
14673         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14674         {
14675                 DE_ASSERT(in.size() == 2);
14676                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14677                 DE_ASSERT(getArgCompCount(1) == 1);
14678
14679                 fp16type        s       (*in[1]);
14680
14681                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14682                 {
14683                         const fp16type  x          (in[0][componentNdx]);
14684                         const double    result (s.asDouble() * x.asDouble());
14685                         const fp16type  m          (result);
14686
14687                         out[componentNdx] = m.bits();
14688                         min[componentNdx] = getMin(result, getULPs(in));
14689                         max[componentNdx] = getMax(result, getULPs(in));
14690                 }
14691
14692                 return true;
14693         }
14694 };
14695
14696 struct fp16MatrixBase : public fp16AllComponents
14697 {
14698         deUint32                getComponentValidity                    ()
14699         {
14700                 return static_cast<deUint32>(-1);
14701         }
14702
14703         inline size_t   getNdx                                                  (const size_t rowCount, const size_t col, const size_t row)
14704         {
14705                 const size_t minComponentCount  = 0;
14706                 const size_t maxComponentCount  = 3;
14707                 const size_t alignedRowsCount   = (rowCount == 3) ? 4 : rowCount;
14708
14709                 DE_ASSERT(de::inRange(rowCount, minComponentCount + 1, maxComponentCount + 1));
14710                 DE_ASSERT(de::inRange(col, minComponentCount, maxComponentCount));
14711                 DE_ASSERT(de::inBounds(row, minComponentCount, rowCount));
14712                 DE_UNREF(minComponentCount);
14713                 DE_UNREF(maxComponentCount);
14714
14715                 return col * alignedRowsCount + row;
14716         }
14717
14718         deUint32                getComponentMatrixValidityMask  (size_t cols, size_t rows)
14719         {
14720                 deUint32        result  = 0u;
14721
14722                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14723                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14724                         {
14725                                 const size_t bitNdx = getNdx(rows, colNdx, rowNdx);
14726
14727                                 DE_ASSERT(bitNdx < sizeof(result) * 8);
14728
14729                                 result |= (1<<bitNdx);
14730                         }
14731
14732                 return result;
14733         }
14734 };
14735
14736 template<size_t cols, size_t rows>
14737 struct fp16Transpose : public fp16MatrixBase
14738 {
14739         virtual double getULPs(vector<const deFloat16*>& in)
14740         {
14741                 DE_UNREF(in);
14742
14743                 return 1.0;
14744         }
14745
14746         deUint32        getComponentValidity    ()
14747         {
14748                 return getComponentMatrixValidityMask(rows, cols);
14749         }
14750
14751         template<class fp16type>
14752         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14753         {
14754                 DE_ASSERT(in.size() == 1);
14755
14756                 const size_t            alignedCols     = (cols == 3) ? 4 : cols;
14757                 const size_t            alignedRows     = (rows == 3) ? 4 : rows;
14758                 vector<deFloat16>       output          (alignedCols * alignedRows, 0);
14759
14760                 DE_ASSERT(output.size() == alignedCols * alignedRows);
14761
14762                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14763                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14764                                 output[rowNdx * alignedCols + colNdx] = in[0][colNdx * alignedRows + rowNdx];
14765
14766                 deMemcpy(out, &output[0], sizeof(deFloat16) * output.size());
14767                 deMemcpy(min, &output[0], sizeof(deFloat16) * output.size());
14768                 deMemcpy(max, &output[0], sizeof(deFloat16) * output.size());
14769
14770                 return true;
14771         }
14772 };
14773
14774 template<size_t cols, size_t rows>
14775 struct fp16MatrixTimesScalar : public fp16MatrixBase
14776 {
14777         virtual double getULPs(vector<const deFloat16*>& in)
14778         {
14779                 DE_UNREF(in);
14780
14781                 return 4.0;
14782         }
14783
14784         deUint32        getComponentValidity    ()
14785         {
14786                 return getComponentMatrixValidityMask(cols, rows);
14787         }
14788
14789         template<class fp16type>
14790         bool calc(vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14791         {
14792                 DE_ASSERT(in.size() == 2);
14793                 DE_ASSERT(getArgCompCount(1) == 1);
14794
14795                 const fp16type  y                       (in[1][0]);
14796                 const float             scalar          (y.asFloat());
14797                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14798                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14799
14800                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14801                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
14802                 DE_UNREF(alignedCols);
14803
14804                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14805                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14806                         {
14807                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
14808                                 const fp16type  x       (in[0][ndx]);
14809                                 const double    result  (scalar * x.asFloat());
14810
14811                                 out[ndx] = fp16type(result).bits();
14812                                 min[ndx] = getMin(result, getULPs(in));
14813                                 max[ndx] = getMax(result, getULPs(in));
14814                         }
14815
14816                 return true;
14817         }
14818 };
14819
14820 template<size_t cols, size_t rows>
14821 struct fp16VectorTimesMatrix : public fp16MatrixBase
14822 {
14823         fp16VectorTimesMatrix() : fp16MatrixBase()
14824         {
14825                 flavorNames.push_back("EmulatingFP16");
14826                 flavorNames.push_back("FloatCalc");
14827         }
14828
14829         virtual double getULPs (vector<const deFloat16*>& in)
14830         {
14831                 DE_UNREF(in);
14832
14833                 return (8.0 * cols);
14834         }
14835
14836         deUint32 getComponentValidity ()
14837         {
14838                 return getComponentMatrixValidityMask(cols, 1);
14839         }
14840
14841         template<class fp16type>
14842         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14843         {
14844                 DE_ASSERT(in.size() == 2);
14845
14846                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14847                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14848
14849                 DE_ASSERT(getOutCompCount() == cols);
14850                 DE_ASSERT(getArgCompCount(0) == rows);
14851                 DE_ASSERT(getArgCompCount(1) == alignedCols * alignedRows);
14852                 DE_UNREF(alignedCols);
14853
14854                 if (getFlavor() == 0)
14855                 {
14856                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14857                         {
14858                                 fp16type        s       (fp16type::zero(1));
14859
14860                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14861                                 {
14862                                         const fp16type  v       (in[0][rowNdx]);
14863                                         const float             vf      (v.asFloat());
14864                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14865                                         const fp16type  x       (in[1][ndx]);
14866                                         const float             xf      (x.asFloat());
14867                                         const fp16type  m       (vf * xf);
14868
14869                                         s = fp16type(s.asFloat() + m.asFloat());
14870                                 }
14871
14872                                 out[colNdx] = s.bits();
14873                                 min[colNdx] = getMin(s.asDouble(), getULPs(in));
14874                                 max[colNdx] = getMax(s.asDouble(), getULPs(in));
14875                         }
14876                 }
14877                 else if (getFlavor() == 1)
14878                 {
14879                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14880                         {
14881                                 float   s       (0.0f);
14882
14883                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14884                                 {
14885                                         const fp16type  v       (in[0][rowNdx]);
14886                                         const float             vf      (v.asFloat());
14887                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14888                                         const fp16type  x       (in[1][ndx]);
14889                                         const float             xf      (x.asFloat());
14890                                         const float             m       (vf * xf);
14891
14892                                         s += m;
14893                                 }
14894
14895                                 out[colNdx] = fp16type(s).bits();
14896                                 min[colNdx] = getMin(static_cast<double>(s), getULPs(in));
14897                                 max[colNdx] = getMax(static_cast<double>(s), getULPs(in));
14898                         }
14899                 }
14900                 else
14901                 {
14902                         TCU_THROW(InternalError, "Unknown flavor");
14903                 }
14904
14905                 return true;
14906         }
14907 };
14908
14909 template<size_t cols, size_t rows>
14910 struct fp16MatrixTimesVector : public fp16MatrixBase
14911 {
14912         fp16MatrixTimesVector() : fp16MatrixBase()
14913         {
14914                 flavorNames.push_back("EmulatingFP16");
14915                 flavorNames.push_back("FloatCalc");
14916         }
14917
14918         virtual double getULPs (vector<const deFloat16*>& in)
14919         {
14920                 DE_UNREF(in);
14921
14922                 return (8.0 * rows);
14923         }
14924
14925         deUint32 getComponentValidity ()
14926         {
14927                 return getComponentMatrixValidityMask(rows, 1);
14928         }
14929
14930         template<class fp16type>
14931         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14932         {
14933                 DE_ASSERT(in.size() == 2);
14934
14935                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14936                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14937
14938                 DE_ASSERT(getOutCompCount() == rows);
14939                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14940                 DE_ASSERT(getArgCompCount(1) == cols);
14941                 DE_UNREF(alignedCols);
14942
14943                 if (getFlavor() == 0)
14944                 {
14945                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14946                         {
14947                                 fp16type        s       (fp16type::zero(1));
14948
14949                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14950                                 {
14951                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14952                                         const fp16type  x       (in[0][ndx]);
14953                                         const float             xf      (x.asFloat());
14954                                         const fp16type  v       (in[1][colNdx]);
14955                                         const float             vf      (v.asFloat());
14956                                         const fp16type  m       (vf * xf);
14957
14958                                         s = fp16type(s.asFloat() + m.asFloat());
14959                                 }
14960
14961                                 out[rowNdx] = s.bits();
14962                                 min[rowNdx] = getMin(s.asDouble(), getULPs(in));
14963                                 max[rowNdx] = getMax(s.asDouble(), getULPs(in));
14964                         }
14965                 }
14966                 else if (getFlavor() == 1)
14967                 {
14968                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14969                         {
14970                                 float   s       (0.0f);
14971
14972                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14973                                 {
14974                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14975                                         const fp16type  x       (in[0][ndx]);
14976                                         const float             xf      (x.asFloat());
14977                                         const fp16type  v       (in[1][colNdx]);
14978                                         const float             vf      (v.asFloat());
14979                                         const float             m       (vf * xf);
14980
14981                                         s += m;
14982                                 }
14983
14984                                 out[rowNdx] = fp16type(s).bits();
14985                                 min[rowNdx] = getMin(static_cast<double>(s), getULPs(in));
14986                                 max[rowNdx] = getMax(static_cast<double>(s), getULPs(in));
14987                         }
14988                 }
14989                 else
14990                 {
14991                         TCU_THROW(InternalError, "Unknown flavor");
14992                 }
14993
14994                 return true;
14995         }
14996 };
14997
14998 template<size_t colsL, size_t rowsL, size_t colsR, size_t rowsR>
14999 struct fp16MatrixTimesMatrix : public fp16MatrixBase
15000 {
15001         fp16MatrixTimesMatrix() : fp16MatrixBase()
15002         {
15003                 flavorNames.push_back("EmulatingFP16");
15004                 flavorNames.push_back("FloatCalc");
15005         }
15006
15007         virtual double getULPs (vector<const deFloat16*>& in)
15008         {
15009                 DE_UNREF(in);
15010
15011                 return 32.0;
15012         }
15013
15014         deUint32 getComponentValidity ()
15015         {
15016                 return getComponentMatrixValidityMask(colsR, rowsL);
15017         }
15018
15019         template<class fp16type>
15020         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15021         {
15022                 DE_STATIC_ASSERT(colsL == rowsR);
15023
15024                 DE_ASSERT(in.size() == 2);
15025
15026                 const size_t    alignedColsL    = (colsL == 3) ? 4 : colsL;
15027                 const size_t    alignedRowsL    = (rowsL == 3) ? 4 : rowsL;
15028                 const size_t    alignedColsR    = (colsR == 3) ? 4 : colsR;
15029                 const size_t    alignedRowsR    = (rowsR == 3) ? 4 : rowsR;
15030
15031                 DE_ASSERT(getOutCompCount() == alignedColsR * alignedRowsL);
15032                 DE_ASSERT(getArgCompCount(0) == alignedColsL * alignedRowsL);
15033                 DE_ASSERT(getArgCompCount(1) == alignedColsR * alignedRowsR);
15034                 DE_UNREF(alignedColsL);
15035                 DE_UNREF(alignedColsR);
15036
15037                 if (getFlavor() == 0)
15038                 {
15039                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15040                         {
15041                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15042                                 {
15043                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15044                                         fp16type                s       (fp16type::zero(1));
15045
15046                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15047                                         {
15048                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15049                                                 const fp16type  l               (in[0][ndxl]);
15050                                                 const float             lf              (l.asFloat());
15051                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15052                                                 const fp16type  r               (in[1][ndxr]);
15053                                                 const float             rf              (r.asFloat());
15054                                                 const fp16type  m               (lf * rf);
15055
15056                                                 s = fp16type(s.asFloat() + m.asFloat());
15057                                         }
15058
15059                                         out[ndx] = s.bits();
15060                                         min[ndx] = getMin(s.asDouble(), getULPs(in));
15061                                         max[ndx] = getMax(s.asDouble(), getULPs(in));
15062                                 }
15063                         }
15064                 }
15065                 else if (getFlavor() == 1)
15066                 {
15067                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15068                         {
15069                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15070                                 {
15071                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15072                                         float                   s       (0.0f);
15073
15074                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15075                                         {
15076                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15077                                                 const fp16type  l               (in[0][ndxl]);
15078                                                 const float             lf              (l.asFloat());
15079                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15080                                                 const fp16type  r               (in[1][ndxr]);
15081                                                 const float             rf              (r.asFloat());
15082                                                 const float             m               (lf * rf);
15083
15084                                                 s += m;
15085                                         }
15086
15087                                         out[ndx] = fp16type(s).bits();
15088                                         min[ndx] = getMin(static_cast<double>(s), getULPs(in));
15089                                         max[ndx] = getMax(static_cast<double>(s), getULPs(in));
15090                                 }
15091                         }
15092                 }
15093                 else
15094                 {
15095                         TCU_THROW(InternalError, "Unknown flavor");
15096                 }
15097
15098                 return true;
15099         }
15100 };
15101
15102 template<size_t cols, size_t rows>
15103 struct fp16OuterProduct : public fp16MatrixBase
15104 {
15105         virtual double getULPs (vector<const deFloat16*>& in)
15106         {
15107                 DE_UNREF(in);
15108
15109                 return 2.0;
15110         }
15111
15112         deUint32 getComponentValidity ()
15113         {
15114                 return getComponentMatrixValidityMask(cols, rows);
15115         }
15116
15117         template<class fp16type>
15118         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15119         {
15120                 DE_ASSERT(in.size() == 2);
15121
15122                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15123                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15124
15125                 DE_ASSERT(getArgCompCount(0) == rows);
15126                 DE_ASSERT(getArgCompCount(1) == cols);
15127                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
15128                 DE_UNREF(alignedCols);
15129
15130                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15131                 {
15132                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15133                         {
15134                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15135                                 const fp16type  x       (in[0][rowNdx]);
15136                                 const float             xf      (x.asFloat());
15137                                 const fp16type  y       (in[1][colNdx]);
15138                                 const float             yf      (y.asFloat());
15139                                 const fp16type  m       (xf * yf);
15140
15141                                 out[ndx] = m.bits();
15142                                 min[ndx] = getMin(m.asDouble(), getULPs(in));
15143                                 max[ndx] = getMax(m.asDouble(), getULPs(in));
15144                         }
15145                 }
15146
15147                 return true;
15148         }
15149 };
15150
15151 template<size_t size>
15152 struct fp16Determinant;
15153
15154 template<>
15155 struct fp16Determinant<2> : public fp16MatrixBase
15156 {
15157         virtual double getULPs (vector<const deFloat16*>& in)
15158         {
15159                 DE_UNREF(in);
15160
15161                 return 128.0; // This is not a precision test. Value is not from spec
15162         }
15163
15164         deUint32 getComponentValidity ()
15165         {
15166                 return 1;
15167         }
15168
15169         template<class fp16type>
15170         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15171         {
15172                 const size_t    cols            = 2;
15173                 const size_t    rows            = 2;
15174                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15175                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15176
15177                 DE_ASSERT(in.size() == 1);
15178                 DE_ASSERT(getOutCompCount() == 1);
15179                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15180                 DE_UNREF(alignedCols);
15181                 DE_UNREF(alignedRows);
15182
15183                 // [ a b ]
15184                 // [ c d ]
15185                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15186                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15187                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15188                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15189                 const float             ad              (a * d);
15190                 const fp16type  adf16   (ad);
15191                 const float             bc              (b * c);
15192                 const fp16type  bcf16   (bc);
15193                 const float             r               (adf16.asFloat() - bcf16.asFloat());
15194                 const fp16type  rf16    (r);
15195
15196                 out[0] = rf16.bits();
15197                 min[0] = getMin(r, getULPs(in));
15198                 max[0] = getMax(r, getULPs(in));
15199
15200                 return true;
15201         }
15202 };
15203
15204 template<>
15205 struct fp16Determinant<3> : public fp16MatrixBase
15206 {
15207         virtual double getULPs (vector<const deFloat16*>& in)
15208         {
15209                 DE_UNREF(in);
15210
15211                 return 128.0; // This is not a precision test. Value is not from spec
15212         }
15213
15214         deUint32 getComponentValidity ()
15215         {
15216                 return 1;
15217         }
15218
15219         template<class fp16type>
15220         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15221         {
15222                 const size_t    cols            = 3;
15223                 const size_t    rows            = 3;
15224                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15225                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15226
15227                 DE_ASSERT(in.size() == 1);
15228                 DE_ASSERT(getOutCompCount() == 1);
15229                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15230                 DE_UNREF(alignedCols);
15231                 DE_UNREF(alignedRows);
15232
15233                 // [ a b c ]
15234                 // [ d e f ]
15235                 // [ g h i ]
15236                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15237                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15238                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15239                 const float             d               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15240                 const float             e               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15241                 const float             f               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15242                 const float             g               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15243                 const float             h               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15244                 const float             i               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15245                 const fp16type  aei             (a * e * i);
15246                 const fp16type  bfg             (b * f * g);
15247                 const fp16type  cdh             (c * d * h);
15248                 const fp16type  ceg             (c * e * g);
15249                 const fp16type  bdi             (b * d * i);
15250                 const fp16type  afh             (a * f * h);
15251                 const float             r               (aei.asFloat() + bfg.asFloat() + cdh.asFloat() - ceg.asFloat() - bdi.asFloat() - afh.asFloat());
15252                 const fp16type  rf16    (r);
15253
15254                 out[0] = rf16.bits();
15255                 min[0] = getMin(r, getULPs(in));
15256                 max[0] = getMax(r, getULPs(in));
15257
15258                 return true;
15259         }
15260 };
15261
15262 template<>
15263 struct fp16Determinant<4> : public fp16MatrixBase
15264 {
15265         virtual double getULPs (vector<const deFloat16*>& in)
15266         {
15267                 DE_UNREF(in);
15268
15269                 return 128.0; // This is not a precision test. Value is not from spec
15270         }
15271
15272         deUint32 getComponentValidity ()
15273         {
15274                 return 1;
15275         }
15276
15277         template<class fp16type>
15278         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15279         {
15280                 const size_t    rows            = 4;
15281                 const size_t    cols            = 4;
15282                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15283                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15284
15285                 DE_ASSERT(in.size() == 1);
15286                 DE_ASSERT(getOutCompCount() == 1);
15287                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15288                 DE_UNREF(alignedCols);
15289                 DE_UNREF(alignedRows);
15290
15291                 // [ a b c d ]
15292                 // [ e f g h ]
15293                 // [ i j k l ]
15294                 // [ m n o p ]
15295                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15296                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15297                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15298                 const float             d               (fp16type(in[0][getNdx(rows, 3, 0)]).asFloat());
15299                 const float             e               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15300                 const float             f               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15301                 const float             g               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15302                 const float             h               (fp16type(in[0][getNdx(rows, 3, 1)]).asFloat());
15303                 const float             i               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15304                 const float             j               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15305                 const float             k               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15306                 const float             l               (fp16type(in[0][getNdx(rows, 3, 2)]).asFloat());
15307                 const float             m               (fp16type(in[0][getNdx(rows, 0, 3)]).asFloat());
15308                 const float             n               (fp16type(in[0][getNdx(rows, 1, 3)]).asFloat());
15309                 const float             o               (fp16type(in[0][getNdx(rows, 2, 3)]).asFloat());
15310                 const float             p               (fp16type(in[0][getNdx(rows, 3, 3)]).asFloat());
15311
15312                 // [ f g h ]
15313                 // [ j k l ]
15314                 // [ n o p ]
15315                 const fp16type  fkp             (f * k * p);
15316                 const fp16type  gln             (g * l * n);
15317                 const fp16type  hjo             (h * j * o);
15318                 const fp16type  hkn             (h * k * n);
15319                 const fp16type  gjp             (g * j * p);
15320                 const fp16type  flo             (f * l * o);
15321                 const fp16type  detA    (a * (fkp.asFloat() + gln.asFloat() + hjo.asFloat() - hkn.asFloat() - gjp.asFloat() - flo.asFloat()));
15322
15323                 // [ e g h ]
15324                 // [ i k l ]
15325                 // [ m o p ]
15326                 const fp16type  ekp             (e * k * p);
15327                 const fp16type  glm             (g * l * m);
15328                 const fp16type  hio             (h * i * o);
15329                 const fp16type  hkm             (h * k * m);
15330                 const fp16type  gip             (g * i * p);
15331                 const fp16type  elo             (e * l * o);
15332                 const fp16type  detB    (b * (ekp.asFloat() + glm.asFloat() + hio.asFloat() - hkm.asFloat() - gip.asFloat() - elo.asFloat()));
15333
15334                 // [ e f h ]
15335                 // [ i j l ]
15336                 // [ m n p ]
15337                 const fp16type  ejp             (e * j * p);
15338                 const fp16type  flm             (f * l * m);
15339                 const fp16type  hin             (h * i * n);
15340                 const fp16type  hjm             (h * j * m);
15341                 const fp16type  fip             (f * i * p);
15342                 const fp16type  eln             (e * l * n);
15343                 const fp16type  detC    (c * (ejp.asFloat() + flm.asFloat() + hin.asFloat() - hjm.asFloat() - fip.asFloat() - eln.asFloat()));
15344
15345                 // [ e f g ]
15346                 // [ i j k ]
15347                 // [ m n o ]
15348                 const fp16type  ejo             (e * j * o);
15349                 const fp16type  fkm             (f * k * m);
15350                 const fp16type  gin             (g * i * n);
15351                 const fp16type  gjm             (g * j * m);
15352                 const fp16type  fio             (f * i * o);
15353                 const fp16type  ekn             (e * k * n);
15354                 const fp16type  detD    (d * (ejo.asFloat() + fkm.asFloat() + gin.asFloat() - gjm.asFloat() - fio.asFloat() - ekn.asFloat()));
15355
15356                 const float             r               (detA.asFloat() - detB.asFloat() + detC.asFloat() - detD.asFloat());
15357                 const fp16type  rf16    (r);
15358
15359                 out[0] = rf16.bits();
15360                 min[0] = getMin(r, getULPs(in));
15361                 max[0] = getMax(r, getULPs(in));
15362
15363                 return true;
15364         }
15365 };
15366
15367 template<size_t size>
15368 struct fp16Inverse;
15369
15370 template<>
15371 struct fp16Inverse<2> : public fp16MatrixBase
15372 {
15373         virtual double getULPs (vector<const deFloat16*>& in)
15374         {
15375                 DE_UNREF(in);
15376
15377                 return 128.0; // This is not a precision test. Value is not from spec
15378         }
15379
15380         deUint32 getComponentValidity ()
15381         {
15382                 return getComponentMatrixValidityMask(2, 2);
15383         }
15384
15385         template<class fp16type>
15386         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15387         {
15388                 const size_t    cols            = 2;
15389                 const size_t    rows            = 2;
15390                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15391                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15392
15393                 DE_ASSERT(in.size() == 1);
15394                 DE_ASSERT(getOutCompCount() == alignedRows * alignedCols);
15395                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15396                 DE_UNREF(alignedCols);
15397
15398                 // [ a b ]
15399                 // [ c d ]
15400                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15401                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15402                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15403                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15404                 const float             ad              (a * d);
15405                 const fp16type  adf16   (ad);
15406                 const float             bc              (b * c);
15407                 const fp16type  bcf16   (bc);
15408                 const float             det             (adf16.asFloat() - bcf16.asFloat());
15409                 const fp16type  det16   (det);
15410
15411                 out[0] = fp16type( d / det16.asFloat()).bits();
15412                 out[1] = fp16type(-c / det16.asFloat()).bits();
15413                 out[2] = fp16type(-b / det16.asFloat()).bits();
15414                 out[3] = fp16type( a / det16.asFloat()).bits();
15415
15416                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15417                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15418                         {
15419                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15420                                 const fp16type  s       (out[ndx]);
15421
15422                                 min[ndx] = getMin(s.asDouble(), getULPs(in));
15423                                 max[ndx] = getMax(s.asDouble(), getULPs(in));
15424                         }
15425
15426                 return true;
15427         }
15428 };
15429
15430 inline std::string fp16ToString(deFloat16 val)
15431 {
15432         return tcu::toHex<4>(val).toString() + " (" + de::floatToString(tcu::Float16(val).asFloat(), 10) + ")";
15433 }
15434
15435 template <size_t RES_COMPONENTS, size_t ARG0_COMPONENTS, size_t ARG1_COMPONENTS, size_t ARG2_COMPONENTS, class TestedArithmeticFunction>
15436 bool compareFP16ArithmeticFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
15437 {
15438         if (inputs.size() < 1 || inputs.size() > 3 || outputAllocs.size() != 1 || expectedOutputs.size() != 1)
15439                 return false;
15440
15441         const size_t    resultStep                      = (RES_COMPONENTS == 3) ? 4 : RES_COMPONENTS;
15442         const size_t    iterationsCount         = expectedOutputs[0].getByteSize() / (sizeof(deFloat16) * resultStep);
15443         const size_t    inputsSteps[3]          =
15444         {
15445                 (ARG0_COMPONENTS == 3) ? 4 : ARG0_COMPONENTS,
15446                 (ARG1_COMPONENTS == 3) ? 4 : ARG1_COMPONENTS,
15447                 (ARG2_COMPONENTS == 3) ? 4 : ARG2_COMPONENTS,
15448         };
15449
15450         DE_ASSERT(expectedOutputs[0].getByteSize() > 0);
15451         DE_ASSERT(expectedOutputs[0].getByteSize() == sizeof(deFloat16) * iterationsCount * resultStep);
15452
15453         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15454         {
15455                 DE_ASSERT(inputs[inputNdx].getByteSize() > 0);
15456                 DE_ASSERT(inputs[inputNdx].getByteSize() == sizeof(deFloat16) * iterationsCount * inputsSteps[inputNdx]);
15457         }
15458
15459         const deFloat16* const          outputAsFP16                                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
15460         TestedArithmeticFunction        func;
15461
15462         func.setOutCompCount(RES_COMPONENTS);
15463         func.setArgCompCount(0, ARG0_COMPONENTS);
15464         func.setArgCompCount(1, ARG1_COMPONENTS);
15465         func.setArgCompCount(2, ARG2_COMPONENTS);
15466
15467         const bool                                      callOncePerComponent                    = func.callOncePerComponent();
15468         const deUint32                          componentValidityMask                   = func.getComponentValidity();
15469         const size_t                            denormModesCount                                = 2;
15470         const char*                                     denormModes[denormModesCount]   = { "keep denormal numbers", "flush to zero" };
15471         const size_t                            successfulRunsPerComponent              = denormModesCount * func.getFlavorCount();
15472         bool                                            success                                                 = true;
15473         size_t                                          validatedCount                                  = 0;
15474
15475         vector<deUint8> inputBytes[3];
15476
15477         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15478                 inputs[inputNdx].getBytes(inputBytes[inputNdx]);
15479
15480         const deFloat16* const                  inputsAsFP16[3]                 =
15481         {
15482                 inputs.size() >= 1 ? (const deFloat16*)&inputBytes[0][0] : DE_NULL,
15483                 inputs.size() >= 2 ? (const deFloat16*)&inputBytes[1][0] : DE_NULL,
15484                 inputs.size() >= 3 ? (const deFloat16*)&inputBytes[2][0] : DE_NULL,
15485         };
15486
15487         for (size_t idx = 0; idx < iterationsCount; ++idx)
15488         {
15489                 std::vector<size_t>                     successfulRuns          (RES_COMPONENTS, successfulRunsPerComponent);
15490                 std::vector<std::string>        errors                          (RES_COMPONENTS);
15491                 bool                                            iterationValidated      (true);
15492
15493                 for (size_t denormNdx = 0; denormNdx < 2; ++denormNdx)
15494                 {
15495                         for (size_t flavorNdx = 0; flavorNdx < func.getFlavorCount(); ++flavorNdx)
15496                         {
15497                                 func.setFlavor(flavorNdx);
15498
15499                                 const deFloat16*                        iterationOutputFP16             = &outputAsFP16[idx * resultStep];
15500                                 vector<deFloat16>                       iterationCalculatedFP16 (resultStep, 0);
15501                                 vector<double>                          iterationEdgeMin                (resultStep, 0.0);
15502                                 vector<double>                          iterationEdgeMax                (resultStep, 0.0);
15503                                 vector<const deFloat16*>        arguments;
15504
15505                                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15506                                 {
15507                                         std::string     error;
15508                                         bool            reportError = false;
15509
15510                                         if (callOncePerComponent || componentNdx == 0)
15511                                         {
15512                                                 bool funcCallResult;
15513
15514                                                 arguments.clear();
15515
15516                                                 for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15517                                                         arguments.push_back(&inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + componentNdx]);
15518
15519                                                 if (denormNdx == 0)
15520                                                         funcCallResult = func.template calc<tcu::Float16>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15521                                                 else
15522                                                         funcCallResult = func.template calc<tcu::Float16Denormless>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15523
15524                                                 if (!funcCallResult)
15525                                                 {
15526                                                         iterationValidated = false;
15527
15528                                                         if (callOncePerComponent)
15529                                                                 continue;
15530                                                         else
15531                                                                 break;
15532                                                 }
15533                                         }
15534
15535                                         if ((componentValidityMask != 0) && (componentValidityMask & (1<<componentNdx)) == 0)
15536                                                 continue;
15537
15538                                         reportError = !compare16BitFloat(iterationCalculatedFP16[componentNdx], iterationOutputFP16[componentNdx], error);
15539
15540                                         if (reportError)
15541                                         {
15542                                                 tcu::Float16 expected   (iterationCalculatedFP16[componentNdx]);
15543                                                 tcu::Float16 outputted  (iterationOutputFP16[componentNdx]);
15544
15545                                                 if (reportError && expected.isNaN())
15546                                                         reportError = false;
15547
15548                                                 if (reportError && !expected.isNaN() && !outputted.isNaN())
15549                                                 {
15550                                                         if (reportError && !expected.isInf() && !outputted.isInf())
15551                                                         {
15552                                                                 // Ignore rounding
15553                                                                 if (expected.bits() == outputted.bits() + 1 || expected.bits() + 1 == outputted.bits())
15554                                                                         reportError = false;
15555                                                         }
15556
15557                                                         if (reportError && expected.isInf())
15558                                                         {
15559                                                                 // RTZ rounding mode returns +/-65504 instead of Inf on overflow
15560                                                                 if (expected.sign() == 1 && outputted.bits() == 0x7bff && iterationEdgeMin[componentNdx] <= std::numeric_limits<double>::max())
15561                                                                         reportError = false;
15562                                                                 else if (expected.sign() == -1 && outputted.bits() == 0xfbff && iterationEdgeMax[componentNdx] >= -std::numeric_limits<double>::max())
15563                                                                         reportError = false;
15564                                                         }
15565
15566                                                         if (reportError)
15567                                                         {
15568                                                                 const double    outputtedDouble = outputted.asDouble();
15569
15570                                                                 DE_ASSERT(iterationEdgeMin[componentNdx] <= iterationEdgeMax[componentNdx]);
15571
15572                                                                 if (de::inRange(outputtedDouble, iterationEdgeMin[componentNdx], iterationEdgeMax[componentNdx]))
15573                                                                         reportError = false;
15574                                                         }
15575                                                 }
15576
15577                                                 if (reportError)
15578                                                 {
15579                                                         const size_t            inputsComps[3]  =
15580                                                         {
15581                                                                 ARG0_COMPONENTS,
15582                                                                 ARG1_COMPONENTS,
15583                                                                 ARG2_COMPONENTS,
15584                                                         };
15585                                                         string                          inputsValues    ("Inputs:");
15586                                                         string                          flavorName              (func.getFlavorCount() == 1 ? "" : string(" flavor ") + de::toString(flavorNdx) + " (" + func.getCurrentFlavorName() + ")");
15587                                                         std::stringstream       errStream;
15588
15589                                                         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15590                                                         {
15591                                                                 const size_t    inputCompsCount = inputsComps[inputNdx];
15592
15593                                                                 inputsValues += " [" + de::toString(inputNdx) + "]=(";
15594
15595                                                                 for (size_t compNdx = 0; compNdx < inputCompsCount; ++compNdx)
15596                                                                 {
15597                                                                         const deFloat16 inputComponentValue = inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + compNdx];
15598
15599                                                                         inputsValues += fp16ToString(inputComponentValue) + ((compNdx + 1 == inputCompsCount) ? ")": ", ");
15600                                                                 }
15601                                                         }
15602
15603                                                         errStream       << "At"
15604                                                                                 << " iteration " << de::toString(idx)
15605                                                                                 << " component " << de::toString(componentNdx)
15606                                                                                 << " denormMode " << de::toString(denormNdx)
15607                                                                                 << " (" << denormModes[denormNdx] << ")"
15608                                                                                 << " " << flavorName
15609                                                                                 << " " << inputsValues
15610                                                                                 << " outputted:" + fp16ToString(iterationOutputFP16[componentNdx])
15611                                                                                 << " expected:" + fp16ToString(iterationCalculatedFP16[componentNdx])
15612                                                                                 << " or in range: [" << iterationEdgeMin[componentNdx] << ", " << iterationEdgeMax[componentNdx] << "]."
15613                                                                                 << " " << error << "."
15614                                                                                 << std::endl;
15615
15616                                                         errors[componentNdx] += errStream.str();
15617
15618                                                         successfulRuns[componentNdx]--;
15619                                                 }
15620                                         }
15621                                 }
15622                         }
15623                 }
15624
15625                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15626                 {
15627                         // Check if any component has total failure
15628                         if (successfulRuns[componentNdx] == 0)
15629                         {
15630                                 // Test failed in all denorm modes and all flavors for certain component: dump errors
15631                                 log << TestLog::Message << errors[componentNdx] << TestLog::EndMessage;
15632
15633                                 success = false;
15634                         }
15635                 }
15636
15637                 if (iterationValidated)
15638                         validatedCount++;
15639         }
15640
15641         if (validatedCount < 16)
15642                 TCU_THROW(InternalError, "Too few samples has been validated.");
15643
15644         return success;
15645 }
15646
15647 // IEEE-754 floating point numbers:
15648 // +--------+------+----------+-------------+
15649 // | binary | sign | exponent | significand |
15650 // +--------+------+----------+-------------+
15651 // | 16-bit |  1   |    5     |     10      |
15652 // +--------+------+----------+-------------+
15653 // | 32-bit |  1   |    8     |     23      |
15654 // +--------+------+----------+-------------+
15655 //
15656 // 16-bit floats:
15657 //
15658 // 0   000 00   00 0000 0001 (0x0001: 2e-24:         minimum positive denormalized)
15659 // 0   000 00   11 1111 1111 (0x03ff: 2e-14 - 2e-24: maximum positive denormalized)
15660 // 0   000 01   00 0000 0000 (0x0400: 2e-14:         minimum positive normalized)
15661 // 0   111 10   11 1111 1111 (0x7bff: 65504:         maximum positive normalized)
15662 //
15663 // 0   000 00   00 0000 0000 (0x0000: +0)
15664 // 0   111 11   00 0000 0000 (0x7c00: +Inf)
15665 // 0   000 00   11 1111 0000 (0x03f0: +Denorm)
15666 // 0   000 01   00 0000 0001 (0x0401: +Norm)
15667 // 0   111 11   00 0000 1111 (0x7c0f: +SNaN)
15668 // 0   111 11   11 1111 0000 (0x7ff0: +QNaN)
15669 // Generate and return 16-bit floats and their corresponding 32-bit values.
15670 //
15671 // The first 14 number pairs are manually picked, while the rest are randomly generated.
15672 // Expected count to be at least 14 (numPicks).
15673 vector<deFloat16> getFloat16a (de::Random& rnd, deUint32 count)
15674 {
15675         vector<deFloat16>       float16;
15676
15677         float16.reserve(count);
15678
15679         // Zero
15680         float16.push_back(deUint16(0x0000));
15681         float16.push_back(deUint16(0x8000));
15682         // Infinity
15683         float16.push_back(deUint16(0x7c00));
15684         float16.push_back(deUint16(0xfc00));
15685         // Normalized
15686         float16.push_back(deUint16(0x0401));
15687         float16.push_back(deUint16(0x8401));
15688         // Some normal number
15689         float16.push_back(deUint16(0x14cb));
15690         float16.push_back(deUint16(0x94cb));
15691         // Min/max positive normal
15692         float16.push_back(deUint16(0x0400));
15693         float16.push_back(deUint16(0x7bff));
15694         // Min/max negative normal
15695         float16.push_back(deUint16(0x8400));
15696         float16.push_back(deUint16(0xfbff));
15697         // PI
15698         float16.push_back(deUint16(0x4248)); // 3.140625
15699         float16.push_back(deUint16(0xb248)); // -3.140625
15700         // PI/2
15701         float16.push_back(deUint16(0x3e48)); // 1.5703125
15702         float16.push_back(deUint16(0xbe48)); // -1.5703125
15703         float16.push_back(deUint16(0x3c00)); // 1.0
15704         float16.push_back(deUint16(0x3800)); // 0.5
15705         // Some useful constants
15706         float16.push_back(tcu::Float16(-2.5f).bits());
15707         float16.push_back(tcu::Float16(-1.0f).bits());
15708         float16.push_back(tcu::Float16( 0.4f).bits());
15709         float16.push_back(tcu::Float16( 2.5f).bits());
15710
15711         const deUint32          numPicks        = static_cast<deUint32>(float16.size());
15712
15713         DE_ASSERT(count >= numPicks);
15714         count -= numPicks;
15715
15716         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15717         {
15718                 int                     sign            = (rnd.getUint16() % 2 == 0) ? +1 : -1;
15719                 int                     exponent        = (rnd.getUint16() % 29) - 14 + 1;
15720                 deUint16        mantissa        = static_cast<deUint16>(2 * (rnd.getUint16() % 512));
15721
15722                 // Exclude power of -14 to avoid denorms
15723                 DE_ASSERT(de::inRange(exponent, -13, 15));
15724
15725                 float16.push_back(tcu::Float16::constructBits(sign, exponent, mantissa).bits());
15726         }
15727
15728         return float16;
15729 }
15730
15731 static inline vector<deFloat16> getInputData1 (deUint32 seed, size_t count, size_t argNo)
15732 {
15733         DE_UNREF(argNo);
15734
15735         de::Random      rnd(seed);
15736
15737         return getFloat16a(rnd, static_cast<deUint32>(count));
15738 }
15739
15740 static inline vector<deFloat16> getInputData2 (deUint32 seed, size_t count, size_t argNo)
15741 {
15742         de::Random      rnd             (seed);
15743         size_t          newCount = static_cast<size_t>(deSqrt(double(count)));
15744
15745         DE_ASSERT(newCount * newCount == count);
15746
15747         vector<deFloat16>       float16 = getFloat16a(rnd, static_cast<deUint32>(newCount));
15748
15749         return squarize(float16, static_cast<deUint32>(argNo));
15750 }
15751
15752 static inline vector<deFloat16> getInputData3 (deUint32 seed, size_t count, size_t argNo)
15753 {
15754         if (argNo == 0 || argNo == 1)
15755                 return getInputData2(seed, count, argNo);
15756         else
15757                 return getInputData1(seed<<argNo, count, argNo);
15758 }
15759
15760 vector<deFloat16> getInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15761 {
15762         DE_UNREF(stride);
15763
15764         vector<deFloat16>       result;
15765
15766         switch (argCount)
15767         {
15768                 case 1:result = getInputData1(seed, count, argNo); break;
15769                 case 2:result = getInputData2(seed, count, argNo); break;
15770                 case 3:result = getInputData3(seed, count, argNo); break;
15771                 default: TCU_THROW(InternalError, "Invalid argument count specified");
15772         }
15773
15774         if (compCount == 3)
15775         {
15776                 const size_t            newCount = (3 * count) / 4;
15777                 vector<deFloat16>       newResult;
15778
15779                 newResult.reserve(result.size());
15780
15781                 for (size_t ndx = 0; ndx < newCount; ++ndx)
15782                 {
15783                         newResult.push_back(result[ndx]);
15784
15785                         if (ndx % 3 == 2)
15786                                 newResult.push_back(0);
15787                 }
15788
15789                 result = newResult;
15790         }
15791
15792         DE_ASSERT(result.size() == count);
15793
15794         return result;
15795 }
15796
15797 // Generator for functions requiring data in range [1, inf]
15798 vector<deFloat16> getInputDataAC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15799 {
15800         vector<deFloat16>       result;
15801
15802         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15803
15804         // Filter out values below 1.0 from upper half of numbers
15805         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15806         {
15807                 const float f = tcu::Float16(result[idx]).asFloat();
15808
15809                 if (f < 1.0f)
15810                         result[idx] = tcu::Float16(1.0f - f).bits();
15811         }
15812
15813         return result;
15814 }
15815
15816 // Generator for functions requiring data in range [-1, 1]
15817 vector<deFloat16> getInputDataA (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15818 {
15819         vector<deFloat16>       result;
15820
15821         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15822
15823         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15824         {
15825                 const float f = tcu::Float16(result[idx]).asFloat();
15826
15827                 if (!de::inRange(f, -1.0f, 1.0f))
15828                         result[idx] = tcu::Float16(deFloatFrac(f)).bits();
15829         }
15830
15831         return result;
15832 }
15833
15834 // Generator for functions requiring data in range [-pi, pi]
15835 vector<deFloat16> getInputDataPI (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15836 {
15837         vector<deFloat16>       result;
15838
15839         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15840
15841         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15842         {
15843                 const float f = tcu::Float16(result[idx]).asFloat();
15844
15845                 if (!de::inRange(f, -DE_PI, DE_PI))
15846                         result[idx] = tcu::Float16(fmodf(f, DE_PI)).bits();
15847         }
15848
15849         return result;
15850 }
15851
15852 // Generator for functions requiring data in range [0, inf]
15853 vector<deFloat16> getInputDataP (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15854 {
15855         vector<deFloat16>       result;
15856
15857         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15858
15859         if (argNo == 0)
15860         {
15861                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15862                         result[idx] &= static_cast<deFloat16>(~0x8000);
15863         }
15864
15865         return result;
15866 }
15867
15868 vector<deFloat16> getInputDataV (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15869 {
15870         DE_UNREF(stride);
15871         DE_UNREF(argCount);
15872
15873         vector<deFloat16>       result;
15874
15875         if (argNo == 0)
15876                 result = getInputData2(seed, count, argNo);
15877         else
15878         {
15879                 const size_t            alignedCount    = (compCount == 3) ? 4 : compCount;
15880                 const size_t            newCountX               = static_cast<size_t>(deSqrt(double(count * alignedCount)));
15881                 const size_t            newCountY               = count / newCountX;
15882                 de::Random                      rnd                             (seed);
15883                 vector<deFloat16>       float16                 = getFloat16a(rnd, static_cast<deUint32>(newCountX));
15884
15885                 DE_ASSERT(newCountX * newCountX == alignedCount * count);
15886
15887                 for (size_t numIdx = 0; numIdx < newCountX; ++numIdx)
15888                 {
15889                         const vector<deFloat16> tmp(newCountY, float16[numIdx]);
15890
15891                         result.insert(result.end(), tmp.begin(), tmp.end());
15892                 }
15893         }
15894
15895         DE_ASSERT(result.size() == count);
15896
15897         return result;
15898 }
15899
15900 vector<deFloat16> getInputDataM (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15901 {
15902         DE_UNREF(compCount);
15903         DE_UNREF(stride);
15904         DE_UNREF(argCount);
15905
15906         de::Random                      rnd             (seed << argNo);
15907         vector<deFloat16>       result;
15908
15909         result = getFloat16a(rnd, static_cast<deUint32>(count));
15910
15911         DE_ASSERT(result.size() == count);
15912
15913         return result;
15914 }
15915
15916 vector<deFloat16> getInputDataD (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15917 {
15918         DE_UNREF(compCount);
15919         DE_UNREF(argCount);
15920
15921         de::Random                      rnd             (seed << argNo);
15922         vector<deFloat16>       result;
15923
15924         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15925         {
15926                 int num = (rnd.getUint16() % 16) - 8;
15927
15928                 result.push_back(tcu::Float16(float(num)).bits());
15929         }
15930
15931         result[0 * stride] = deUint16(0x7c00); // +Inf
15932         result[1 * stride] = deUint16(0xfc00); // -Inf
15933
15934         DE_ASSERT(result.size() == count);
15935
15936         return result;
15937 }
15938
15939 // Generator for smoothstep function
15940 vector<deFloat16> getInputDataSS (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15941 {
15942         vector<deFloat16>       result;
15943
15944         result = getInputDataD(seed, count, compCount, stride, argCount, argNo);
15945
15946         if (argNo == 0)
15947         {
15948                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15949                 {
15950                         const float f = tcu::Float16(result[idx]).asFloat();
15951
15952                         if (f > 4.0f)
15953                                 result[idx] = tcu::Float16(-f).bits();
15954                 }
15955         }
15956
15957         if (argNo == 1)
15958         {
15959                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15960                 {
15961                         const float f = tcu::Float16(result[idx]).asFloat();
15962
15963                         if (f < 4.0f)
15964                                 result[idx] = tcu::Float16(-f).bits();
15965                 }
15966         }
15967
15968         return result;
15969 }
15970
15971 // Generates normalized vectors for arguments 0 and 1
15972 vector<deFloat16> getInputDataN (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15973 {
15974         DE_UNREF(compCount);
15975         DE_UNREF(argCount);
15976
15977         de::Random                      rnd             (seed << argNo);
15978         vector<deFloat16>       result;
15979
15980         if (argNo == 0 || argNo == 1)
15981         {
15982                 // The input parameters for the incident vector I and the surface normal N must already be normalized
15983                 for (size_t numIdx = 0; numIdx < count; numIdx += stride)
15984                 {
15985                         vector <float>  unnormolized;
15986                         float                   sum                             = 0;
15987
15988                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
15989                                 unnormolized.push_back(float((rnd.getUint16() % 16) - 8));
15990
15991                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
15992                                 sum += unnormolized[compIdx] * unnormolized[compIdx];
15993
15994                         sum = deFloatSqrt(sum);
15995                         if (sum == 0.0f)
15996                                 unnormolized[0] = sum = 1.0f;
15997
15998                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
15999                                 result.push_back(tcu::Float16(unnormolized[compIdx] / sum).bits());
16000
16001                         for (size_t compIdx = compCount; compIdx < stride; ++compIdx)
16002                                 result.push_back(0);
16003                 }
16004         }
16005         else
16006         {
16007                 // Input parameter eta
16008                 for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16009                 {
16010                         int num = (rnd.getUint16() % 16) - 8;
16011
16012                         result.push_back(tcu::Float16(float(num)).bits());
16013                 }
16014         }
16015
16016         DE_ASSERT(result.size() == count);
16017
16018         return result;
16019 }
16020
16021 // Data generator for complex matrix functions like determinant and inverse
16022 vector<deFloat16> getInputDataC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16023 {
16024         DE_UNREF(compCount);
16025         DE_UNREF(stride);
16026         DE_UNREF(argCount);
16027
16028         de::Random                      rnd             (seed << argNo);
16029         vector<deFloat16>       result;
16030
16031         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16032         {
16033                 int num = (rnd.getUint16() % 16) - 8;
16034
16035                 result.push_back(tcu::Float16(float(num)).bits());
16036         }
16037
16038         DE_ASSERT(result.size() == count);
16039
16040         return result;
16041 }
16042
16043 struct Math16TestType
16044 {
16045         const char*             typePrefix;
16046         const size_t    typeComponents;
16047         const size_t    typeArrayStride;
16048         const size_t    typeStructStride;
16049 };
16050
16051 enum Math16DataTypes
16052 {
16053         NONE    = 0,
16054         SCALAR  = 1,
16055         VEC2    = 2,
16056         VEC3    = 3,
16057         VEC4    = 4,
16058         MAT2X2,
16059         MAT2X3,
16060         MAT2X4,
16061         MAT3X2,
16062         MAT3X3,
16063         MAT3X4,
16064         MAT4X2,
16065         MAT4X3,
16066         MAT4X4,
16067         MATH16_TYPE_LAST
16068 };
16069
16070 struct Math16ArgFragments
16071 {
16072         const char*     bodies;
16073         const char*     variables;
16074         const char*     decorations;
16075         const char*     funcVariables;
16076 };
16077
16078 typedef vector<deFloat16> Math16GetInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo);
16079
16080 struct Math16TestFunc
16081 {
16082         const char*                                     funcName;
16083         const char*                                     funcSuffix;
16084         size_t                                          funcArgsCount;
16085         size_t                                          typeResult;
16086         size_t                                          typeArg0;
16087         size_t                                          typeArg1;
16088         size_t                                          typeArg2;
16089         Math16GetInputData*                     getInputDataFunc;
16090         VerifyIOFunc                            verifyFunc;
16091 };
16092
16093 template<class SpecResource>
16094 void createFloat16ArithmeticFuncTest (tcu::TestContext& testCtx, tcu::TestCaseGroup& testGroup, const size_t testTypeIdx, const Math16TestFunc& testFunc)
16095 {
16096         const int                                       testSpecificSeed                        = deStringHash(testGroup.getName());
16097         const int                                       seed                                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
16098         const size_t                            numDataPointsByAxis                     = 32;
16099         const size_t                            numDataPoints                           = numDataPointsByAxis * numDataPointsByAxis;
16100         const char*                                     componentType                           = "f16";
16101         const Math16TestType            testTypes[MATH16_TYPE_LAST]     =
16102         {
16103                 { "",           0,       0,                                              0,                                             },
16104                 { "",           1,       1 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16105                 { "v2",         2,       2 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16106                 { "v3",         3,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16107                 { "v4",         4,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16108                 { "m2x2",       0,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16109                 { "m2x3",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16110                 { "m2x4",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16111                 { "m3x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16112                 { "m3x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16113                 { "m3x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16114                 { "m4x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16115                 { "m4x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16116                 { "m4x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16117         };
16118
16119         DE_ASSERT(testTypeIdx == testTypes[testTypeIdx].typeComponents);
16120
16121
16122         const StringTemplate preMain
16123         (
16124                 "     %c_i32_ndp  = OpConstant %i32 ${num_data_points}\n"
16125
16126                 "        %f16     = OpTypeFloat 16\n"
16127                 "        %v2f16   = OpTypeVector %f16 2\n"
16128                 "        %v3f16   = OpTypeVector %f16 3\n"
16129                 "        %v4f16   = OpTypeVector %f16 4\n"
16130                 "        %m2x2f16 = OpTypeMatrix %v2f16 2\n"
16131                 "        %m2x3f16 = OpTypeMatrix %v3f16 2\n"
16132                 "        %m2x4f16 = OpTypeMatrix %v4f16 2\n"
16133                 "        %m3x2f16 = OpTypeMatrix %v2f16 3\n"
16134                 "        %m3x3f16 = OpTypeMatrix %v3f16 3\n"
16135                 "        %m3x4f16 = OpTypeMatrix %v4f16 3\n"
16136                 "        %m4x2f16 = OpTypeMatrix %v2f16 4\n"
16137                 "        %m4x3f16 = OpTypeMatrix %v3f16 4\n"
16138                 "        %m4x4f16 = OpTypeMatrix %v4f16 4\n"
16139
16140                 "     %up_f16     = OpTypePointer Uniform %f16    \n"
16141                 "     %up_v2f16   = OpTypePointer Uniform %v2f16  \n"
16142                 "     %up_v3f16   = OpTypePointer Uniform %v3f16  \n"
16143                 "     %up_v4f16   = OpTypePointer Uniform %v4f16  \n"
16144                 "     %up_m2x2f16 = OpTypePointer Uniform %m2x2f16\n"
16145                 "     %up_m2x3f16 = OpTypePointer Uniform %m2x3f16\n"
16146                 "     %up_m2x4f16 = OpTypePointer Uniform %m2x4f16\n"
16147                 "     %up_m3x2f16 = OpTypePointer Uniform %m3x2f16\n"
16148                 "     %up_m3x3f16 = OpTypePointer Uniform %m3x3f16\n"
16149                 "     %up_m3x4f16 = OpTypePointer Uniform %m3x4f16\n"
16150                 "     %up_m4x2f16 = OpTypePointer Uniform %m4x2f16\n"
16151                 "     %up_m4x3f16 = OpTypePointer Uniform %m4x3f16\n"
16152                 "     %up_m4x4f16 = OpTypePointer Uniform %m4x4f16\n"
16153
16154                 "     %ra_f16     = OpTypeArray %f16     %c_i32_ndp\n"
16155                 "     %ra_v2f16   = OpTypeArray %v2f16   %c_i32_ndp\n"
16156                 "     %ra_v3f16   = OpTypeArray %v3f16   %c_i32_ndp\n"
16157                 "     %ra_v4f16   = OpTypeArray %v4f16   %c_i32_ndp\n"
16158                 "     %ra_m2x2f16 = OpTypeArray %m2x2f16 %c_i32_ndp\n"
16159                 "     %ra_m2x3f16 = OpTypeArray %m2x3f16 %c_i32_ndp\n"
16160                 "     %ra_m2x4f16 = OpTypeArray %m2x4f16 %c_i32_ndp\n"
16161                 "     %ra_m3x2f16 = OpTypeArray %m3x2f16 %c_i32_ndp\n"
16162                 "     %ra_m3x3f16 = OpTypeArray %m3x3f16 %c_i32_ndp\n"
16163                 "     %ra_m3x4f16 = OpTypeArray %m3x4f16 %c_i32_ndp\n"
16164                 "     %ra_m4x2f16 = OpTypeArray %m4x2f16 %c_i32_ndp\n"
16165                 "     %ra_m4x3f16 = OpTypeArray %m4x3f16 %c_i32_ndp\n"
16166                 "     %ra_m4x4f16 = OpTypeArray %m4x4f16 %c_i32_ndp\n"
16167
16168                 "   %SSBO_f16     = OpTypeStruct %ra_f16    \n"
16169                 "   %SSBO_v2f16   = OpTypeStruct %ra_v2f16  \n"
16170                 "   %SSBO_v3f16   = OpTypeStruct %ra_v3f16  \n"
16171                 "   %SSBO_v4f16   = OpTypeStruct %ra_v4f16  \n"
16172                 "   %SSBO_m2x2f16 = OpTypeStruct %ra_m2x2f16\n"
16173                 "   %SSBO_m2x3f16 = OpTypeStruct %ra_m2x3f16\n"
16174                 "   %SSBO_m2x4f16 = OpTypeStruct %ra_m2x4f16\n"
16175                 "   %SSBO_m3x2f16 = OpTypeStruct %ra_m3x2f16\n"
16176                 "   %SSBO_m3x3f16 = OpTypeStruct %ra_m3x3f16\n"
16177                 "   %SSBO_m3x4f16 = OpTypeStruct %ra_m3x4f16\n"
16178                 "   %SSBO_m4x2f16 = OpTypeStruct %ra_m4x2f16\n"
16179                 "   %SSBO_m4x3f16 = OpTypeStruct %ra_m4x3f16\n"
16180                 "   %SSBO_m4x4f16 = OpTypeStruct %ra_m4x4f16\n"
16181
16182                 "%up_SSBO_f16     = OpTypePointer Uniform %SSBO_f16    \n"
16183                 "%up_SSBO_v2f16   = OpTypePointer Uniform %SSBO_v2f16  \n"
16184                 "%up_SSBO_v3f16   = OpTypePointer Uniform %SSBO_v3f16  \n"
16185                 "%up_SSBO_v4f16   = OpTypePointer Uniform %SSBO_v4f16  \n"
16186                 "%up_SSBO_m2x2f16 = OpTypePointer Uniform %SSBO_m2x2f16\n"
16187                 "%up_SSBO_m2x3f16 = OpTypePointer Uniform %SSBO_m2x3f16\n"
16188                 "%up_SSBO_m2x4f16 = OpTypePointer Uniform %SSBO_m2x4f16\n"
16189                 "%up_SSBO_m3x2f16 = OpTypePointer Uniform %SSBO_m3x2f16\n"
16190                 "%up_SSBO_m3x3f16 = OpTypePointer Uniform %SSBO_m3x3f16\n"
16191                 "%up_SSBO_m3x4f16 = OpTypePointer Uniform %SSBO_m3x4f16\n"
16192                 "%up_SSBO_m4x2f16 = OpTypePointer Uniform %SSBO_m4x2f16\n"
16193                 "%up_SSBO_m4x3f16 = OpTypePointer Uniform %SSBO_m4x3f16\n"
16194                 "%up_SSBO_m4x4f16 = OpTypePointer Uniform %SSBO_m4x4f16\n"
16195
16196                 "       %fp_v2i32 = OpTypePointer Function %v2i32\n"
16197                 "       %fp_v3i32 = OpTypePointer Function %v3i32\n"
16198                 "       %fp_v4i32 = OpTypePointer Function %v4i32\n"
16199                 "${arg_vars}"
16200         );
16201
16202         const StringTemplate decoration
16203         (
16204                 "OpDecorate %ra_f16     ArrayStride 2 \n"
16205                 "OpDecorate %ra_v2f16   ArrayStride 4 \n"
16206                 "OpDecorate %ra_v3f16   ArrayStride 8 \n"
16207                 "OpDecorate %ra_v4f16   ArrayStride 8 \n"
16208                 "OpDecorate %ra_m2x2f16 ArrayStride 8 \n"
16209                 "OpDecorate %ra_m2x3f16 ArrayStride 16\n"
16210                 "OpDecorate %ra_m2x4f16 ArrayStride 16\n"
16211                 "OpDecorate %ra_m3x2f16 ArrayStride 16\n"
16212                 "OpDecorate %ra_m3x3f16 ArrayStride 32\n"
16213                 "OpDecorate %ra_m3x4f16 ArrayStride 32\n"
16214                 "OpDecorate %ra_m4x2f16 ArrayStride 16\n"
16215                 "OpDecorate %ra_m4x3f16 ArrayStride 32\n"
16216                 "OpDecorate %ra_m4x4f16 ArrayStride 32\n"
16217
16218                 "OpMemberDecorate %SSBO_f16     0 Offset 0\n"
16219                 "OpMemberDecorate %SSBO_v2f16   0 Offset 0\n"
16220                 "OpMemberDecorate %SSBO_v3f16   0 Offset 0\n"
16221                 "OpMemberDecorate %SSBO_v4f16   0 Offset 0\n"
16222                 "OpMemberDecorate %SSBO_m2x2f16 0 Offset 0\n"
16223                 "OpMemberDecorate %SSBO_m2x3f16 0 Offset 0\n"
16224                 "OpMemberDecorate %SSBO_m2x4f16 0 Offset 0\n"
16225                 "OpMemberDecorate %SSBO_m3x2f16 0 Offset 0\n"
16226                 "OpMemberDecorate %SSBO_m3x3f16 0 Offset 0\n"
16227                 "OpMemberDecorate %SSBO_m3x4f16 0 Offset 0\n"
16228                 "OpMemberDecorate %SSBO_m4x2f16 0 Offset 0\n"
16229                 "OpMemberDecorate %SSBO_m4x3f16 0 Offset 0\n"
16230                 "OpMemberDecorate %SSBO_m4x4f16 0 Offset 0\n"
16231
16232                 "OpDecorate %SSBO_f16     BufferBlock\n"
16233                 "OpDecorate %SSBO_v2f16   BufferBlock\n"
16234                 "OpDecorate %SSBO_v3f16   BufferBlock\n"
16235                 "OpDecorate %SSBO_v4f16   BufferBlock\n"
16236                 "OpDecorate %SSBO_m2x2f16 BufferBlock\n"
16237                 "OpDecorate %SSBO_m2x3f16 BufferBlock\n"
16238                 "OpDecorate %SSBO_m2x4f16 BufferBlock\n"
16239                 "OpDecorate %SSBO_m3x2f16 BufferBlock\n"
16240                 "OpDecorate %SSBO_m3x3f16 BufferBlock\n"
16241                 "OpDecorate %SSBO_m3x4f16 BufferBlock\n"
16242                 "OpDecorate %SSBO_m4x2f16 BufferBlock\n"
16243                 "OpDecorate %SSBO_m4x3f16 BufferBlock\n"
16244                 "OpDecorate %SSBO_m4x4f16 BufferBlock\n"
16245
16246                 "OpMemberDecorate %SSBO_m2x2f16 0 ColMajor\n"
16247                 "OpMemberDecorate %SSBO_m2x3f16 0 ColMajor\n"
16248                 "OpMemberDecorate %SSBO_m2x4f16 0 ColMajor\n"
16249                 "OpMemberDecorate %SSBO_m3x2f16 0 ColMajor\n"
16250                 "OpMemberDecorate %SSBO_m3x3f16 0 ColMajor\n"
16251                 "OpMemberDecorate %SSBO_m3x4f16 0 ColMajor\n"
16252                 "OpMemberDecorate %SSBO_m4x2f16 0 ColMajor\n"
16253                 "OpMemberDecorate %SSBO_m4x3f16 0 ColMajor\n"
16254                 "OpMemberDecorate %SSBO_m4x4f16 0 ColMajor\n"
16255
16256                 "OpMemberDecorate %SSBO_m2x2f16 0 MatrixStride 4\n"
16257                 "OpMemberDecorate %SSBO_m2x3f16 0 MatrixStride 8\n"
16258                 "OpMemberDecorate %SSBO_m2x4f16 0 MatrixStride 8\n"
16259                 "OpMemberDecorate %SSBO_m3x2f16 0 MatrixStride 4\n"
16260                 "OpMemberDecorate %SSBO_m3x3f16 0 MatrixStride 8\n"
16261                 "OpMemberDecorate %SSBO_m3x4f16 0 MatrixStride 8\n"
16262                 "OpMemberDecorate %SSBO_m4x2f16 0 MatrixStride 4\n"
16263                 "OpMemberDecorate %SSBO_m4x3f16 0 MatrixStride 8\n"
16264                 "OpMemberDecorate %SSBO_m4x4f16 0 MatrixStride 8\n"
16265
16266                 "${arg_decorations}"
16267         );
16268
16269         const StringTemplate testFun
16270         (
16271                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
16272                 "    %param = OpFunctionParameter %v4f32\n"
16273                 "    %entry = OpLabel\n"
16274
16275                 "        %i = OpVariable %fp_i32 Function\n"
16276                 "${arg_infunc_vars}"
16277                 "             OpStore %i %c_i32_0\n"
16278                 "             OpBranch %loop\n"
16279
16280                 "     %loop = OpLabel\n"
16281                 "    %i_cmp = OpLoad %i32 %i\n"
16282                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
16283                 "             OpLoopMerge %merge %next None\n"
16284                 "             OpBranchConditional %lt %write %merge\n"
16285
16286                 "    %write = OpLabel\n"
16287                 "      %ndx = OpLoad %i32 %i\n"
16288
16289                 "${arg_func_call}"
16290
16291                 "             OpBranch %next\n"
16292
16293                 "     %next = OpLabel\n"
16294                 "    %i_cur = OpLoad %i32 %i\n"
16295                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
16296                 "             OpStore %i %i_new\n"
16297                 "             OpBranch %loop\n"
16298
16299                 "    %merge = OpLabel\n"
16300                 "             OpReturnValue %param\n"
16301                 "             OpFunctionEnd\n"
16302         );
16303
16304         const Math16ArgFragments        argFragment1    =
16305         {
16306                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16307                 " %val_src0 = OpLoad %${t0} %src0\n"
16308                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0\n"
16309                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16310                 "             OpStore %dst %val_dst\n",
16311                 "",
16312                 "",
16313                 "",
16314         };
16315
16316         const Math16ArgFragments        argFragment2    =
16317         {
16318                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16319                 " %val_src0 = OpLoad %${t0} %src0\n"
16320                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16321                 " %val_src1 = OpLoad %${t1} %src1\n"
16322                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1\n"
16323                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16324                 "             OpStore %dst %val_dst\n",
16325                 "",
16326                 "",
16327                 "",
16328         };
16329
16330         const Math16ArgFragments        argFragment3    =
16331         {
16332                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16333                 " %val_src0 = OpLoad %${t0} %src0\n"
16334                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16335                 " %val_src1 = OpLoad %${t1} %src1\n"
16336                 "     %src2 = OpAccessChain %up_${t2} %ssbo_src2 %c_i32_0 %ndx\n"
16337                 " %val_src2 = OpLoad %${t2} %src2\n"
16338                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1 %val_src2\n"
16339                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16340                 "             OpStore %dst %val_dst\n",
16341                 "",
16342                 "",
16343                 "",
16344         };
16345
16346         const Math16ArgFragments        argFragmentLdExp        =
16347         {
16348                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16349                 " %val_src0 = OpLoad %${t0} %src0\n"
16350                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16351                 " %val_src1 = OpLoad %${t1} %src1\n"
16352                 "%val_src1i = OpConvertFToS %${dr}i32 %val_src1\n"
16353                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1i\n"
16354                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16355                 "             OpStore %dst %val_dst\n",
16356
16357                 "",
16358
16359                 "",
16360
16361                 "",
16362         };
16363
16364         const Math16ArgFragments        argFragmentModfFrac     =
16365         {
16366                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16367                 " %val_src0 = OpLoad %${t0} %src0\n"
16368                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16369                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16370                 "             OpStore %dst %val_dst\n",
16371
16372                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16373
16374                 "",
16375
16376                 "      %tmp = OpVariable %fp_tmp Function\n",
16377         };
16378
16379         const Math16ArgFragments        argFragmentModfInt      =
16380         {
16381                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16382                 " %val_src0 = OpLoad %${t0} %src0\n"
16383                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16384                 "     %tmp0 = OpAccessChain %fp_tmp %tmp\n"
16385                 "  %val_dst = OpLoad %${tr} %tmp0\n"
16386                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16387                 "             OpStore %dst %val_dst\n",
16388
16389                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16390
16391                 "",
16392
16393                 "      %tmp = OpVariable %fp_tmp Function\n",
16394         };
16395
16396         const Math16ArgFragments        argFragmentModfStruct   =
16397         {
16398                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16399                 " %val_src0 = OpLoad %${t0} %src0\n"
16400                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16401                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16402                 "             OpStore %tmp_ptr_s %val_tmp\n"
16403                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_${struct_member}\n"
16404                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16405                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16406                 "             OpStore %dst %val_dst\n",
16407
16408                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16409                 "   %st_tmp = OpTypeStruct %${tr} %${tr}\n"
16410                 "   %fp_tmp = OpTypePointer Function %st_tmp\n"
16411                 "   %c_frac = OpConstant %i32 0\n"
16412                 "    %c_int = OpConstant %i32 1\n",
16413
16414                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16415                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16416
16417                 "      %tmp = OpVariable %fp_tmp Function\n",
16418         };
16419
16420         const Math16ArgFragments        argFragmentFrexpStructS =
16421         {
16422                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16423                 " %val_src0 = OpLoad %${t0} %src0\n"
16424                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16425                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16426                 "             OpStore %tmp_ptr_s %val_tmp\n"
16427                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_i32_0\n"
16428                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16429                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16430                 "             OpStore %dst %val_dst\n",
16431
16432                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16433                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16434                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16435
16436                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16437                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16438
16439                 "      %tmp = OpVariable %fp_tmp Function\n",
16440         };
16441
16442         const Math16ArgFragments        argFragmentFrexpStructE =
16443         {
16444                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16445                 " %val_src0 = OpLoad %${t0} %src0\n"
16446                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16447                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16448                 "             OpStore %tmp_ptr_s %val_tmp\n"
16449                 "%tmp_ptr_l = OpAccessChain %fp_${dr}i32 %tmp %c_i32_1\n"
16450                 "%val_dst_i = OpLoad %${dr}i32 %tmp_ptr_l\n"
16451                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16452                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16453                 "             OpStore %dst %val_dst\n",
16454
16455                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16456                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16457
16458                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16459                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16460
16461                 "      %tmp = OpVariable %fp_tmp Function\n",
16462         };
16463
16464         const Math16ArgFragments        argFragmentFrexpS               =
16465         {
16466                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16467                 " %val_src0 = OpLoad %${t0} %src0\n"
16468                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16469                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16470                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16471                 "             OpStore %dst %val_dst\n",
16472
16473                 "",
16474
16475                 "",
16476
16477                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16478         };
16479
16480         const Math16ArgFragments        argFragmentFrexpE               =
16481         {
16482                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16483                 " %val_src0 = OpLoad %${t0} %src0\n"
16484                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16485                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16486                 "%val_dst_i = OpLoad %${dr}i32 %out_exp\n"
16487                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16488                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16489                 "             OpStore %dst %val_dst\n",
16490
16491                 "",
16492
16493                 "",
16494
16495                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16496         };
16497
16498         const Math16TestType&           testType                                = testTypes[testTypeIdx];
16499         const string                            funcNameString                  = string(testFunc.funcName) + string(testFunc.funcSuffix);
16500         const string                            testName                                = de::toLower(funcNameString);
16501         const Math16ArgFragments*       argFragments                    = DE_NULL;
16502         const size_t                            typeStructStride                = testType.typeStructStride;
16503         const bool                                      extInst                                 = !(testFunc.funcName[0] == 'O' && testFunc.funcName[1] == 'p');
16504         const size_t                            numFloatsPerArg0Type    = testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16);
16505         const size_t                            iterations                              = numDataPoints / numFloatsPerArg0Type;
16506         const size_t                            numFloatsPerResultType  = testTypes[testFunc.typeResult].typeArrayStride / sizeof(deFloat16);
16507         const vector<deFloat16>         float16DummyOutput              (iterations * numFloatsPerResultType, 0);
16508         VulkanFeatures                          features;
16509         SpecResource                            specResource;
16510         map<string, string>                     specs;
16511         map<string, string>                     fragments;
16512         vector<string>                          extensions;
16513         string                                          funcCall;
16514         string                                          funcVariables;
16515         string                                          variables;
16516         string                                          declarations;
16517         string                                          decorations;
16518
16519         switch (testFunc.funcArgsCount)
16520         {
16521                 case 1:
16522                 {
16523                         argFragments = &argFragment1;
16524
16525                         if (funcNameString == "ModfFrac")               argFragments = &argFragmentModfFrac;
16526                         if (funcNameString == "ModfInt")                argFragments = &argFragmentModfInt;
16527                         if (funcNameString == "ModfStructFrac") argFragments = &argFragmentModfStruct;
16528                         if (funcNameString == "ModfStructInt")  argFragments = &argFragmentModfStruct;
16529                         if (funcNameString == "FrexpS")                 argFragments = &argFragmentFrexpS;
16530                         if (funcNameString == "FrexpE")                 argFragments = &argFragmentFrexpE;
16531                         if (funcNameString == "FrexpStructS")   argFragments = &argFragmentFrexpStructS;
16532                         if (funcNameString == "FrexpStructE")   argFragments = &argFragmentFrexpStructE;
16533
16534                         break;
16535                 }
16536                 case 2:
16537                 {
16538                         argFragments = &argFragment2;
16539
16540                         if (funcNameString == "Ldexp")                  argFragments = &argFragmentLdExp;
16541
16542                         break;
16543                 }
16544                 case 3:
16545                 {
16546                         argFragments = &argFragment3;
16547
16548                         break;
16549                 }
16550                 default:
16551                 {
16552                         TCU_THROW(InternalError, "Invalid number of arguments");
16553                 }
16554         }
16555
16556         if (testFunc.funcArgsCount == 1)
16557         {
16558                 variables +=
16559                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16560                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16561
16562                 decorations +=
16563                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16564                         "OpDecorate %ssbo_src0 Binding 0\n"
16565                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16566                         "OpDecorate %ssbo_dst Binding 1\n";
16567         }
16568         else if (testFunc.funcArgsCount == 2)
16569         {
16570                 variables +=
16571                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16572                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16573                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16574
16575                 decorations +=
16576                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16577                         "OpDecorate %ssbo_src0 Binding 0\n"
16578                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16579                         "OpDecorate %ssbo_src1 Binding 1\n"
16580                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16581                         "OpDecorate %ssbo_dst Binding 2\n";
16582         }
16583         else if (testFunc.funcArgsCount == 3)
16584         {
16585                 variables +=
16586                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16587                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16588                         " %ssbo_src2 = OpVariable %up_SSBO_${t2} Uniform\n"
16589                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16590
16591                 decorations +=
16592                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16593                         "OpDecorate %ssbo_src0 Binding 0\n"
16594                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16595                         "OpDecorate %ssbo_src1 Binding 1\n"
16596                         "OpDecorate %ssbo_src2 DescriptorSet 0\n"
16597                         "OpDecorate %ssbo_src2 Binding 2\n"
16598                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16599                         "OpDecorate %ssbo_dst Binding 3\n";
16600         }
16601         else
16602         {
16603                 TCU_THROW(InternalError, "Invalid number of function arguments");
16604         }
16605
16606         variables       += argFragments->variables;
16607         decorations     += argFragments->decorations;
16608
16609         specs["dr"]                                     = testTypes[testFunc.typeResult].typePrefix;
16610         specs["d0"]                                     = testTypes[testFunc.typeArg0].typePrefix;
16611         specs["d1"]                                     = testTypes[testFunc.typeArg1].typePrefix;
16612         specs["d2"]                                     = testTypes[testFunc.typeArg2].typePrefix;
16613         specs["tr"]                                     = string(testTypes[testFunc.typeResult].typePrefix) + componentType;
16614         specs["t0"]                                     = string(testTypes[testFunc.typeArg0].typePrefix) + componentType;
16615         specs["t1"]                                     = string(testTypes[testFunc.typeArg1].typePrefix) + componentType;
16616         specs["t2"]                                     = string(testTypes[testFunc.typeArg2].typePrefix) + componentType;
16617         specs["struct_stride"]          = de::toString(typeStructStride);
16618         specs["op"]                                     = extInst ? "OpExtInst" : testFunc.funcName;
16619         specs["ext_inst"]                       = extInst ? string("%ext_import ") + testFunc.funcName : "";
16620         specs["struct_member"]          = de::toLower(testFunc.funcSuffix);
16621
16622         variables                                       = StringTemplate(variables).specialize(specs);
16623         decorations                                     = StringTemplate(decorations).specialize(specs);
16624         funcVariables                           = StringTemplate(argFragments->funcVariables).specialize(specs);
16625         funcCall                                        = StringTemplate(argFragments->bodies).specialize(specs);
16626
16627         specs["num_data_points"]        = de::toString(iterations);
16628         specs["arg_vars"]                       = variables;
16629         specs["arg_decorations"]        = decorations;
16630         specs["arg_infunc_vars"]        = funcVariables;
16631         specs["arg_func_call"]          = funcCall;
16632
16633         fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"\n%ext_import = OpExtInstImport \"GLSL.std.450\"";
16634         fragments["capability"]         = "OpCapability Matrix\nOpCapability StorageUniformBufferBlock16";
16635         fragments["decoration"]         = decoration.specialize(specs);
16636         fragments["pre_main"]           = preMain.specialize(specs);
16637         fragments["testfun"]            = testFun.specialize(specs);
16638
16639         for (size_t inputArgNdx = 0; inputArgNdx < testFunc.funcArgsCount; ++inputArgNdx)
16640         {
16641                 const size_t                    numFloatsPerItem        = (inputArgNdx == 0) ? testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16)
16642                                                                                                         : (inputArgNdx == 1) ? testTypes[testFunc.typeArg1].typeArrayStride / sizeof(deFloat16)
16643                                                                                                         : (inputArgNdx == 2) ? testTypes[testFunc.typeArg2].typeArrayStride / sizeof(deFloat16)
16644                                                                                                         : -1;
16645                 const vector<deFloat16> inputData                       = testFunc.getInputDataFunc(seed, numFloatsPerItem * iterations, testTypeIdx, numFloatsPerItem, testFunc.funcArgsCount, inputArgNdx);
16646
16647                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16648         }
16649
16650         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16DummyOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16651         specResource.verifyIO = testFunc.verifyFunc;
16652
16653         extensions.push_back("VK_KHR_16bit_storage");
16654         extensions.push_back("VK_KHR_shader_float16_int8");
16655
16656         features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
16657         features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
16658
16659         finalizeTestsCreation(specResource, fragments, testCtx, testGroup, testName, features, extensions, IVec3(1, 1, 1));
16660 }
16661
16662 template<size_t C, class SpecResource>
16663 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16664 {
16665         DE_STATIC_ASSERT(C >= 1 && C <= 4);
16666
16667         const std::string                               testGroupName   (string("arithmetic_") + de::toString(C));
16668         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16669         const Math16TestFunc                    testFuncs[]             =
16670         {
16671                 {       "OpFNegate",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16OpFNegate>                                       },
16672                 {       "Round",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Round>                                           },
16673                 {       "RoundEven",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16RoundEven>                                       },
16674                 {       "Trunc",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Trunc>                                           },
16675                 {       "FAbs",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FAbs>                                            },
16676                 {       "FSign",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FSign>                                           },
16677                 {       "Floor",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Floor>                                           },
16678                 {       "Ceil",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Ceil>                                            },
16679                 {       "Fract",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Fract>                                           },
16680                 {       "Radians",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Radians>                                         },
16681                 {       "Degrees",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Degrees>                                         },
16682                 {       "Sin",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sin>                                                     },
16683                 {       "Cos",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cos>                                                     },
16684                 {       "Tan",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tan>                                                     },
16685                 {       "Asin",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asin>                                            },
16686                 {       "Acos",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acos>                                            },
16687                 {       "Atan",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atan>                                            },
16688                 {       "Sinh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sinh>                                            },
16689                 {       "Cosh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cosh>                                            },
16690                 {       "Tanh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tanh>                                            },
16691                 {       "Asinh",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asinh>                                           },
16692                 {       "Acosh",                                "",                     1,      C,              C,              0,              0, &getInputDataAC,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acosh>                                           },
16693                 {       "Atanh",                                "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atanh>                                           },
16694                 {       "Exp",                                  "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp>                                                     },
16695                 {       "Log",                                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log>                                                     },
16696                 {       "Exp2",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp2>                                            },
16697                 {       "Log2",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log2>                                            },
16698                 {       "Sqrt",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sqrt>                                            },
16699                 {       "InverseSqrt",                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16InverseSqrt>                                     },
16700                 {       "Modf",                                 "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16701                 {       "Modf",                                 "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16702                 {       "ModfStruct",                   "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16703                 {       "ModfStruct",                   "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16704                 {       "Frexp",                                "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16705                 {       "Frexp",                                "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16706                 {       "FrexpStruct",                  "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16707                 {       "FrexpStruct",                  "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16708                 {       "OpFAdd",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFAdd>                                          },
16709                 {       "OpFSub",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFSub>                                          },
16710                 {       "OpFMul",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFMul>                                          },
16711                 {       "OpFDiv",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFDiv>                                          },
16712                 {       "Atan2",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Atan2>                                           },
16713                 {       "Pow",                                  "",                     2,      C,              C,              C,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Pow>                                                     },
16714                 {       "FMin",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMin>                                            },
16715                 {       "FMax",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMax>                                            },
16716                 {       "Step",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Step>                                            },
16717                 {       "Ldexp",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Ldexp>                                           },
16718                 {       "FClamp",                               "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FClamp>                                          },
16719                 {       "FMix",                                 "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FMix>                                            },
16720                 {       "SmoothStep",                   "",                     3,      C,              C,              C,              C, &getInputDataSS,     compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16SmoothStep>                                      },
16721                 {       "Fma",                                  "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16Fma>                                                     },
16722                 {       "Length",                               "",                     1,      1,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  0,  0, fp16Length>                                          },
16723                 {       "Distance",                             "",                     2,      1,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Distance>                                        },
16724                 {       "Cross",                                "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Cross>                                           },
16725                 {       "Normalize",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Normalize>                                       },
16726                 {       "FaceForward",                  "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FaceForward>                                     },
16727                 {       "Reflect",                              "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Reflect>                                         },
16728                 {       "Refract",                              "",                     3,      C,              C,              C,              1, &getInputDataN,      compareFP16ArithmeticFunc<  C,  C,  C,  1, fp16Refract>                                         },
16729                 {       "OpDot",                                "",                     2,      1,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Dot>                                                     },
16730                 {       "OpVectorTimesScalar",  "",                     2,      C,              C,              1,              0, &getInputDataV,      compareFP16ArithmeticFunc<  C,  C,  1,  0, fp16VectorTimesScalar>                       },
16731         };
16732
16733         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16734         {
16735                 const Math16TestFunc&   testFunc                = testFuncs[testFuncIdx];
16736                 const string                    funcNameString  = testFunc.funcName;
16737
16738                 if ((C != 3) && funcNameString == "Cross")
16739                         continue;
16740
16741                 if ((C < 2) && funcNameString == "OpDot")
16742                         continue;
16743
16744                 if ((C < 2) && funcNameString == "OpVectorTimesScalar")
16745                         continue;
16746
16747                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), C, testFunc);
16748         }
16749
16750         return testGroup.release();
16751 }
16752
16753 template<class SpecResource>
16754 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16755 {
16756         const std::string                               testGroupName   ("arithmetic");
16757         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16758         const Math16TestFunc                    testFuncs[]             =
16759         {
16760                 {       "OpTranspose",                  "2x2",          1,      MAT2X2, MAT2X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Transpose<2,2> >                         },
16761                 {       "OpTranspose",                  "3x2",          1,      MAT2X3, MAT3X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<3,2> >                         },
16762                 {       "OpTranspose",                  "4x2",          1,      MAT2X4, MAT4X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<4,2> >                         },
16763                 {       "OpTranspose",                  "2x3",          1,      MAT3X2, MAT2X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,3> >                         },
16764                 {       "OpTranspose",                  "3x3",          1,      MAT3X3, MAT3X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,3> >                         },
16765                 {       "OpTranspose",                  "4x3",          1,      MAT3X4, MAT4X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,3> >                         },
16766                 {       "OpTranspose",                  "2x4",          1,      MAT4X2, MAT2X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,4> >                         },
16767                 {       "OpTranspose",                  "3x4",          1,      MAT4X3, MAT3X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,4> >                         },
16768                 {       "OpTranspose",                  "4x4",          1,      MAT4X4, MAT4X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,4> >                         },
16769                 {       "OpMatrixTimesScalar",  "2x2",          2,      MAT2X2, MAT2X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  1,  0, fp16MatrixTimesScalar<2,2> >         },
16770                 {       "OpMatrixTimesScalar",  "2x3",          2,      MAT2X3, MAT2X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,3> >         },
16771                 {       "OpMatrixTimesScalar",  "2x4",          2,      MAT2X4, MAT2X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,4> >         },
16772                 {       "OpMatrixTimesScalar",  "3x2",          2,      MAT3X2, MAT3X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<3,2> >         },
16773                 {       "OpMatrixTimesScalar",  "3x3",          2,      MAT3X3, MAT3X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,3> >         },
16774                 {       "OpMatrixTimesScalar",  "3x4",          2,      MAT3X4, MAT3X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,4> >         },
16775                 {       "OpMatrixTimesScalar",  "4x2",          2,      MAT4X2, MAT4X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<4,2> >         },
16776                 {       "OpMatrixTimesScalar",  "4x3",          2,      MAT4X3, MAT4X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,3> >         },
16777                 {       "OpMatrixTimesScalar",  "4x4",          2,      MAT4X4, MAT4X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,4> >         },
16778                 {       "OpVectorTimesMatrix",  "2x2",          2,      VEC2,   VEC2,   MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  2,  4,  0, fp16VectorTimesMatrix<2,2> >         },
16779                 {       "OpVectorTimesMatrix",  "2x3",          2,      VEC2,   VEC3,   MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  3,  8,  0, fp16VectorTimesMatrix<2,3> >         },
16780                 {       "OpVectorTimesMatrix",  "2x4",          2,      VEC2,   VEC4,   MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  8,  0, fp16VectorTimesMatrix<2,4> >         },
16781                 {       "OpVectorTimesMatrix",  "3x2",          2,      VEC3,   VEC2,   MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  2,  8,  0, fp16VectorTimesMatrix<3,2> >         },
16782                 {       "OpVectorTimesMatrix",  "3x3",          2,      VEC3,   VEC3,   MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  3, 16,  0, fp16VectorTimesMatrix<3,3> >         },
16783                 {       "OpVectorTimesMatrix",  "3x4",          2,      VEC3,   VEC4,   MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  4, 16,  0, fp16VectorTimesMatrix<3,4> >         },
16784                 {       "OpVectorTimesMatrix",  "4x2",          2,      VEC4,   VEC2,   MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  8,  0, fp16VectorTimesMatrix<4,2> >         },
16785                 {       "OpVectorTimesMatrix",  "4x3",          2,      VEC4,   VEC3,   MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  3, 16,  0, fp16VectorTimesMatrix<4,3> >         },
16786                 {       "OpVectorTimesMatrix",  "4x4",          2,      VEC4,   VEC4,   MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4, 16,  0, fp16VectorTimesMatrix<4,4> >         },
16787                 {       "OpMatrixTimesVector",  "2x2",          2,      VEC2,   MAT2X2, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  2,  0, fp16MatrixTimesVector<2,2> >         },
16788                 {       "OpMatrixTimesVector",  "2x3",          2,      VEC3,   MAT2X3, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  8,  2,  0, fp16MatrixTimesVector<2,3> >         },
16789                 {       "OpMatrixTimesVector",  "2x4",          2,      VEC4,   MAT2X4, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  2,  0, fp16MatrixTimesVector<2,4> >         },
16790                 {       "OpMatrixTimesVector",  "3x2",          2,      VEC2,   MAT3X2, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  3,  0, fp16MatrixTimesVector<3,2> >         },
16791                 {       "OpMatrixTimesVector",  "3x3",          2,      VEC3,   MAT3X3, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  3,  0, fp16MatrixTimesVector<3,3> >         },
16792                 {       "OpMatrixTimesVector",  "3x4",          2,      VEC4,   MAT3X4, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  3,  0, fp16MatrixTimesVector<3,4> >         },
16793                 {       "OpMatrixTimesVector",  "4x2",          2,      VEC2,   MAT4X2, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  4,  0, fp16MatrixTimesVector<4,2> >         },
16794                 {       "OpMatrixTimesVector",  "4x3",          2,      VEC3,   MAT4X3, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  4,  0, fp16MatrixTimesVector<4,3> >         },
16795                 {       "OpMatrixTimesVector",  "4x4",          2,      VEC4,   MAT4X4, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  4,  0, fp16MatrixTimesVector<4,4> >         },
16796                 {       "OpMatrixTimesMatrix",  "2x2_2x2",      2,      MAT2X2, MAT2X2, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  4,  0, fp16MatrixTimesMatrix<2,2,2,2> >     },
16797                 {       "OpMatrixTimesMatrix",  "2x2_3x2",      2,      MAT3X2, MAT2X2, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,3,2> >     },
16798                 {       "OpMatrixTimesMatrix",  "2x2_4x2",      2,      MAT4X2, MAT2X2, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,4,2> >     },
16799                 {       "OpMatrixTimesMatrix",  "2x3_2x2",      2,      MAT2X3, MAT2X3, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,3,2,2> >     },
16800                 {       "OpMatrixTimesMatrix",  "2x3_3x2",      2,      MAT3X3, MAT2X3, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,3,2> >     },
16801                 {       "OpMatrixTimesMatrix",  "2x3_4x2",      2,      MAT4X3, MAT2X3, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,4,2> >     },
16802                 {       "OpMatrixTimesMatrix",  "2x4_2x2",      2,      MAT2X4, MAT2X4, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,4,2,2> >     },
16803                 {       "OpMatrixTimesMatrix",  "2x4_3x2",      2,      MAT3X4, MAT2X4, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,3,2> >     },
16804                 {       "OpMatrixTimesMatrix",  "2x4_4x2",      2,      MAT4X4, MAT2X4, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,4,2> >     },
16805                 {       "OpMatrixTimesMatrix",  "3x2_2x3",      2,      MAT2X2, MAT3X2, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<3,2,2,3> >     },
16806                 {       "OpMatrixTimesMatrix",  "3x2_3x3",      2,      MAT3X2, MAT3X2, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,3,3> >     },
16807                 {       "OpMatrixTimesMatrix",  "3x2_4x3",      2,      MAT4X2, MAT3X2, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,4,3> >     },
16808                 {       "OpMatrixTimesMatrix",  "3x3_2x3",      2,      MAT2X3, MAT3X3, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,3,2,3> >     },
16809                 {       "OpMatrixTimesMatrix",  "3x3_3x3",      2,      MAT3X3, MAT3X3, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,3,3> >     },
16810                 {       "OpMatrixTimesMatrix",  "3x3_4x3",      2,      MAT4X3, MAT3X3, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,4,3> >     },
16811                 {       "OpMatrixTimesMatrix",  "3x4_2x3",      2,      MAT2X4, MAT3X4, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,4,2,3> >     },
16812                 {       "OpMatrixTimesMatrix",  "3x4_3x3",      2,      MAT3X4, MAT3X4, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,3,3> >     },
16813                 {       "OpMatrixTimesMatrix",  "3x4_4x3",      2,      MAT4X4, MAT3X4, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,4,3> >     },
16814                 {       "OpMatrixTimesMatrix",  "4x2_2x4",      2,      MAT2X2, MAT4X2, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<4,2,2,4> >     },
16815                 {       "OpMatrixTimesMatrix",  "4x2_3x4",      2,      MAT3X2, MAT4X2, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,3,4> >     },
16816                 {       "OpMatrixTimesMatrix",  "4x2_4x4",      2,      MAT4X2, MAT4X2, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,4,4> >     },
16817                 {       "OpMatrixTimesMatrix",  "4x3_2x4",      2,      MAT2X3, MAT4X3, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,3,2,4> >     },
16818                 {       "OpMatrixTimesMatrix",  "4x3_3x4",      2,      MAT3X3, MAT4X3, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,3,4> >     },
16819                 {       "OpMatrixTimesMatrix",  "4x3_4x4",      2,      MAT4X3, MAT4X3, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,4,4> >     },
16820                 {       "OpMatrixTimesMatrix",  "4x4_2x4",      2,      MAT2X4, MAT4X4, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,4,2,4> >     },
16821                 {       "OpMatrixTimesMatrix",  "4x4_3x4",      2,      MAT3X4, MAT4X4, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,3,4> >     },
16822                 {       "OpMatrixTimesMatrix",  "4x4_4x4",      2,      MAT4X4, MAT4X4, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,4,4> >     },
16823                 {       "OpOuterProduct",               "2x2",          2,      MAT2X2, VEC2,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  2,  0, fp16OuterProduct<2,2> >                      },
16824                 {       "OpOuterProduct",               "2x3",          2,      MAT2X3, VEC3,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  3,  2,  0, fp16OuterProduct<2,3> >                      },
16825                 {       "OpOuterProduct",               "2x4",          2,      MAT2X4, VEC4,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  2,  0, fp16OuterProduct<2,4> >                      },
16826                 {       "OpOuterProduct",               "3x2",          2,      MAT3X2, VEC2,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  3,  0, fp16OuterProduct<3,2> >                      },
16827                 {       "OpOuterProduct",               "3x3",          2,      MAT3X3, VEC3,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  3,  0, fp16OuterProduct<3,3> >                      },
16828                 {       "OpOuterProduct",               "3x4",          2,      MAT3X4, VEC4,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  3,  0, fp16OuterProduct<3,4> >                      },
16829                 {       "OpOuterProduct",               "4x2",          2,      MAT4X2, VEC2,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  4,  0, fp16OuterProduct<4,2> >                      },
16830                 {       "OpOuterProduct",               "4x3",          2,      MAT4X3, VEC3,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  4,  0, fp16OuterProduct<4,3> >                      },
16831                 {       "OpOuterProduct",               "4x4",          2,      MAT4X4, VEC4,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  4,  0, fp16OuterProduct<4,4> >                      },
16832                 {       "Determinant",                  "2x2",          1,      SCALAR, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1,  4,  0,  0, fp16Determinant<2> >                         },
16833                 {       "Determinant",                  "3x3",          1,      SCALAR, MAT3X3, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<3> >                         },
16834                 {       "Determinant",                  "4x4",          1,      SCALAR, MAT4X4, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<4> >                         },
16835                 {       "MatrixInverse",                "2x2",          1,      MAT2X2, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Inverse<2> >                                     },
16836         };
16837
16838         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16839         {
16840                 const Math16TestFunc&   testFunc        = testFuncs[testFuncIdx];
16841
16842                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), 0, testFunc);
16843         }
16844
16845         return testGroup.release();
16846 }
16847
16848 const string getNumberTypeName (const NumberType type)
16849 {
16850         if (type == NUMBERTYPE_INT32)
16851         {
16852                 return "int";
16853         }
16854         else if (type == NUMBERTYPE_UINT32)
16855         {
16856                 return "uint";
16857         }
16858         else if (type == NUMBERTYPE_FLOAT32)
16859         {
16860                 return "float";
16861         }
16862         else
16863         {
16864                 DE_ASSERT(false);
16865                 return "";
16866         }
16867 }
16868
16869 deInt32 getInt(de::Random& rnd)
16870 {
16871         return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
16872 }
16873
16874 const string repeatString (const string& str, int times)
16875 {
16876         string filler;
16877         for (int i = 0; i < times; ++i)
16878         {
16879                 filler += str;
16880         }
16881         return filler;
16882 }
16883
16884 const string getRandomConstantString (const NumberType type, de::Random& rnd)
16885 {
16886         if (type == NUMBERTYPE_INT32)
16887         {
16888                 return numberToString<deInt32>(getInt(rnd));
16889         }
16890         else if (type == NUMBERTYPE_UINT32)
16891         {
16892                 return numberToString<deUint32>(rnd.getUint32());
16893         }
16894         else if (type == NUMBERTYPE_FLOAT32)
16895         {
16896                 return numberToString<float>(rnd.getFloat());
16897         }
16898         else
16899         {
16900                 DE_ASSERT(false);
16901                 return "";
16902         }
16903 }
16904
16905 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16906 {
16907         map<string, string> params;
16908
16909         // Vec2 to Vec4
16910         for (int width = 2; width <= 4; ++width)
16911         {
16912                 const string randomConst = numberToString(getInt(rnd));
16913                 const string widthStr = numberToString(width);
16914                 const string composite_type = "${customType}vec" + widthStr;
16915                 const int index = rnd.getInt(0, width-1);
16916
16917                 params["type"]                  = "vec";
16918                 params["name"]                  = params["type"] + "_" + widthStr;
16919                 params["compositeDecl"]         = composite_type + " = OpTypeVector ${customType} " + widthStr +"\n";
16920                 params["compositeType"]         = composite_type;
16921                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16922                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct " + composite_type + repeatString(" %filler", width) + "\n";
16923                 params["indexes"]               = numberToString(index);
16924                 testCases.push_back(params);
16925         }
16926 }
16927
16928 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16929 {
16930         const int limit = 10;
16931         map<string, string> params;
16932
16933         for (int width = 2; width <= limit; ++width)
16934         {
16935                 string randomConst = numberToString(getInt(rnd));
16936                 string widthStr = numberToString(width);
16937                 int index = rnd.getInt(0, width-1);
16938
16939                 params["type"]                  = "array";
16940                 params["name"]                  = params["type"] + "_" + widthStr;
16941                 params["compositeDecl"]         = string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
16942                                                                                         +        "%composite = OpTypeArray ${customType} %arraywidth\n";
16943                 params["compositeType"]         = "%composite";
16944                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16945                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16946                 params["indexes"]               = numberToString(index);
16947                 testCases.push_back(params);
16948         }
16949 }
16950
16951 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16952 {
16953         const int limit = 10;
16954         map<string, string> params;
16955
16956         for (int width = 2; width <= limit; ++width)
16957         {
16958                 string randomConst = numberToString(getInt(rnd));
16959                 int index = rnd.getInt(0, width-1);
16960
16961                 params["type"]                  = "struct";
16962                 params["name"]                  = params["type"] + "_" + numberToString(width);
16963                 params["compositeDecl"]         = "%composite = OpTypeStruct" + repeatString(" ${customType}", width) + "\n";
16964                 params["compositeType"]         = "%composite";
16965                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16966                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16967                 params["indexes"]               = numberToString(index);
16968                 testCases.push_back(params);
16969         }
16970 }
16971
16972 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16973 {
16974         map<string, string> params;
16975
16976         // Vec2 to Vec4
16977         for (int width = 2; width <= 4; ++width)
16978         {
16979                 string widthStr = numberToString(width);
16980
16981                 for (int column = 2 ; column <= 4; ++column)
16982                 {
16983                         int index_0 = rnd.getInt(0, column-1);
16984                         int index_1 = rnd.getInt(0, width-1);
16985                         string columnStr = numberToString(column);
16986
16987                         params["type"]          = "matrix";
16988                         params["name"]          = params["type"] + "_" + widthStr + "x" + columnStr;
16989                         params["compositeDecl"] = string("%vectype   = OpTypeVector ${customType} " + widthStr + "\n")
16990                                                                                                 +        "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
16991                         params["compositeType"] = "%composite";
16992
16993                         params["filler"]        = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n"
16994                                                                                                 +        "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
16995
16996                         params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
16997                         params["indexes"]       = numberToString(index_0) + " " + numberToString(index_1);
16998                         testCases.push_back(params);
16999                 }
17000         }
17001 }
17002
17003 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17004 {
17005         createVectorCompositeCases(testCases, rnd, type);
17006         createArrayCompositeCases(testCases, rnd, type);
17007         createStructCompositeCases(testCases, rnd, type);
17008         // Matrix only supports float types
17009         if (type == NUMBERTYPE_FLOAT32)
17010         {
17011                 createMatrixCompositeCases(testCases, rnd, type);
17012         }
17013 }
17014
17015 const string getAssemblyTypeDeclaration (const NumberType type)
17016 {
17017         switch (type)
17018         {
17019                 case NUMBERTYPE_INT32:          return "OpTypeInt 32 1";
17020                 case NUMBERTYPE_UINT32:         return "OpTypeInt 32 0";
17021                 case NUMBERTYPE_FLOAT32:        return "OpTypeFloat 32";
17022                 default:                        DE_ASSERT(false); return "";
17023         }
17024 }
17025
17026 const string getAssemblyTypeName (const NumberType type)
17027 {
17028         switch (type)
17029         {
17030                 case NUMBERTYPE_INT32:          return "%i32";
17031                 case NUMBERTYPE_UINT32:         return "%u32";
17032                 case NUMBERTYPE_FLOAT32:        return "%f32";
17033                 default:                        DE_ASSERT(false); return "";
17034         }
17035 }
17036
17037 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
17038 {
17039         map<string, string>     parameters(params);
17040
17041         const string customType = getAssemblyTypeName(type);
17042         map<string, string> substCustomType;
17043         substCustomType["customType"] = customType;
17044         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17045         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17046         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17047         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17048         parameters["customType"] = customType;
17049         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17050
17051         if (parameters.at("compositeType") != "%u32vec3")
17052         {
17053                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17054         }
17055
17056         return StringTemplate(
17057                 "OpCapability Shader\n"
17058                 "OpCapability Matrix\n"
17059                 "OpMemoryModel Logical GLSL450\n"
17060                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17061                 "OpExecutionMode %main LocalSize 1 1 1\n"
17062
17063                 "OpSource GLSL 430\n"
17064                 "OpName %main           \"main\"\n"
17065                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17066
17067                 // Decorators
17068                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17069                 "OpDecorate %buf BufferBlock\n"
17070                 "OpDecorate %indata DescriptorSet 0\n"
17071                 "OpDecorate %indata Binding 0\n"
17072                 "OpDecorate %outdata DescriptorSet 0\n"
17073                 "OpDecorate %outdata Binding 1\n"
17074                 "OpDecorate %customarr ArrayStride 4\n"
17075                 "${compositeDecorator}"
17076                 "OpMemberDecorate %buf 0 Offset 0\n"
17077
17078                 // General types
17079                 "%void      = OpTypeVoid\n"
17080                 "%voidf     = OpTypeFunction %void\n"
17081                 "%u32       = OpTypeInt 32 0\n"
17082                 "%i32       = OpTypeInt 32 1\n"
17083                 "%f32       = OpTypeFloat 32\n"
17084
17085                 // Composite declaration
17086                 "${compositeDecl}"
17087
17088                 // Constants
17089                 "${filler}"
17090
17091                 "${u32vec3Decl:opt}"
17092                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17093
17094                 // Inherited from custom
17095                 "%customptr = OpTypePointer Uniform ${customType}\n"
17096                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17097                 "%buf       = OpTypeStruct %customarr\n"
17098                 "%bufptr    = OpTypePointer Uniform %buf\n"
17099
17100                 "%indata    = OpVariable %bufptr Uniform\n"
17101                 "%outdata   = OpVariable %bufptr Uniform\n"
17102
17103                 "%id        = OpVariable %uvec3ptr Input\n"
17104                 "%zero      = OpConstant %i32 0\n"
17105
17106                 "%main      = OpFunction %void None %voidf\n"
17107                 "%label     = OpLabel\n"
17108                 "%idval     = OpLoad %u32vec3 %id\n"
17109                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17110
17111                 "%inloc     = OpAccessChain %customptr %indata %zero %x\n"
17112                 "%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
17113                 // Read the input value
17114                 "%inval     = OpLoad ${customType} %inloc\n"
17115                 // Create the composite and fill it
17116                 "${compositeConstruct}"
17117                 // Insert the input value to a place
17118                 "%instance2 = OpCompositeInsert ${compositeType} %inval %instance ${indexes}\n"
17119                 // Read back the value from the position
17120                 "%out_val   = OpCompositeExtract ${customType} %instance2 ${indexes}\n"
17121                 // Store it in the output position
17122                 "             OpStore %outloc %out_val\n"
17123                 "             OpReturn\n"
17124                 "             OpFunctionEnd\n"
17125         ).specialize(parameters);
17126 }
17127
17128 template<typename T>
17129 BufferSp createCompositeBuffer(T number)
17130 {
17131         return BufferSp(new Buffer<T>(vector<T>(1, number)));
17132 }
17133
17134 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
17135 {
17136         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
17137         de::Random                                              rnd             (deStringHash(group->getName()));
17138
17139         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17140         {
17141                 NumberType                                              numberType              = NumberType(type);
17142                 const string                                    typeName                = getNumberTypeName(numberType);
17143                 const string                                    description             = "Test the OpCompositeInsert instruction with " + typeName + "s";
17144                 de::MovePtr<tcu::TestCaseGroup> subGroup                (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17145                 vector<map<string, string> >    testCases;
17146
17147                 createCompositeCases(testCases, rnd, numberType);
17148
17149                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17150                 {
17151                         ComputeShaderSpec       spec;
17152
17153                         spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
17154
17155                         switch (numberType)
17156                         {
17157                                 case NUMBERTYPE_INT32:
17158                                 {
17159                                         deInt32 number = getInt(rnd);
17160                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17161                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17162                                         break;
17163                                 }
17164                                 case NUMBERTYPE_UINT32:
17165                                 {
17166                                         deUint32 number = rnd.getUint32();
17167                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17168                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17169                                         break;
17170                                 }
17171                                 case NUMBERTYPE_FLOAT32:
17172                                 {
17173                                         float number = rnd.getFloat();
17174                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17175                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17176                                         break;
17177                                 }
17178                                 default:
17179                                         DE_ASSERT(false);
17180                         }
17181
17182                         spec.numWorkGroups = IVec3(1, 1, 1);
17183                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
17184                 }
17185                 group->addChild(subGroup.release());
17186         }
17187         return group.release();
17188 }
17189
17190 struct AssemblyStructInfo
17191 {
17192         AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
17193         : components    (comp)
17194         , index                 (idx)
17195         {}
17196
17197         deUint32 components;
17198         deUint32 index;
17199 };
17200
17201 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
17202 {
17203         // Create the full index string
17204         string                          fullIndex       = numberToString(structInfo.index) + " " + params.at("indexes");
17205         // Convert it to list of indexes
17206         vector<string>          indexes         = de::splitString(fullIndex, ' ');
17207
17208         map<string, string>     parameters      (params);
17209         parameters["structType"]        = repeatString(" ${compositeType}", structInfo.components);
17210         parameters["structConstruct"]   = repeatString(" %instance", structInfo.components);
17211         parameters["insertIndexes"]     = fullIndex;
17212
17213         // In matrix cases the last two index is the CompositeExtract indexes
17214         const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
17215
17216         // Construct the extractIndex
17217         for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
17218         {
17219                 parameters["extractIndexes"] += " " + *index;
17220         }
17221
17222         // Remove the last 1 or 2 element depends on matrix case or not
17223         indexes.erase(indexes.end() - extractIndexes, indexes.end());
17224
17225         deUint32 id = 0;
17226         // Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
17227         for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
17228         {
17229                 string indexId = "%index_" + numberToString(id++);
17230                 parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
17231                 parameters["accessChainIndexes"] += " " + indexId;
17232         }
17233
17234         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17235
17236         const string customType = getAssemblyTypeName(type);
17237         map<string, string> substCustomType;
17238         substCustomType["customType"] = customType;
17239         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17240         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17241         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17242         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17243         parameters["customType"] = customType;
17244
17245         const string compositeType = parameters.at("compositeType");
17246         map<string, string> substCompositeType;
17247         substCompositeType["compositeType"] = compositeType;
17248         parameters["structType"] = StringTemplate(parameters.at("structType")).specialize(substCompositeType);
17249         if (compositeType != "%u32vec3")
17250         {
17251                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17252         }
17253
17254         return StringTemplate(
17255                 "OpCapability Shader\n"
17256                 "OpCapability Matrix\n"
17257                 "OpMemoryModel Logical GLSL450\n"
17258                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17259                 "OpExecutionMode %main LocalSize 1 1 1\n"
17260
17261                 "OpSource GLSL 430\n"
17262                 "OpName %main           \"main\"\n"
17263                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17264                 // Decorators
17265                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17266                 "OpDecorate %buf BufferBlock\n"
17267                 "OpDecorate %indata DescriptorSet 0\n"
17268                 "OpDecorate %indata Binding 0\n"
17269                 "OpDecorate %outdata DescriptorSet 0\n"
17270                 "OpDecorate %outdata Binding 1\n"
17271                 "OpDecorate %customarr ArrayStride 4\n"
17272                 "${compositeDecorator}"
17273                 "OpMemberDecorate %buf 0 Offset 0\n"
17274                 // General types
17275                 "%void      = OpTypeVoid\n"
17276                 "%voidf     = OpTypeFunction %void\n"
17277                 "%i32       = OpTypeInt 32 1\n"
17278                 "%u32       = OpTypeInt 32 0\n"
17279                 "%f32       = OpTypeFloat 32\n"
17280                 // Custom types
17281                 "${compositeDecl}"
17282                 // %u32vec3 if not already declared in ${compositeDecl}
17283                 "${u32vec3Decl:opt}"
17284                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17285                 // Inherited from composite
17286                 "%composite_p = OpTypePointer Function ${compositeType}\n"
17287                 "%struct_t  = OpTypeStruct${structType}\n"
17288                 "%struct_p  = OpTypePointer Function %struct_t\n"
17289                 // Constants
17290                 "${filler}"
17291                 "${accessChainConstDeclaration}"
17292                 // Inherited from custom
17293                 "%customptr = OpTypePointer Uniform ${customType}\n"
17294                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17295                 "%buf       = OpTypeStruct %customarr\n"
17296                 "%bufptr    = OpTypePointer Uniform %buf\n"
17297                 "%indata    = OpVariable %bufptr Uniform\n"
17298                 "%outdata   = OpVariable %bufptr Uniform\n"
17299
17300                 "%id        = OpVariable %uvec3ptr Input\n"
17301                 "%zero      = OpConstant %u32 0\n"
17302                 "%main      = OpFunction %void None %voidf\n"
17303                 "%label     = OpLabel\n"
17304                 "%struct_v  = OpVariable %struct_p Function\n"
17305                 "%idval     = OpLoad %u32vec3 %id\n"
17306                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17307                 // Create the input/output type
17308                 "%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
17309                 "%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
17310                 // Read the input value
17311                 "%inval     = OpLoad ${customType} %inloc\n"
17312                 // Create the composite and fill it
17313                 "${compositeConstruct}"
17314                 // Create the struct and fill it with the composite
17315                 "%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
17316                 // Insert the value
17317                 "%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
17318                 // Store the object
17319                 "             OpStore %struct_v %comp_obj\n"
17320                 // Get deepest possible composite pointer
17321                 "%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
17322                 "%read_obj  = OpLoad ${compositeType} %inner_ptr\n"
17323                 // Read back the stored value
17324                 "%read_val  = OpCompositeExtract ${customType} %read_obj${extractIndexes}\n"
17325                 "             OpStore %outloc %read_val\n"
17326                 "             OpReturn\n"
17327                 "             OpFunctionEnd\n"
17328         ).specialize(parameters);
17329 }
17330
17331 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
17332 {
17333         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
17334         de::Random                                              rnd                             (deStringHash(group->getName()));
17335
17336         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17337         {
17338                 NumberType                                              numberType      = NumberType(type);
17339                 const string                                    typeName        = getNumberTypeName(numberType);
17340                 const string                                    description     = "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
17341                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17342
17343                 vector<map<string, string> >    testCases;
17344                 createCompositeCases(testCases, rnd, numberType);
17345
17346                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17347                 {
17348                         ComputeShaderSpec       spec;
17349
17350                         // Number of components inside of a struct
17351                         deUint32 structComponents = rnd.getInt(2, 8);
17352                         // Component index value
17353                         deUint32 structIndex = rnd.getInt(0, structComponents - 1);
17354                         AssemblyStructInfo structInfo(structComponents, structIndex);
17355
17356                         spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
17357
17358                         switch (numberType)
17359                         {
17360                                 case NUMBERTYPE_INT32:
17361                                 {
17362                                         deInt32 number = getInt(rnd);
17363                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17364                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17365                                         break;
17366                                 }
17367                                 case NUMBERTYPE_UINT32:
17368                                 {
17369                                         deUint32 number = rnd.getUint32();
17370                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17371                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17372                                         break;
17373                                 }
17374                                 case NUMBERTYPE_FLOAT32:
17375                                 {
17376                                         float number = rnd.getFloat();
17377                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17378                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17379                                         break;
17380                                 }
17381                                 default:
17382                                         DE_ASSERT(false);
17383                         }
17384                         spec.numWorkGroups = IVec3(1, 1, 1);
17385                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
17386                 }
17387                 group->addChild(subGroup.release());
17388         }
17389         return group.release();
17390 }
17391
17392 // If the params missing, uninitialized case
17393 const string specializeDefaultOutputShaderTemplate (const NumberType type, const map<string, string>& params = map<string, string>())
17394 {
17395         map<string, string> parameters(params);
17396
17397         parameters["customType"]        = getAssemblyTypeName(type);
17398
17399         // Declare the const value, and use it in the initializer
17400         if (params.find("constValue") != params.end())
17401         {
17402                 parameters["variableInitializer"]       = " %const";
17403         }
17404         // Uninitialized case
17405         else
17406         {
17407                 parameters["commentDecl"]       = ";";
17408         }
17409
17410         return StringTemplate(
17411                 "OpCapability Shader\n"
17412                 "OpMemoryModel Logical GLSL450\n"
17413                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17414                 "OpExecutionMode %main LocalSize 1 1 1\n"
17415                 "OpSource GLSL 430\n"
17416                 "OpName %main           \"main\"\n"
17417                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17418                 // Decorators
17419                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17420                 "OpDecorate %indata DescriptorSet 0\n"
17421                 "OpDecorate %indata Binding 0\n"
17422                 "OpDecorate %outdata DescriptorSet 0\n"
17423                 "OpDecorate %outdata Binding 1\n"
17424                 "OpDecorate %in_arr ArrayStride 4\n"
17425                 "OpDecorate %in_buf BufferBlock\n"
17426                 "OpMemberDecorate %in_buf 0 Offset 0\n"
17427                 // Base types
17428                 "%void       = OpTypeVoid\n"
17429                 "%voidf      = OpTypeFunction %void\n"
17430                 "%u32        = OpTypeInt 32 0\n"
17431                 "%i32        = OpTypeInt 32 1\n"
17432                 "%f32        = OpTypeFloat 32\n"
17433                 "%uvec3      = OpTypeVector %u32 3\n"
17434                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
17435                 "${commentDecl:opt}%const      = OpConstant ${customType} ${constValue:opt}\n"
17436                 // Derived types
17437                 "%in_ptr     = OpTypePointer Uniform ${customType}\n"
17438                 "%in_arr     = OpTypeRuntimeArray ${customType}\n"
17439                 "%in_buf     = OpTypeStruct %in_arr\n"
17440                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
17441                 "%indata     = OpVariable %in_bufptr Uniform\n"
17442                 "%outdata    = OpVariable %in_bufptr Uniform\n"
17443                 "%id         = OpVariable %uvec3ptr Input\n"
17444                 "%var_ptr    = OpTypePointer Function ${customType}\n"
17445                 // Constants
17446                 "%zero       = OpConstant %i32 0\n"
17447                 // Main function
17448                 "%main       = OpFunction %void None %voidf\n"
17449                 "%label      = OpLabel\n"
17450                 "%out_var    = OpVariable %var_ptr Function${variableInitializer:opt}\n"
17451                 "%idval      = OpLoad %uvec3 %id\n"
17452                 "%x          = OpCompositeExtract %u32 %idval 0\n"
17453                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
17454                 "%outloc     = OpAccessChain %in_ptr %outdata %zero %x\n"
17455
17456                 "%outval     = OpLoad ${customType} %out_var\n"
17457                 "              OpStore %outloc %outval\n"
17458                 "              OpReturn\n"
17459                 "              OpFunctionEnd\n"
17460         ).specialize(parameters);
17461 }
17462
17463 bool compareFloats (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
17464 {
17465         DE_ASSERT(outputAllocs.size() != 0);
17466         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17467
17468         // Use custom epsilon because of the float->string conversion
17469         const float     epsilon = 0.00001f;
17470
17471         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17472         {
17473                 vector<deUint8> expectedBytes;
17474                 float                   expected;
17475                 float                   actual;
17476
17477                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17478                 memcpy(&expected, &expectedBytes.front(), expectedBytes.size());
17479                 memcpy(&actual, outputAllocs[outputNdx]->getHostPtr(), expectedBytes.size());
17480
17481                 // Test with epsilon
17482                 if (fabs(expected - actual) > epsilon)
17483                 {
17484                         log << TestLog::Message << "Error: The actual and expected values not matching."
17485                                 << " Expected: " << expected << " Actual: " << actual << " Epsilon: " << epsilon << TestLog::EndMessage;
17486                         return false;
17487                 }
17488         }
17489         return true;
17490 }
17491
17492 // Checks if the driver crash with uninitialized cases
17493 bool passthruVerify (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
17494 {
17495         DE_ASSERT(outputAllocs.size() != 0);
17496         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17497
17498         // Copy and discard the result.
17499         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17500         {
17501                 vector<deUint8> expectedBytes;
17502                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17503
17504                 const size_t    width                   = expectedBytes.size();
17505                 vector<char>    data                    (width);
17506
17507                 memcpy(&data[0], outputAllocs[outputNdx]->getHostPtr(), width);
17508         }
17509         return true;
17510 }
17511
17512 tcu::TestCaseGroup* createShaderDefaultOutputGroup (tcu::TestContext& testCtx)
17513 {
17514         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "shader_default_output", "Test shader default output."));
17515         de::Random                                              rnd             (deStringHash(group->getName()));
17516
17517         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17518         {
17519                 NumberType                                              numberType      = NumberType(type);
17520                 const string                                    typeName        = getNumberTypeName(numberType);
17521                 const string                                    description     = "Test the OpVariable initializer with " + typeName + ".";
17522                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17523
17524                 // 2 similar subcases (initialized and uninitialized)
17525                 for (int subCase = 0; subCase < 2; ++subCase)
17526                 {
17527                         ComputeShaderSpec spec;
17528                         spec.numWorkGroups = IVec3(1, 1, 1);
17529
17530                         map<string, string>                             params;
17531
17532                         switch (numberType)
17533                         {
17534                                 case NUMBERTYPE_INT32:
17535                                 {
17536                                         deInt32 number = getInt(rnd);
17537                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17538                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17539                                         params["constValue"] = numberToString(number);
17540                                         break;
17541                                 }
17542                                 case NUMBERTYPE_UINT32:
17543                                 {
17544                                         deUint32 number = rnd.getUint32();
17545                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17546                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17547                                         params["constValue"] = numberToString(number);
17548                                         break;
17549                                 }
17550                                 case NUMBERTYPE_FLOAT32:
17551                                 {
17552                                         float number = rnd.getFloat();
17553                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17554                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17555                                         spec.verifyIO = &compareFloats;
17556                                         params["constValue"] = numberToString(number);
17557                                         break;
17558                                 }
17559                                 default:
17560                                         DE_ASSERT(false);
17561                         }
17562
17563                         // Initialized subcase
17564                         if (!subCase)
17565                         {
17566                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType, params);
17567                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "initialized", "OpVariable initializer tests.", spec));
17568                         }
17569                         // Uninitialized subcase
17570                         else
17571                         {
17572                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType);
17573                                 spec.verifyIO = &passthruVerify;
17574                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "uninitialized", "OpVariable initializer tests.", spec));
17575                         }
17576                 }
17577                 group->addChild(subGroup.release());
17578         }
17579         return group.release();
17580 }
17581
17582 tcu::TestCaseGroup* createOpNopTests (tcu::TestContext& testCtx)
17583 {
17584         de::MovePtr<tcu::TestCaseGroup> testGroup (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
17585         RGBA                                                    defaultColors[4];
17586         map<string, string>                             opNopFragments;
17587
17588         getDefaultColors(defaultColors);
17589
17590         opNopFragments["testfun"]               =
17591                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17592                 "%param1 = OpFunctionParameter %v4f32\n"
17593                 "%label_testfun = OpLabel\n"
17594                 "OpNop\n"
17595                 "OpNop\n"
17596                 "OpNop\n"
17597                 "OpNop\n"
17598                 "OpNop\n"
17599                 "OpNop\n"
17600                 "OpNop\n"
17601                 "OpNop\n"
17602                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17603                 "%b = OpFAdd %f32 %a %a\n"
17604                 "OpNop\n"
17605                 "%c = OpFSub %f32 %b %a\n"
17606                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17607                 "OpNop\n"
17608                 "OpNop\n"
17609                 "OpReturnValue %ret\n"
17610                 "OpFunctionEnd\n";
17611
17612         createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, testGroup.get());
17613
17614         return testGroup.release();
17615 }
17616
17617 tcu::TestCaseGroup* createOpNameTests (tcu::TestContext& testCtx)
17618 {
17619         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "opname","Test OpName"));
17620         RGBA                                                    defaultColors[4];
17621         map<string, string>                             opNameFragments;
17622
17623         getDefaultColors(defaultColors);
17624
17625         opNameFragments["testfun"] =
17626                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17627                 "%param1     = OpFunctionParameter %v4f32\n"
17628                 "%label_func = OpLabel\n"
17629                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17630                 "%b          = OpFAdd %f32 %a %a\n"
17631                 "%c          = OpFSub %f32 %b %a\n"
17632                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17633                 "OpReturnValue %ret\n"
17634                 "OpFunctionEnd\n";
17635
17636         opNameFragments["debug"] =
17637                 "OpName %BP_main \"not_main\"";
17638
17639         createTestsForAllStages("opname", defaultColors, defaultColors, opNameFragments, testGroup.get());
17640
17641         return testGroup.release();
17642 }
17643
17644 tcu::TestCaseGroup* createFloat16Tests (tcu::TestContext& testCtx)
17645 {
17646         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17647
17648         testGroup->addChild(createOpConstantFloat16Tests(testCtx));
17649         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITH_NAN));
17650         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITHOUT_NAN));
17651         testGroup->addChild(createFloat16FuncSet<GraphicsResources>(testCtx));
17652         testGroup->addChild(createDerivativeTests<256, 1>(testCtx));
17653         testGroup->addChild(createDerivativeTests<256, 2>(testCtx));
17654         testGroup->addChild(createDerivativeTests<256, 4>(testCtx));
17655         testGroup->addChild(createFloat16VectorExtractSet<GraphicsResources>(testCtx));
17656         testGroup->addChild(createFloat16VectorInsertSet<GraphicsResources>(testCtx));
17657         testGroup->addChild(createFloat16VectorShuffleSet<GraphicsResources>(testCtx));
17658         testGroup->addChild(createFloat16CompositeConstructSet<GraphicsResources>(testCtx));
17659         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeExtract"));
17660         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeInsert"));
17661         testGroup->addChild(createFloat16ArithmeticSet<GraphicsResources>(testCtx));
17662         testGroup->addChild(createFloat16ArithmeticSet<1, GraphicsResources>(testCtx));
17663         testGroup->addChild(createFloat16ArithmeticSet<2, GraphicsResources>(testCtx));
17664         testGroup->addChild(createFloat16ArithmeticSet<3, GraphicsResources>(testCtx));
17665         testGroup->addChild(createFloat16ArithmeticSet<4, GraphicsResources>(testCtx));
17666
17667         return testGroup.release();
17668 }
17669
17670 tcu::TestCaseGroup* createFloat16Group (tcu::TestContext& testCtx)
17671 {
17672         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17673
17674         testGroup->addChild(createFloat16OpConstantCompositeGroup(testCtx));
17675         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITH_NAN));
17676         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITHOUT_NAN));
17677         testGroup->addChild(createFloat16FuncSet<ComputeShaderSpec>(testCtx));
17678         testGroup->addChild(createFloat16VectorExtractSet<ComputeShaderSpec>(testCtx));
17679         testGroup->addChild(createFloat16VectorInsertSet<ComputeShaderSpec>(testCtx));
17680         testGroup->addChild(createFloat16VectorShuffleSet<ComputeShaderSpec>(testCtx));
17681         testGroup->addChild(createFloat16CompositeConstructSet<ComputeShaderSpec>(testCtx));
17682         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeExtract"));
17683         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeInsert"));
17684         testGroup->addChild(createFloat16ArithmeticSet<ComputeShaderSpec>(testCtx));
17685         testGroup->addChild(createFloat16ArithmeticSet<1, ComputeShaderSpec>(testCtx));
17686         testGroup->addChild(createFloat16ArithmeticSet<2, ComputeShaderSpec>(testCtx));
17687         testGroup->addChild(createFloat16ArithmeticSet<3, ComputeShaderSpec>(testCtx));
17688         testGroup->addChild(createFloat16ArithmeticSet<4, ComputeShaderSpec>(testCtx));
17689
17690         return testGroup.release();
17691 }
17692
17693 tcu::TestCaseGroup* createBoolMixedBitSizeGroup (tcu::TestContext& testCtx)
17694 {
17695         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "mixed_bitsize", "Tests boolean operands produced from instructions of different bit-sizes"));
17696
17697         de::Random                                              rnd                             (deStringHash(group->getName()));
17698         const int               numElements             = 100;
17699         vector<float>   inputData               (numElements, 0);
17700         vector<float>   outputData              (numElements, 0);
17701         fillRandomScalars(rnd, 0.0f, 100.0f, &inputData[0], 100);
17702
17703         const StringTemplate                    shaderTemplate  (
17704                 "${CAPS}\n"
17705                 "OpMemoryModel Logical GLSL450\n"
17706                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17707                 "OpExecutionMode %main LocalSize 1 1 1\n"
17708                 "OpSource GLSL 430\n"
17709                 "OpName %main           \"main\"\n"
17710                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17711
17712                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17713
17714                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
17715
17716                 "%id        = OpVariable %uvec3ptr Input\n"
17717                 "${CONST}\n"
17718                 "%main      = OpFunction %void None %voidf\n"
17719                 "%label     = OpLabel\n"
17720                 "%idval     = OpLoad %uvec3 %id\n"
17721                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17722                 "%inloc     = OpAccessChain %f32ptr %indata %c0i32 %x\n"
17723
17724                 "${TEST}\n"
17725
17726                 "%outloc    = OpAccessChain %f32ptr %outdata %c0i32 %x\n"
17727                 "             OpStore %outloc %res\n"
17728                 "             OpReturn\n"
17729                 "             OpFunctionEnd\n"
17730         );
17731
17732         // Each test case produces 4 boolean values, and we want each of these values
17733         // to come froma different combination of the available bit-sizes, so compute
17734         // all possible combinations here.
17735         vector<deUint32>        widths;
17736         widths.push_back(32);
17737         widths.push_back(16);
17738         widths.push_back(8);
17739
17740         vector<IVec4>   cases;
17741         for (size_t width0 = 0; width0 < widths.size(); width0++)
17742         {
17743                 for (size_t width1 = 0; width1 < widths.size(); width1++)
17744                 {
17745                         for (size_t width2 = 0; width2 < widths.size(); width2++)
17746                         {
17747                                 for (size_t width3 = 0; width3 < widths.size(); width3++)
17748                                 {
17749                                         cases.push_back(IVec4(widths[width0], widths[width1], widths[width2], widths[width3]));
17750                                 }
17751                         }
17752                 }
17753         }
17754
17755         for (size_t caseNdx = 0; caseNdx < cases.size(); caseNdx++)
17756         {
17757                 /// Skip cases where all bitsizes are the same, we are only interested in testing booleans produced from instructions with different native bit-sizes
17758                 if (cases[caseNdx][0] == cases[caseNdx][1] && cases[caseNdx][0] == cases[caseNdx][2] && cases[caseNdx][0] == cases[caseNdx][3])
17759                         continue;
17760
17761                 map<string, string>     specializations;
17762                 ComputeShaderSpec       spec;
17763
17764                 // Inject appropriate capabilities and reference constants depending
17765                 // on the bit-sizes required by this test case
17766                 bool hasFloat32 = cases[caseNdx][0] == 32 || cases[caseNdx][1] == 32 || cases[caseNdx][2] == 32 || cases[caseNdx][3] == 32;
17767                 bool hasFloat16 = cases[caseNdx][0] == 16 || cases[caseNdx][1] == 16 || cases[caseNdx][2] == 16 || cases[caseNdx][3] == 16;
17768                 bool hasInt8    = cases[caseNdx][0] == 8 || cases[caseNdx][1] == 8 || cases[caseNdx][2] == 8 || cases[caseNdx][3] == 8;
17769
17770                 string capsStr  = "OpCapability Shader\n";
17771                 string constStr =
17772                         "%c0i32     = OpConstant %i32 0\n"
17773                         "%c1f32     = OpConstant %f32 1.0\n"
17774                         "%c0f32     = OpConstant %f32 0.0\n";
17775
17776                 if (hasFloat32)
17777                 {
17778                         constStr        +=
17779                                 "%c10f32    = OpConstant %f32 10.0\n"
17780                                 "%c25f32    = OpConstant %f32 25.0\n"
17781                                 "%c50f32    = OpConstant %f32 50.0\n"
17782                                 "%c90f32    = OpConstant %f32 90.0\n";
17783                 }
17784
17785                 if (hasFloat16)
17786                 {
17787                         capsStr         += "OpCapability Float16\n";
17788                         constStr        +=
17789                                 "%f16       = OpTypeFloat 16\n"
17790                                 "%c10f16    = OpConstant %f16 10.0\n"
17791                                 "%c25f16    = OpConstant %f16 25.0\n"
17792                                 "%c50f16    = OpConstant %f16 50.0\n"
17793                                 "%c90f16    = OpConstant %f16 90.0\n";
17794                 }
17795
17796                 if (hasInt8)
17797                 {
17798                         capsStr         += "OpCapability Int8\n";
17799                         constStr        +=
17800                                 "%i8        = OpTypeInt 8 1\n"
17801                                 "%c10i8     = OpConstant %i8 10\n"
17802                                 "%c25i8     = OpConstant %i8 25\n"
17803                                 "%c50i8     = OpConstant %i8 50\n"
17804                                 "%c90i8     = OpConstant %i8 90\n";
17805                 }
17806
17807                 // Each invocation reads a different float32 value as input. Depending on
17808                 // the bit-sizes required by the particular test case, we also produce
17809                 // float16 and/or and int8 values by converting from the 32-bit float.
17810                 string testStr  = "";
17811                 testStr                 += "%inval32   = OpLoad %f32 %inloc\n";
17812                 if (hasFloat16)
17813                         testStr         += "%inval16   = OpFConvert %f16 %inval32\n";
17814                 if (hasInt8)
17815                         testStr         += "%inval8    = OpConvertFToS %i8 %inval32\n";
17816
17817                 // Because conversions from Float to Int round towards 0 we want our "greater" comparisons to be >=,
17818                 // that way a float32/float16 comparison such as 50.6f >= 50.0f will preserve its result
17819                 // when converted to int8, since FtoS(50.6f) results in 50. For "less" comparisons, it is the
17820                 // other way around, so in this case we want < instead of <=.
17821                 if (cases[caseNdx][0] == 32)
17822                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval32 %c25f32\n";
17823                 else if (cases[caseNdx][0] == 16)
17824                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval16 %c25f16\n";
17825                 else
17826                         testStr         += "%cmp1      = OpSGreaterThanEqual %bool %inval8 %c25i8\n";
17827
17828                 if (cases[caseNdx][1] == 32)
17829                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval32 %c50f32\n";
17830                 else if (cases[caseNdx][1] == 16)
17831                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval16 %c50f16\n";
17832                 else
17833                         testStr         += "%cmp2      = OpSLessThan %bool %inval8 %c50i8\n";
17834
17835                 if (cases[caseNdx][2] == 32)
17836                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval32 %c10f32\n";
17837                 else if (cases[caseNdx][2] == 16)
17838                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval16 %c10f16\n";
17839                 else
17840                         testStr         += "%cmp3      = OpSLessThan %bool %inval8 %c10i8\n";
17841
17842                 if (cases[caseNdx][3] == 32)
17843                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval32 %c90f32\n";
17844                 else if (cases[caseNdx][3] == 16)
17845                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval16 %c90f16\n";
17846                 else
17847                         testStr         += "%cmp4      = OpSGreaterThanEqual %bool %inval8 %c90i8\n";
17848
17849                 testStr                 += "%and1      = OpLogicalAnd %bool %cmp1 %cmp2\n";
17850                 testStr                 += "%or1       = OpLogicalOr %bool %cmp3 %cmp4\n";
17851                 testStr                 += "%or2       = OpLogicalOr %bool %and1 %or1\n";
17852                 testStr                 += "%not1      = OpLogicalNot %bool %or2\n";
17853                 testStr                 += "%res       = OpSelect %f32 %not1 %c1f32 %c0f32\n";
17854
17855                 specializations["CAPS"]         = capsStr;
17856                 specializations["CONST"]        = constStr;
17857                 specializations["TEST"]         = testStr;
17858
17859                 // Compute expected result by evaluating the boolean expression computed in the shader for each input value
17860                 for (size_t ndx = 0; ndx < numElements; ++ndx)
17861                         outputData[ndx] = !((inputData[ndx] >= 25.0f && inputData[ndx] < 50.0f) || (inputData[ndx] < 10.0f || inputData[ndx] >= 90.0f));
17862
17863                 spec.assembly = shaderTemplate.specialize(specializations);
17864                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputData)));
17865                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputData)));
17866                 spec.numWorkGroups = IVec3(numElements, 1, 1);
17867                 if (hasFloat16)
17868                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
17869                 if (hasInt8)
17870                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
17871                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
17872
17873                 string testName = "b" + de::toString(cases[caseNdx][0]) + "b" + de::toString(cases[caseNdx][1]) + "b" + de::toString(cases[caseNdx][2]) + "b" + de::toString(cases[caseNdx][3]);
17874                 group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", spec));
17875         }
17876
17877         return group.release();
17878 }
17879
17880 tcu::TestCaseGroup* createBoolGroup (tcu::TestContext& testCtx)
17881 {
17882         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "bool", "Boolean tests"));
17883
17884         testGroup->addChild(createBoolMixedBitSizeGroup(testCtx));
17885
17886         return testGroup.release();
17887 }
17888
17889 tcu::TestCaseGroup* createOpNameAbuseTests (tcu::TestContext& testCtx)
17890 {
17891         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opname_abuse", "OpName abuse tests"));
17892         vector<CaseParameter>                   abuseCases;
17893         RGBA                                                    defaultColors[4];
17894         map<string, string>                             opNameFragments;
17895
17896         getOpNameAbuseCases(abuseCases);
17897         getDefaultColors(defaultColors);
17898
17899         opNameFragments["testfun"] =
17900                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17901                 "%param1     = OpFunctionParameter %v4f32\n"
17902                 "%label_func = OpLabel\n"
17903                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17904                 "%b          = OpFAdd %f32 %a %a\n"
17905                 "%c          = OpFSub %f32 %b %a\n"
17906                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17907                 "OpReturnValue %ret\n"
17908                 "OpFunctionEnd\n";
17909
17910         for (unsigned int i = 0; i < abuseCases.size(); i++)
17911         {
17912                 string casename;
17913                 casename = string("main") + abuseCases[i].name;
17914
17915                 opNameFragments["debug"] =
17916                         "OpName %BP_main \"" + abuseCases[i].param + "\"";
17917
17918                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17919         }
17920
17921         for (unsigned int i = 0; i < abuseCases.size(); i++)
17922         {
17923                 string casename;
17924                 casename = string("b") + abuseCases[i].name;
17925
17926                 opNameFragments["debug"] =
17927                         "OpName %b \"" + abuseCases[i].param + "\"";
17928
17929                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17930         }
17931
17932         {
17933                 opNameFragments["debug"] =
17934                         "OpName %test_code \"name1\"\n"
17935                         "OpName %param1    \"name2\"\n"
17936                         "OpName %a         \"name3\"\n"
17937                         "OpName %b         \"name4\"\n"
17938                         "OpName %c         \"name5\"\n"
17939                         "OpName %ret       \"name6\"\n";
17940
17941                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17942         }
17943
17944         {
17945                 opNameFragments["debug"] =
17946                         "OpName %test_code \"the_same\"\n"
17947                         "OpName %param1    \"the_same\"\n"
17948                         "OpName %a         \"the_same\"\n"
17949                         "OpName %b         \"the_same\"\n"
17950                         "OpName %c         \"the_same\"\n"
17951                         "OpName %ret       \"the_same\"\n";
17952
17953                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17954         }
17955
17956         {
17957                 opNameFragments["debug"] =
17958                         "OpName %BP_main \"to_be\"\n"
17959                         "OpName %BP_main \"or_not\"\n"
17960                         "OpName %BP_main \"to_be\"\n";
17961
17962                 createTestsForAllStages("main_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17963         }
17964
17965         {
17966                 opNameFragments["debug"] =
17967                         "OpName %b \"to_be\"\n"
17968                         "OpName %b \"or_not\"\n"
17969                         "OpName %b \"to_be\"\n";
17970
17971                 createTestsForAllStages("b_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17972         }
17973
17974         return abuseGroup.release();
17975 }
17976
17977
17978 tcu::TestCaseGroup* createOpMemberNameAbuseTests (tcu::TestContext& testCtx)
17979 {
17980         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opmembername_abuse", "OpName abuse tests"));
17981         vector<CaseParameter>                   abuseCases;
17982         RGBA                                                    defaultColors[4];
17983         map<string, string>                             opMemberNameFragments;
17984
17985         getOpNameAbuseCases(abuseCases);
17986         getDefaultColors(defaultColors);
17987
17988         opMemberNameFragments["pre_main"] =
17989                 "%f3str = OpTypeStruct %f32 %f32 %f32\n";
17990
17991         opMemberNameFragments["testfun"] =
17992                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17993                 "%param1     = OpFunctionParameter %v4f32\n"
17994                 "%label_func = OpLabel\n"
17995                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17996                 "%b          = OpFAdd %f32 %a %a\n"
17997                 "%c          = OpFSub %f32 %b %a\n"
17998                 "%cstr       = OpCompositeConstruct %f3str %c %c %c\n"
17999                 "%d          = OpCompositeExtract %f32 %cstr 0\n"
18000                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %d %c_i32_0\n"
18001                 "OpReturnValue %ret\n"
18002                 "OpFunctionEnd\n";
18003
18004         for (unsigned int i = 0; i < abuseCases.size(); i++)
18005         {
18006                 string casename;
18007                 casename = string("f3str_x") + abuseCases[i].name;
18008
18009                 opMemberNameFragments["debug"] =
18010                         "OpMemberName %f3str 0 \"" + abuseCases[i].param + "\"";
18011
18012                 createTestsForAllStages(casename, defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18013         }
18014
18015         {
18016                 opMemberNameFragments["debug"] =
18017                         "OpMemberName %f3str 0 \"name1\"\n"
18018                         "OpMemberName %f3str 1 \"name2\"\n"
18019                         "OpMemberName %f3str 2 \"name3\"\n";
18020
18021                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18022         }
18023
18024         {
18025                 opMemberNameFragments["debug"] =
18026                         "OpMemberName %f3str 0 \"the_same\"\n"
18027                         "OpMemberName %f3str 1 \"the_same\"\n"
18028                         "OpMemberName %f3str 2 \"the_same\"\n";
18029
18030                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18031         }
18032
18033         {
18034                 opMemberNameFragments["debug"] =
18035                         "OpMemberName %f3str 0 \"to_be\"\n"
18036                         "OpMemberName %f3str 1 \"or_not\"\n"
18037                         "OpMemberName %f3str 0 \"to_be\"\n"
18038                         "OpMemberName %f3str 2 \"makes_no\"\n"
18039                         "OpMemberName %f3str 0 \"difference\"\n"
18040                         "OpMemberName %f3str 0 \"to_me\"\n";
18041
18042
18043                 createTestsForAllStages("f3str_x_has_multiple_names", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18044         }
18045
18046         return abuseGroup.release();
18047 }
18048
18049 vector<deUint32> getSparseIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18050 {
18051         vector<deUint32>        result;
18052         de::Random                      rnd             (seed);
18053
18054         result.reserve(numDataPoints);
18055
18056         for (deUint32 dataPointNdx = 0; dataPointNdx < numDataPoints; ++dataPointNdx)
18057                 result.push_back(rnd.getUint32());
18058
18059         return result;
18060 }
18061
18062 vector<deUint32> getSparseIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2)
18063 {
18064         vector<deUint32>        result;
18065
18066         result.reserve(inData1.size());
18067
18068         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18069                 result.push_back(inData1[dataPointNdx] + inData2[dataPointNdx]);
18070
18071         return result;
18072 }
18073
18074 template<class SpecResource>
18075 void createSparseIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18076 {
18077         const deUint32                  numDataPoints   = 16;
18078         const std::string               testName                ("sparse_ids");
18079         const deUint32                  seed                    (deStringHash(testName.c_str()));
18080         const vector<deUint32>  inData1                 (getSparseIdsAbuseData(numDataPoints, seed + 1));
18081         const vector<deUint32>  inData2                 (getSparseIdsAbuseData(numDataPoints, seed + 2));
18082         const vector<deUint32>  outData                 (getSparseIdsAbuseResults(inData1, inData2));
18083         const StringTemplate    preMain
18084         (
18085                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18086                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18087                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18088                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18089                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18090                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18091                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18092                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18093         );
18094         const StringTemplate    decoration
18095         (
18096                 "OpDecorate %ra_u32 ArrayStride 4\n"
18097                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18098                 "OpDecorate %SSBO32 BufferBlock\n"
18099                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18100                 "OpDecorate %ssbo_src0 Binding 0\n"
18101                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18102                 "OpDecorate %ssbo_src1 Binding 1\n"
18103                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18104                 "OpDecorate %ssbo_dst Binding 2\n"
18105         );
18106         const StringTemplate    testFun
18107         (
18108                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18109                 "    %param = OpFunctionParameter %v4f32\n"
18110
18111                 "    %entry = OpLabel\n"
18112                 "        %i = OpVariable %fp_i32 Function\n"
18113                 "             OpStore %i %c_i32_0\n"
18114                 "             OpBranch %loop\n"
18115
18116                 "     %loop = OpLabel\n"
18117                 "    %i_cmp = OpLoad %i32 %i\n"
18118                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18119                 "             OpLoopMerge %merge %next None\n"
18120                 "             OpBranchConditional %lt %write %merge\n"
18121
18122                 "    %write = OpLabel\n"
18123                 "      %ndx = OpLoad %i32 %i\n"
18124
18125                 "      %127 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18126                 "      %128 = OpLoad %u32 %127\n"
18127
18128                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18129                 "  %4194000 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18130                 "  %4194001 = OpLoad %u32 %4194000\n"
18131
18132                 "  %2097151 = OpIAdd %u32 %128 %4194001\n"
18133                 "  %2097152 = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18134                 "             OpStore %2097152 %2097151\n"
18135                 "             OpBranch %next\n"
18136
18137                 "     %next = OpLabel\n"
18138                 "    %i_cur = OpLoad %i32 %i\n"
18139                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18140                 "             OpStore %i %i_new\n"
18141                 "             OpBranch %loop\n"
18142
18143                 "    %merge = OpLabel\n"
18144                 "             OpReturnValue %param\n"
18145
18146                 "             OpFunctionEnd\n"
18147         );
18148         SpecResource                    specResource;
18149         map<string, string>             specs;
18150         VulkanFeatures                  features;
18151         map<string, string>             fragments;
18152         vector<string>                  extensions;
18153
18154         specs["num_data_points"]        = de::toString(numDataPoints);
18155
18156         fragments["decoration"]         = decoration.specialize(specs);
18157         fragments["pre_main"]           = preMain.specialize(specs);
18158         fragments["testfun"]            = testFun.specialize(specs);
18159
18160         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18161         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18162         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18163
18164         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18165 }
18166
18167 vector<deUint32> getLotsIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18168 {
18169         vector<deUint32>        result;
18170         de::Random                      rnd             (seed);
18171
18172         result.reserve(numDataPoints);
18173
18174         // Fixed value
18175         result.push_back(1u);
18176
18177         // Random values
18178         for (deUint32 dataPointNdx = 1; dataPointNdx < numDataPoints; ++dataPointNdx)
18179                 result.push_back(rnd.getUint8());
18180
18181         return result;
18182 }
18183
18184 vector<deUint32> getLotsIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2, const deUint32 count)
18185 {
18186         vector<deUint32>        result;
18187
18188         result.reserve(inData1.size());
18189
18190         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18191                 result.push_back(inData1[dataPointNdx] + count * inData2[dataPointNdx]);
18192
18193         return result;
18194 }
18195
18196 template<class SpecResource>
18197 void createLotsIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18198 {
18199         const deUint32                  numDataPoints   = 16;
18200         const deUint32                  firstNdx                = 100u;
18201         const deUint32                  sequenceCount   = 10000u;
18202         const std::string               testName                ("lots_ids");
18203         const deUint32                  seed                    (deStringHash(testName.c_str()));
18204         const vector<deUint32>  inData1                 (getLotsIdsAbuseData(numDataPoints, seed + 1));
18205         const vector<deUint32>  inData2                 (getLotsIdsAbuseData(numDataPoints, seed + 2));
18206         const vector<deUint32>  outData                 (getLotsIdsAbuseResults(inData1, inData2, sequenceCount));
18207         const StringTemplate preMain
18208         (
18209                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18210                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18211                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18212                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18213                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18214                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18215                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18216                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18217         );
18218         const StringTemplate decoration
18219         (
18220                 "OpDecorate %ra_u32 ArrayStride 4\n"
18221                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18222                 "OpDecorate %SSBO32 BufferBlock\n"
18223                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18224                 "OpDecorate %ssbo_src0 Binding 0\n"
18225                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18226                 "OpDecorate %ssbo_src1 Binding 1\n"
18227                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18228                 "OpDecorate %ssbo_dst Binding 2\n"
18229         );
18230         const StringTemplate testFun
18231         (
18232                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18233                 "    %param = OpFunctionParameter %v4f32\n"
18234
18235                 "    %entry = OpLabel\n"
18236                 "        %i = OpVariable %fp_i32 Function\n"
18237                 "             OpStore %i %c_i32_0\n"
18238                 "             OpBranch %loop\n"
18239
18240                 "     %loop = OpLabel\n"
18241                 "    %i_cmp = OpLoad %i32 %i\n"
18242                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18243                 "             OpLoopMerge %merge %next None\n"
18244                 "             OpBranchConditional %lt %write %merge\n"
18245
18246                 "    %write = OpLabel\n"
18247                 "      %ndx = OpLoad %i32 %i\n"
18248
18249                 "       %90 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18250                 "       %91 = OpLoad %u32 %90\n"
18251
18252                 "       %98 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18253                 "       %${zeroth_id} = OpLoad %u32 %98\n"
18254
18255                 "${seq}\n"
18256
18257                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18258                 "      %dst = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18259                 "             OpStore %dst %${last_id}\n"
18260                 "             OpBranch %next\n"
18261
18262                 "     %next = OpLabel\n"
18263                 "    %i_cur = OpLoad %i32 %i\n"
18264                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18265                 "             OpStore %i %i_new\n"
18266                 "             OpBranch %loop\n"
18267
18268                 "    %merge = OpLabel\n"
18269                 "             OpReturnValue %param\n"
18270
18271                 "             OpFunctionEnd\n"
18272         );
18273         deUint32                                lastId                  = firstNdx;
18274         SpecResource                    specResource;
18275         map<string, string>             specs;
18276         VulkanFeatures                  features;
18277         map<string, string>             fragments;
18278         vector<string>                  extensions;
18279         std::string                             sequence;
18280
18281         for (deUint32 sequenceNdx = 0; sequenceNdx < sequenceCount; ++sequenceNdx)
18282         {
18283                 const deUint32          sequenceId              = sequenceNdx + firstNdx;
18284                 const std::string       sequenceIdStr   = de::toString(sequenceId);
18285
18286                 sequence += "%" + sequenceIdStr + " = OpIAdd %u32 %91 %" + de::toString(sequenceId - 1) + "\n";
18287                 lastId = sequenceId;
18288
18289                 if (sequenceNdx == 0)
18290                         sequence.reserve((10 + sequence.length()) * sequenceCount);
18291         }
18292
18293         specs["num_data_points"]        = de::toString(numDataPoints);
18294         specs["zeroth_id"]                      = de::toString(firstNdx - 1);
18295         specs["last_id"]                        = de::toString(lastId);
18296         specs["seq"]                            = sequence;
18297
18298         fragments["decoration"]         = decoration.specialize(specs);
18299         fragments["pre_main"]           = preMain.specialize(specs);
18300         fragments["testfun"]            = testFun.specialize(specs);
18301
18302         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18303         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18304         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18305
18306         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18307 }
18308
18309 tcu::TestCaseGroup* createSpirvIdsAbuseTests (tcu::TestContext& testCtx)
18310 {
18311         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18312
18313         createSparseIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18314         createLotsIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18315
18316         return testGroup.release();
18317 }
18318
18319 tcu::TestCaseGroup* createSpirvIdsAbuseGroup (tcu::TestContext& testCtx)
18320 {
18321         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18322
18323         createSparseIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18324         createLotsIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18325
18326         return testGroup.release();
18327 }
18328
18329 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
18330 {
18331         const bool testComputePipeline = true;
18332
18333         de::MovePtr<tcu::TestCaseGroup> instructionTests        (new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
18334         de::MovePtr<tcu::TestCaseGroup> computeTests            (new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
18335         de::MovePtr<tcu::TestCaseGroup> graphicsTests           (new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
18336
18337         computeTests->addChild(createSpivVersionCheckTests(testCtx, testComputePipeline));
18338         computeTests->addChild(createLocalSizeGroup(testCtx));
18339         computeTests->addChild(createOpNopGroup(testCtx));
18340         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITHOUT_NAN));
18341         computeTests->addChild(createOpAtomicGroup(testCtx, false));
18342         computeTests->addChild(createOpAtomicGroup(testCtx, true));                                     // Using new StorageBuffer decoration
18343         computeTests->addChild(createOpAtomicGroup(testCtx, false, 1024, true));        // Return value validation
18344         computeTests->addChild(createOpLineGroup(testCtx));
18345         computeTests->addChild(createOpModuleProcessedGroup(testCtx));
18346         computeTests->addChild(createOpNoLineGroup(testCtx));
18347         computeTests->addChild(createOpConstantNullGroup(testCtx));
18348         computeTests->addChild(createOpConstantCompositeGroup(testCtx));
18349         computeTests->addChild(createOpConstantUsageGroup(testCtx));
18350         computeTests->addChild(createSpecConstantGroup(testCtx));
18351         computeTests->addChild(createOpSourceGroup(testCtx));
18352         computeTests->addChild(createOpSourceExtensionGroup(testCtx));
18353         computeTests->addChild(createDecorationGroupGroup(testCtx));
18354         computeTests->addChild(createOpPhiGroup(testCtx));
18355         computeTests->addChild(createLoopControlGroup(testCtx));
18356         computeTests->addChild(createFunctionControlGroup(testCtx));
18357         computeTests->addChild(createSelectionControlGroup(testCtx));
18358         computeTests->addChild(createBlockOrderGroup(testCtx));
18359         computeTests->addChild(createMultipleShaderGroup(testCtx));
18360         computeTests->addChild(createMemoryAccessGroup(testCtx));
18361         computeTests->addChild(createOpCopyMemoryGroup(testCtx));
18362         computeTests->addChild(createOpCopyObjectGroup(testCtx));
18363         computeTests->addChild(createNoContractionGroup(testCtx));
18364         computeTests->addChild(createOpUndefGroup(testCtx));
18365         computeTests->addChild(createOpUnreachableGroup(testCtx));
18366         computeTests->addChild(createOpQuantizeToF16Group(testCtx));
18367         computeTests->addChild(createOpFRemGroup(testCtx));
18368         computeTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18369         computeTests->addChild(createOpSRemComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18370         computeTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18371         computeTests->addChild(createOpSModComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18372         computeTests->addChild(createConvertComputeTests(testCtx, "OpSConvert", "sconvert"));
18373         computeTests->addChild(createConvertComputeTests(testCtx, "OpUConvert", "uconvert"));
18374         computeTests->addChild(createConvertComputeTests(testCtx, "OpFConvert", "fconvert"));
18375         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertSToF", "convertstof"));
18376         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToS", "convertftos"));
18377         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertUToF", "convertutof"));
18378         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToU", "convertftou"));
18379         computeTests->addChild(createOpCompositeInsertGroup(testCtx));
18380         computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
18381         computeTests->addChild(createShaderDefaultOutputGroup(testCtx));
18382         computeTests->addChild(createOpNMinGroup(testCtx));
18383         computeTests->addChild(createOpNMaxGroup(testCtx));
18384         computeTests->addChild(createOpNClampGroup(testCtx));
18385         {
18386                 de::MovePtr<tcu::TestCaseGroup> computeAndroidTests     (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18387
18388                 computeAndroidTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18389                 computeAndroidTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18390
18391                 computeTests->addChild(computeAndroidTests.release());
18392         }
18393
18394         computeTests->addChild(create8BitStorageComputeGroup(testCtx));
18395         computeTests->addChild(create16BitStorageComputeGroup(testCtx));
18396         computeTests->addChild(createFloatControlsComputeGroup(testCtx));
18397         computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
18398         computeTests->addChild(createCompositeInsertComputeGroup(testCtx));
18399         computeTests->addChild(createVariableInitComputeGroup(testCtx));
18400         computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
18401         computeTests->addChild(createIndexingComputeGroup(testCtx));
18402         computeTests->addChild(createVariablePointersComputeGroup(testCtx));
18403         computeTests->addChild(createPhysicalPointersComputeGroup(testCtx));
18404         computeTests->addChild(createImageSamplerComputeGroup(testCtx));
18405         computeTests->addChild(createOpNameGroup(testCtx));
18406         computeTests->addChild(createOpMemberNameGroup(testCtx));
18407         computeTests->addChild(createPointerParameterComputeGroup(testCtx));
18408         computeTests->addChild(createFloat16Group(testCtx));
18409         computeTests->addChild(createBoolGroup(testCtx));
18410         computeTests->addChild(createWorkgroupMemoryComputeGroup(testCtx));
18411         computeTests->addChild(createSpirvIdsAbuseGroup(testCtx));
18412
18413         graphicsTests->addChild(createCrossStageInterfaceTests(testCtx));
18414         graphicsTests->addChild(createSpivVersionCheckTests(testCtx, !testComputePipeline));
18415         graphicsTests->addChild(createOpNopTests(testCtx));
18416         graphicsTests->addChild(createOpSourceTests(testCtx));
18417         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
18418         graphicsTests->addChild(createOpModuleProcessedTests(testCtx));
18419         graphicsTests->addChild(createOpLineTests(testCtx));
18420         graphicsTests->addChild(createOpNoLineTests(testCtx));
18421         graphicsTests->addChild(createOpConstantNullTests(testCtx));
18422         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
18423         graphicsTests->addChild(createMemoryAccessTests(testCtx));
18424         graphicsTests->addChild(createOpUndefTests(testCtx));
18425         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
18426         graphicsTests->addChild(createModuleTests(testCtx));
18427         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
18428         graphicsTests->addChild(createOpPhiTests(testCtx));
18429         graphicsTests->addChild(createNoContractionTests(testCtx));
18430         graphicsTests->addChild(createOpQuantizeTests(testCtx));
18431         graphicsTests->addChild(createLoopTests(testCtx));
18432         graphicsTests->addChild(createSpecConstantTests(testCtx));
18433         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
18434         graphicsTests->addChild(createBarrierTests(testCtx));
18435         graphicsTests->addChild(createDecorationGroupTests(testCtx));
18436         graphicsTests->addChild(createFRemTests(testCtx));
18437         graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18438         graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18439
18440         {
18441                 de::MovePtr<tcu::TestCaseGroup> graphicsAndroidTests    (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18442
18443                 graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18444                 graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18445
18446                 graphicsTests->addChild(graphicsAndroidTests.release());
18447         }
18448         graphicsTests->addChild(createOpNameTests(testCtx));
18449         graphicsTests->addChild(createOpNameAbuseTests(testCtx));
18450         graphicsTests->addChild(createOpMemberNameAbuseTests(testCtx));
18451
18452         graphicsTests->addChild(create8BitStorageGraphicsGroup(testCtx));
18453         graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
18454         graphicsTests->addChild(createFloatControlsGraphicsGroup(testCtx));
18455         graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
18456         graphicsTests->addChild(createCompositeInsertGraphicsGroup(testCtx));
18457         graphicsTests->addChild(createVariableInitGraphicsGroup(testCtx));
18458         graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
18459         graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
18460         graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
18461         graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
18462         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpSConvert", "sconvert"));
18463         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpUConvert", "uconvert"));
18464         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpFConvert", "fconvert"));
18465         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertSToF", "convertstof"));
18466         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToS", "convertftos"));
18467         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertUToF", "convertutof"));
18468         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToU", "convertftou"));
18469         graphicsTests->addChild(createPointerParameterGraphicsGroup(testCtx));
18470         graphicsTests->addChild(createVaryingNameGraphicsGroup(testCtx));
18471         graphicsTests->addChild(createFloat16Tests(testCtx));
18472         graphicsTests->addChild(createSpirvIdsAbuseTests(testCtx));
18473
18474         instructionTests->addChild(computeTests.release());
18475         instructionTests->addChild(graphicsTests.release());
18476
18477         return instructionTests.release();
18478 }
18479
18480 } // SpirVAssembly
18481 } // vkt