Merge vk-gl-cts/vulkan-cts-1.1.4 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 "deRandom.hpp"
52 #include "tcuStringTemplate.hpp"
53
54 #include "vktSpvAsmCrossStageInterfaceTests.hpp"
55 #include "vktSpvAsm8bitStorageTests.hpp"
56 #include "vktSpvAsm16bitStorageTests.hpp"
57 #include "vktSpvAsmUboMatrixPaddingTests.hpp"
58 #include "vktSpvAsmConditionalBranchTests.hpp"
59 #include "vktSpvAsmIndexingTests.hpp"
60 #include "vktSpvAsmImageSamplerTests.hpp"
61 #include "vktSpvAsmComputeShaderCase.hpp"
62 #include "vktSpvAsmComputeShaderTestUtil.hpp"
63 #include "vktSpvAsmFloatControlsTests.hpp"
64 #include "vktSpvAsmGraphicsShaderTestUtil.hpp"
65 #include "vktSpvAsmVariablePointersTests.hpp"
66 #include "vktSpvAsmVariableInitTests.hpp"
67 #include "vktSpvAsmPointerParameterTests.hpp"
68 #include "vktSpvAsmSpirvVersionTests.hpp"
69 #include "vktTestCaseUtil.hpp"
70 #include "vktSpvAsmLoopDepLenTests.hpp"
71 #include "vktSpvAsmLoopDepInfTests.hpp"
72 #include "vktSpvAsmCompositeInsertTests.hpp"
73 #include "vktSpvAsmVaryingNameTests.hpp"
74 #include "vktSpvAsmWorkgroupMemoryTests.hpp"
75 #include "vktSpvAsmSignedIntCompareTests.hpp"
76
77 #include <cmath>
78 #include <limits>
79 #include <map>
80 #include <string>
81 #include <sstream>
82 #include <utility>
83 #include <stack>
84
85 namespace vkt
86 {
87 namespace SpirVAssembly
88 {
89
90 namespace
91 {
92
93 using namespace vk;
94 using std::map;
95 using std::string;
96 using std::vector;
97 using tcu::IVec3;
98 using tcu::IVec4;
99 using tcu::RGBA;
100 using tcu::TestLog;
101 using tcu::TestStatus;
102 using tcu::Vec4;
103 using de::UniquePtr;
104 using tcu::StringTemplate;
105 using tcu::Vec4;
106
107 const bool TEST_WITH_NAN        = true;
108 const bool TEST_WITHOUT_NAN     = false;
109
110 template<typename T>
111 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, int offset = 0)
112 {
113         T* const typedPtr = (T*)dst;
114         for (int ndx = 0; ndx < numValues; ndx++)
115                 typedPtr[offset + ndx] = de::randomScalar<T>(rnd, minValue, maxValue);
116 }
117
118 // Filter is a function that returns true if a value should pass, false otherwise.
119 template<typename T, typename FilterT>
120 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, FilterT filter, int offset = 0)
121 {
122         T* const typedPtr = (T*)dst;
123         T value;
124         for (int ndx = 0; ndx < numValues; ndx++)
125         {
126                 do
127                         value = de::randomScalar<T>(rnd, minValue, maxValue);
128                 while (!filter(value));
129
130                 typedPtr[offset + ndx] = value;
131         }
132 }
133
134 // Gets a 64-bit integer with a more logarithmic distribution
135 deInt64 randomInt64LogDistributed (de::Random& rnd)
136 {
137         deInt64 val = rnd.getUint64();
138         val &= (1ull << rnd.getInt(1, 63)) - 1;
139         if (rnd.getBool())
140                 val = -val;
141         return val;
142 }
143
144 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues)
145 {
146         for (int ndx = 0; ndx < numValues; ndx++)
147                 dst[ndx] = randomInt64LogDistributed(rnd);
148 }
149
150 template<typename FilterT>
151 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues, FilterT filter)
152 {
153         for (int ndx = 0; ndx < numValues; ndx++)
154         {
155                 deInt64 value;
156                 do {
157                         value = randomInt64LogDistributed(rnd);
158                 } while (!filter(value));
159                 dst[ndx] = value;
160         }
161 }
162
163 inline bool filterNonNegative (const deInt64 value)
164 {
165         return value >= 0;
166 }
167
168 inline bool filterPositive (const deInt64 value)
169 {
170         return value > 0;
171 }
172
173 inline bool filterNotZero (const deInt64 value)
174 {
175         return value != 0;
176 }
177
178 static void floorAll (vector<float>& values)
179 {
180         for (size_t i = 0; i < values.size(); i++)
181                 values[i] = deFloatFloor(values[i]);
182 }
183
184 static void floorAll (vector<Vec4>& values)
185 {
186         for (size_t i = 0; i < values.size(); i++)
187                 values[i] = floor(values[i]);
188 }
189
190 struct CaseParameter
191 {
192         const char*             name;
193         string                  param;
194
195         CaseParameter   (const char* case_, const string& param_) : name(case_), param(param_) {}
196 };
197
198 // Assembly code used for testing LocalSize, OpNop, OpConstant{Null|Composite}, Op[No]Line, OpSource[Continued], OpSourceExtension, OpUndef is based on GLSL source code:
199 //
200 // #version 430
201 //
202 // layout(std140, set = 0, binding = 0) readonly buffer Input {
203 //   float elements[];
204 // } input_data;
205 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
206 //   float elements[];
207 // } output_data;
208 //
209 // layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
210 //
211 // void main() {
212 //   uint x = gl_GlobalInvocationID.x;
213 //   output_data.elements[x] = -input_data.elements[x];
214 // }
215
216 static string getAsmForLocalSizeTest(bool useLiteralLocalSize, bool useSpecConstantWorkgroupSize, IVec3 workGroupSize, deUint32 ndx)
217 {
218         std::ostringstream out;
219         out << getComputeAsmShaderPreambleWithoutLocalSize();
220
221         if (useLiteralLocalSize)
222         {
223                 out << "OpExecutionMode %main LocalSize "
224                         << workGroupSize.x() << " " << workGroupSize.y() << " " << workGroupSize.z() << "\n";
225         }
226
227         out << "OpSource GLSL 430\n"
228                 "OpName %main           \"main\"\n"
229                 "OpName %id             \"gl_GlobalInvocationID\"\n"
230                 "OpDecorate %id BuiltIn GlobalInvocationId\n";
231
232         if (useSpecConstantWorkgroupSize)
233         {
234                 out << "OpDecorate %spec_0 SpecId 100\n"
235                         << "OpDecorate %spec_1 SpecId 101\n"
236                         << "OpDecorate %spec_2 SpecId 102\n"
237                         << "OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize\n";
238         }
239
240         out << getComputeAsmInputOutputBufferTraits()
241                 << getComputeAsmCommonTypes()
242                 << getComputeAsmInputOutputBuffer()
243                 << "%id        = OpVariable %uvec3ptr Input\n"
244                 << "%zero      = OpConstant %i32 0 \n";
245
246         if (useSpecConstantWorkgroupSize)
247         {
248                 out     << "%spec_0   = OpSpecConstant %u32 "<< workGroupSize.x() << "\n"
249                         << "%spec_1   = OpSpecConstant %u32 "<< workGroupSize.y() << "\n"
250                         << "%spec_2   = OpSpecConstant %u32 "<< workGroupSize.z() << "\n"
251                         << "%gl_WorkGroupSize = OpSpecConstantComposite %uvec3 %spec_0 %spec_1 %spec_2\n";
252         }
253
254         out << "%main      = OpFunction %void None %voidf\n"
255                 << "%label     = OpLabel\n"
256                 << "%idval     = OpLoad %uvec3 %id\n"
257                 << "%ndx         = OpCompositeExtract %u32 %idval " << ndx << "\n"
258
259                         "%inloc     = OpAccessChain %f32ptr %indata %zero %ndx\n"
260                         "%inval     = OpLoad %f32 %inloc\n"
261                         "%neg       = OpFNegate %f32 %inval\n"
262                         "%outloc    = OpAccessChain %f32ptr %outdata %zero %ndx\n"
263                         "             OpStore %outloc %neg\n"
264                         "             OpReturn\n"
265                         "             OpFunctionEnd\n";
266         return out.str();
267 }
268
269 tcu::TestCaseGroup* createLocalSizeGroup (tcu::TestContext& testCtx)
270 {
271         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "localsize", ""));
272         ComputeShaderSpec                               spec;
273         de::Random                                              rnd                             (deStringHash(group->getName()));
274         const deUint32                                  numElements             = 64u;
275         vector<float>                                   positiveFloats  (numElements, 0);
276         vector<float>                                   negativeFloats  (numElements, 0);
277
278         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
279
280         for (size_t ndx = 0; ndx < numElements; ++ndx)
281                 negativeFloats[ndx] = -positiveFloats[ndx];
282
283         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
284         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
285
286         spec.numWorkGroups = IVec3(numElements, 1, 1);
287
288         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, 1), 0u);
289         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize", "", spec));
290
291         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, 1), 0u);
292         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize", "", spec));
293
294         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, 1), 0u);
295         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize", "", spec));
296
297         spec.numWorkGroups = IVec3(1, 1, 1);
298
299         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(numElements, 1, 1), 0u);
300         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_x", "", spec));
301
302         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(numElements, 1, 1), 0u);
303         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_x", "", spec));
304
305         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(numElements, 1, 1), 0u);
306         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_x", "", spec));
307
308         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, numElements, 1), 1u);
309         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_y", "", spec));
310
311         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, numElements, 1), 1u);
312         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_y", "", spec));
313
314         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, numElements, 1), 1u);
315         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_y", "", spec));
316
317         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, numElements), 2u);
318         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_z", "", spec));
319
320         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, numElements), 2u);
321         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_z", "", spec));
322
323         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, numElements), 2u);
324         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_z", "", spec));
325
326         return group.release();
327 }
328
329 tcu::TestCaseGroup* createOpNopGroup (tcu::TestContext& testCtx)
330 {
331         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnop", "Test the OpNop instruction"));
332         ComputeShaderSpec                               spec;
333         de::Random                                              rnd                             (deStringHash(group->getName()));
334         const int                                               numElements             = 100;
335         vector<float>                                   positiveFloats  (numElements, 0);
336         vector<float>                                   negativeFloats  (numElements, 0);
337
338         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
339
340         for (size_t ndx = 0; ndx < numElements; ++ndx)
341                 negativeFloats[ndx] = -positiveFloats[ndx];
342
343         spec.assembly =
344                 string(getComputeAsmShaderPreamble()) +
345
346                 "OpSource GLSL 430\n"
347                 "OpName %main           \"main\"\n"
348                 "OpName %id             \"gl_GlobalInvocationID\"\n"
349
350                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
351
352                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
353
354                 + string(getComputeAsmInputOutputBuffer()) +
355
356                 "%id        = OpVariable %uvec3ptr Input\n"
357                 "%zero      = OpConstant %i32 0\n"
358
359                 "%main      = OpFunction %void None %voidf\n"
360                 "%label     = OpLabel\n"
361                 "%idval     = OpLoad %uvec3 %id\n"
362                 "%x         = OpCompositeExtract %u32 %idval 0\n"
363
364                 "             OpNop\n" // Inside a function body
365
366                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
367                 "%inval     = OpLoad %f32 %inloc\n"
368                 "%neg       = OpFNegate %f32 %inval\n"
369                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
370                 "             OpStore %outloc %neg\n"
371                 "             OpReturn\n"
372                 "             OpFunctionEnd\n";
373         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
374         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
375         spec.numWorkGroups = IVec3(numElements, 1, 1);
376
377         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNop appearing at different places", spec));
378
379         return group.release();
380 }
381
382 template<bool nanSupported>
383 bool compareFUnord (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
384 {
385         if (outputAllocs.size() != 1)
386                 return false;
387
388         vector<deUint8> input1Bytes;
389         vector<deUint8> input2Bytes;
390         vector<deUint8> expectedBytes;
391
392         inputs[0].getBytes(input1Bytes);
393         inputs[1].getBytes(input2Bytes);
394         expectedOutputs[0].getBytes(expectedBytes);
395
396         const deInt32* const    expectedOutputAsInt             = reinterpret_cast<const deInt32*>(&expectedBytes.front());
397         const deInt32* const    outputAsInt                             = static_cast<const deInt32*>(outputAllocs[0]->getHostPtr());
398         const float* const              input1AsFloat                   = reinterpret_cast<const float*>(&input1Bytes.front());
399         const float* const              input2AsFloat                   = reinterpret_cast<const float*>(&input2Bytes.front());
400         bool returnValue                                                                = true;
401
402         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(deInt32); ++idx)
403         {
404                 if (!nanSupported && (tcu::Float32(input1AsFloat[idx]).isNaN() || tcu::Float32(input2AsFloat[idx]).isNaN()))
405                         continue;
406
407                 if (outputAsInt[idx] != expectedOutputAsInt[idx])
408                 {
409                         log << TestLog::Message << "ERROR: Sub-case failed. inputs: " << input1AsFloat[idx] << "," << input2AsFloat[idx] << " output: " << outputAsInt[idx]<< " expected output: " << expectedOutputAsInt[idx] << TestLog::EndMessage;
410                         returnValue = false;
411                 }
412         }
413         return returnValue;
414 }
415
416 typedef VkBool32 (*compareFuncType) (float, float);
417
418 struct OpFUnordCase
419 {
420         const char*             name;
421         const char*             opCode;
422         compareFuncType compareFunc;
423
424                                         OpFUnordCase                    (const char* _name, const char* _opCode, compareFuncType _compareFunc)
425                                                 : name                          (_name)
426                                                 , opCode                        (_opCode)
427                                                 , compareFunc           (_compareFunc) {}
428 };
429
430 #define ADD_OPFUNORD_CASE(NAME, OPCODE, OPERATOR) \
431 do { \
432         struct compare_##NAME { static VkBool32 compare(float x, float y) { return (x OPERATOR y) ? VK_TRUE : VK_FALSE; } }; \
433         cases.push_back(OpFUnordCase(#NAME, OPCODE, compare_##NAME::compare)); \
434 } while (deGetFalse())
435
436 tcu::TestCaseGroup* createOpFUnordGroup (tcu::TestContext& testCtx, const bool testWithNan)
437 {
438         const string                                    nan                             = testWithNan ? "_nan" : "";
439         const string                                    groupName               = "opfunord" + nan;
440         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpFUnord* opcodes"));
441         de::Random                                              rnd                             (deStringHash(group->getName()));
442         const int                                               numElements             = 100;
443         vector<OpFUnordCase>                    cases;
444         string                                                  extensions              = testWithNan ? "OpExtension \"SPV_KHR_float_controls\"\n" : "";
445         string                                                  capabilities    = testWithNan ? "OpCapability SignedZeroInfNanPreserve\n" : "";
446         string                                                  exeModes                = testWithNan ? "OpExecutionMode %main SignedZeroInfNanPreserve 32\n" : "";
447         const StringTemplate                    shaderTemplate  (
448                 string(getComputeAsmShaderPreamble(capabilities, extensions, exeModes)) +
449                 "OpSource GLSL 430\n"
450                 "OpName %main           \"main\"\n"
451                 "OpName %id             \"gl_GlobalInvocationID\"\n"
452
453                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
454
455                 "OpDecorate %buf BufferBlock\n"
456                 "OpDecorate %buf2 BufferBlock\n"
457                 "OpDecorate %indata1 DescriptorSet 0\n"
458                 "OpDecorate %indata1 Binding 0\n"
459                 "OpDecorate %indata2 DescriptorSet 0\n"
460                 "OpDecorate %indata2 Binding 1\n"
461                 "OpDecorate %outdata DescriptorSet 0\n"
462                 "OpDecorate %outdata Binding 2\n"
463                 "OpDecorate %f32arr ArrayStride 4\n"
464                 "OpDecorate %i32arr ArrayStride 4\n"
465                 "OpMemberDecorate %buf 0 Offset 0\n"
466                 "OpMemberDecorate %buf2 0 Offset 0\n"
467
468                 + string(getComputeAsmCommonTypes()) +
469
470                 "%buf        = OpTypeStruct %f32arr\n"
471                 "%bufptr     = OpTypePointer Uniform %buf\n"
472                 "%indata1    = OpVariable %bufptr Uniform\n"
473                 "%indata2    = OpVariable %bufptr Uniform\n"
474
475                 "%buf2       = OpTypeStruct %i32arr\n"
476                 "%buf2ptr    = OpTypePointer Uniform %buf2\n"
477                 "%outdata    = OpVariable %buf2ptr Uniform\n"
478
479                 "%id        = OpVariable %uvec3ptr Input\n"
480                 "%zero      = OpConstant %i32 0\n"
481                 "%consti1   = OpConstant %i32 1\n"
482                 "%constf1   = OpConstant %f32 1.0\n"
483
484                 "%main      = OpFunction %void None %voidf\n"
485                 "%label     = OpLabel\n"
486                 "%idval     = OpLoad %uvec3 %id\n"
487                 "%x         = OpCompositeExtract %u32 %idval 0\n"
488
489                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
490                 "%inval1    = OpLoad %f32 %inloc1\n"
491                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
492                 "%inval2    = OpLoad %f32 %inloc2\n"
493                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
494
495                 "%result    = ${OPCODE} %bool %inval1 %inval2\n"
496                 "%int_res   = OpSelect %i32 %result %consti1 %zero\n"
497                 "             OpStore %outloc %int_res\n"
498
499                 "             OpReturn\n"
500                 "             OpFunctionEnd\n");
501
502         ADD_OPFUNORD_CASE(equal, "OpFUnordEqual", ==);
503         ADD_OPFUNORD_CASE(less, "OpFUnordLessThan", <);
504         ADD_OPFUNORD_CASE(lessequal, "OpFUnordLessThanEqual", <=);
505         ADD_OPFUNORD_CASE(greater, "OpFUnordGreaterThan", >);
506         ADD_OPFUNORD_CASE(greaterequal, "OpFUnordGreaterThanEqual", >=);
507         ADD_OPFUNORD_CASE(notequal, "OpFUnordNotEqual", !=);
508
509         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
510         {
511                 map<string, string>                     specializations;
512                 ComputeShaderSpec                       spec;
513                 const float                                     NaN                             = std::numeric_limits<float>::quiet_NaN();
514                 vector<float>                           inputFloats1    (numElements, 0);
515                 vector<float>                           inputFloats2    (numElements, 0);
516                 vector<deInt32>                         expectedInts    (numElements, 0);
517
518                 specializations["OPCODE"]       = cases[caseNdx].opCode;
519                 spec.assembly                           = shaderTemplate.specialize(specializations);
520
521                 fillRandomScalars(rnd, 1.f, 100.f, &inputFloats1[0], numElements);
522                 for (size_t ndx = 0; ndx < numElements; ++ndx)
523                 {
524                         switch (ndx % 6)
525                         {
526                                 case 0:         inputFloats2[ndx] = inputFloats1[ndx] + 1.0f; break;
527                                 case 1:         inputFloats2[ndx] = inputFloats1[ndx] - 1.0f; break;
528                                 case 2:         inputFloats2[ndx] = inputFloats1[ndx]; break;
529                                 case 3:         inputFloats2[ndx] = NaN; break;
530                                 case 4:         inputFloats2[ndx] = inputFloats1[ndx];  inputFloats1[ndx] = NaN; break;
531                                 case 5:         inputFloats2[ndx] = NaN;                                inputFloats1[ndx] = NaN; break;
532                         }
533                         expectedInts[ndx] = tcu::Float32(inputFloats1[ndx]).isNaN() || tcu::Float32(inputFloats2[ndx]).isNaN() || cases[caseNdx].compareFunc(inputFloats1[ndx], inputFloats2[ndx]);
534                 }
535
536                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
537                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
538                 spec.outputs.push_back(BufferSp(new Int32Buffer(expectedInts)));
539                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
540                 spec.verifyIO           = testWithNan ? &compareFUnord<true> : &compareFUnord<false>;
541
542                 if (testWithNan)
543                 {
544                         spec.extensions.push_back("VK_KHR_shader_float_controls");
545                         spec.requestedVulkanFeatures.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat32 = DE_TRUE;
546                 }
547
548                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
549         }
550
551         return group.release();
552 }
553
554 struct OpAtomicCase
555 {
556         const char*             name;
557         const char*             assembly;
558         const char*             retValAssembly;
559         OpAtomicType    opAtomic;
560         deInt32                 numOutputElements;
561
562                                         OpAtomicCase(const char* _name, const char* _assembly, const char* _retValAssembly, OpAtomicType _opAtomic, deInt32 _numOutputElements)
563                                                 : name                          (_name)
564                                                 , assembly                      (_assembly)
565                                                 , retValAssembly        (_retValAssembly)
566                                                 , opAtomic                      (_opAtomic)
567                                                 , numOutputElements     (_numOutputElements) {}
568 };
569
570 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx, bool useStorageBuffer, int numElements = 65535, bool verifyReturnValues = false)
571 {
572         std::string                                             groupName                       ("opatomic");
573         if (useStorageBuffer)
574                 groupName += "_storage_buffer";
575         if (verifyReturnValues)
576                 groupName += "_return_values";
577         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpAtomic* opcodes"));
578         vector<OpAtomicCase>                    cases;
579
580         const StringTemplate                    shaderTemplate  (
581
582                 string("OpCapability Shader\n") +
583                 (useStorageBuffer ? "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n" : "") +
584                 "OpMemoryModel Logical GLSL450\n"
585                 "OpEntryPoint GLCompute %main \"main\" %id\n"
586                 "OpExecutionMode %main LocalSize 1 1 1\n" +
587
588                 "OpSource GLSL 430\n"
589                 "OpName %main           \"main\"\n"
590                 "OpName %id             \"gl_GlobalInvocationID\"\n"
591
592                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
593
594                 "OpDecorate %buf ${BLOCK_DECORATION}\n"
595                 "OpDecorate %indata DescriptorSet 0\n"
596                 "OpDecorate %indata Binding 0\n"
597                 "OpDecorate %i32arr ArrayStride 4\n"
598                 "OpMemberDecorate %buf 0 Offset 0\n"
599
600                 "OpDecorate %sumbuf ${BLOCK_DECORATION}\n"
601                 "OpDecorate %sum DescriptorSet 0\n"
602                 "OpDecorate %sum Binding 1\n"
603                 "OpMemberDecorate %sumbuf 0 Coherent\n"
604                 "OpMemberDecorate %sumbuf 0 Offset 0\n"
605
606                 "${RETVAL_BUF_DECORATE}"
607
608                 + getComputeAsmCommonTypes("${BLOCK_POINTER_TYPE}") +
609
610                 "%buf       = OpTypeStruct %i32arr\n"
611                 "%bufptr    = OpTypePointer ${BLOCK_POINTER_TYPE} %buf\n"
612                 "%indata    = OpVariable %bufptr ${BLOCK_POINTER_TYPE}\n"
613
614                 "%sumbuf    = OpTypeStruct %i32arr\n"
615                 "%sumbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %sumbuf\n"
616                 "%sum       = OpVariable %sumbufptr ${BLOCK_POINTER_TYPE}\n"
617
618                 "${RETVAL_BUF_DECL}"
619
620                 "%id        = OpVariable %uvec3ptr Input\n"
621                 "%minusone  = OpConstant %i32 -1\n"
622                 "%zero      = OpConstant %i32 0\n"
623                 "%one       = OpConstant %u32 1\n"
624                 "%two       = OpConstant %i32 2\n"
625
626                 "%main      = OpFunction %void None %voidf\n"
627                 "%label     = OpLabel\n"
628                 "%idval     = OpLoad %uvec3 %id\n"
629                 "%x         = OpCompositeExtract %u32 %idval 0\n"
630
631                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
632                 "%inval     = OpLoad %i32 %inloc\n"
633
634                 "%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
635                 "${INSTRUCTION}"
636                 "${RETVAL_ASSEMBLY}"
637
638                 "             OpReturn\n"
639                 "             OpFunctionEnd\n");
640
641         #define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS) \
642         do { \
643                 DE_ASSERT((NUM_OUTPUT_ELEMENTS) == 1 || (NUM_OUTPUT_ELEMENTS) == numElements); \
644                 cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS)); \
645         } while (deGetFalse())
646         #define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, 1)
647         #define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, numElements)
648
649         ADD_OPATOMIC_CASE_1(iadd,       "%retv      = OpAtomicIAdd %i32 %outloc %one %zero %inval\n",
650                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IADD );
651         ADD_OPATOMIC_CASE_1(isub,       "%retv      = OpAtomicISub %i32 %outloc %one %zero %inval\n",
652                                                                 "             OpStore %retloc %retv\n", OPATOMIC_ISUB );
653         ADD_OPATOMIC_CASE_1(iinc,       "%retv      = OpAtomicIIncrement %i32 %outloc %one %zero\n",
654                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IINC );
655         ADD_OPATOMIC_CASE_1(idec,       "%retv      = OpAtomicIDecrement %i32 %outloc %one %zero\n",
656                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IDEC );
657         if (!verifyReturnValues)
658         {
659                 ADD_OPATOMIC_CASE_N(load,       "%inval2    = OpAtomicLoad %i32 %inloc %one %zero\n"
660                                                                         "             OpStore %outloc %inval2\n", "", OPATOMIC_LOAD );
661                 ADD_OPATOMIC_CASE_N(store,      "             OpAtomicStore %outloc %one %zero %inval\n", "", OPATOMIC_STORE );
662         }
663
664         ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
665                                                                 "             OpStore %outloc %even\n"
666                                                                 "%retv      = OpAtomicCompareExchange %i32 %outloc %one %zero %zero %minusone %zero\n",
667                                                                 "                         OpStore %retloc %retv\n", OPATOMIC_COMPEX );
668
669
670         #undef ADD_OPATOMIC_CASE
671         #undef ADD_OPATOMIC_CASE_1
672         #undef ADD_OPATOMIC_CASE_N
673
674         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
675         {
676                 map<string, string>                     specializations;
677                 ComputeShaderSpec                       spec;
678                 vector<deInt32>                         inputInts               (numElements, 0);
679                 vector<deInt32>                         expected                (cases[caseNdx].numOutputElements, -1);
680
681                 specializations["INDEX"]                                = (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
682                 specializations["INSTRUCTION"]                  = cases[caseNdx].assembly;
683                 specializations["BLOCK_DECORATION"]             = useStorageBuffer ? "Block" : "BufferBlock";
684                 specializations["BLOCK_POINTER_TYPE"]   = useStorageBuffer ? "StorageBuffer" : "Uniform";
685
686                 if (verifyReturnValues)
687                 {
688                         const StringTemplate blockDecoration    (
689                                 "\n"
690                                 "OpDecorate %retbuf ${BLOCK_DECORATION}\n"
691                                 "OpDecorate %ret DescriptorSet 0\n"
692                                 "OpDecorate %ret Binding 2\n"
693                                 "OpMemberDecorate %retbuf 0 Offset 0\n\n");
694
695                         const StringTemplate blockDeclaration   (
696                                 "\n"
697                                 "%retbuf    = OpTypeStruct %i32arr\n"
698                                 "%retbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %retbuf\n"
699                                 "%ret       = OpVariable %retbufptr ${BLOCK_POINTER_TYPE}\n\n");
700
701                         specializations["RETVAL_ASSEMBLY"] =
702                                 "%retloc    = OpAccessChain %i32ptr %ret %zero %x\n"
703                                 + std::string(cases[caseNdx].retValAssembly);
704
705                         specializations["RETVAL_BUF_DECORATE"]  = blockDecoration.specialize(specializations);
706                         specializations["RETVAL_BUF_DECL"]              = blockDeclaration.specialize(specializations);
707                 }
708                 else
709                 {
710                         specializations["RETVAL_ASSEMBLY"]              = "";
711                         specializations["RETVAL_BUF_DECORATE"]  = "";
712                         specializations["RETVAL_BUF_DECL"]              = "";
713                 }
714
715                 spec.assembly                                                   = shaderTemplate.specialize(specializations);
716
717                 if (useStorageBuffer)
718                         spec.extensions.push_back("VK_KHR_storage_buffer_storage_class");
719
720                 spec.inputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_INPUT)));
721                 spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_EXPECTED)));
722                 if (verifyReturnValues)
723                         spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_ATOMIC_RET)));
724                 spec.numWorkGroups = IVec3(numElements, 1, 1);
725
726                 if (verifyReturnValues)
727                 {
728                         switch (cases[caseNdx].opAtomic)
729                         {
730                                 case OPATOMIC_IADD:
731                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IADD>;
732                                         break;
733                                 case OPATOMIC_ISUB:
734                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_ISUB>;
735                                         break;
736                                 case OPATOMIC_IINC:
737                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IINC>;
738                                         break;
739                                 case OPATOMIC_IDEC:
740                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IDEC>;
741                                         break;
742                                 case OPATOMIC_COMPEX:
743                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_COMPEX>;
744                                         break;
745                                 default:
746                                         DE_FATAL("Unsupported OpAtomic type for return value verification");
747                         }
748                 }
749                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
750         }
751
752         return group.release();
753 }
754
755 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
756 {
757         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
758         ComputeShaderSpec                               spec;
759         de::Random                                              rnd                             (deStringHash(group->getName()));
760         const int                                               numElements             = 100;
761         vector<float>                                   positiveFloats  (numElements, 0);
762         vector<float>                                   negativeFloats  (numElements, 0);
763
764         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
765
766         for (size_t ndx = 0; ndx < numElements; ++ndx)
767                 negativeFloats[ndx] = -positiveFloats[ndx];
768
769         spec.assembly =
770                 string(getComputeAsmShaderPreamble()) +
771
772                 "%fname1 = OpString \"negateInputs.comp\"\n"
773                 "%fname2 = OpString \"negateInputs\"\n"
774
775                 "OpSource GLSL 430\n"
776                 "OpName %main           \"main\"\n"
777                 "OpName %id             \"gl_GlobalInvocationID\"\n"
778
779                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
780
781                 + string(getComputeAsmInputOutputBufferTraits()) +
782
783                 "OpLine %fname1 0 0\n" // At the earliest possible position
784
785                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
786
787                 "OpLine %fname1 0 1\n" // Multiple OpLines in sequence
788                 "OpLine %fname2 1 0\n" // Different filenames
789                 "OpLine %fname1 1000 100000\n"
790
791                 "%id        = OpVariable %uvec3ptr Input\n"
792                 "%zero      = OpConstant %i32 0\n"
793
794                 "OpLine %fname1 1 1\n" // Before a function
795
796                 "%main      = OpFunction %void None %voidf\n"
797                 "%label     = OpLabel\n"
798
799                 "OpLine %fname1 1 1\n" // In a function
800
801                 "%idval     = OpLoad %uvec3 %id\n"
802                 "%x         = OpCompositeExtract %u32 %idval 0\n"
803                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
804                 "%inval     = OpLoad %f32 %inloc\n"
805                 "%neg       = OpFNegate %f32 %inval\n"
806                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
807                 "             OpStore %outloc %neg\n"
808                 "             OpReturn\n"
809                 "             OpFunctionEnd\n";
810         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
811         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
812         spec.numWorkGroups = IVec3(numElements, 1, 1);
813
814         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
815
816         return group.release();
817 }
818
819 bool veryfiBinaryShader (const ProgramBinary& binary)
820 {
821         const size_t    paternCount                     = 3u;
822         bool paternsCheck[paternCount]          =
823         {
824                 false, false, false
825         };
826         const string patersns[paternCount]      =
827         {
828                 "VULKAN CTS",
829                 "Negative values",
830                 "Date: 2017/09/21"
831         };
832         size_t                  paternNdx               = 0u;
833
834         for (size_t ndx = 0u; ndx < binary.getSize(); ++ndx)
835         {
836                 if (false == paternsCheck[paternNdx] &&
837                         patersns[paternNdx][0] == static_cast<char>(binary.getBinary()[ndx]) &&
838                         deMemoryEqual((const char*)&binary.getBinary()[ndx], &patersns[paternNdx][0], patersns[paternNdx].length()))
839                 {
840                         paternsCheck[paternNdx]= true;
841                         paternNdx++;
842                         if (paternNdx == paternCount)
843                                 break;
844                 }
845         }
846
847         for (size_t ndx = 0u; ndx < paternCount; ++ndx)
848         {
849                 if (!paternsCheck[ndx])
850                         return false;
851         }
852
853         return true;
854 }
855
856 tcu::TestCaseGroup* createOpModuleProcessedGroup (tcu::TestContext& testCtx)
857 {
858         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "Test the OpModuleProcessed instruction"));
859         ComputeShaderSpec                               spec;
860         de::Random                                              rnd                             (deStringHash(group->getName()));
861         const int                                               numElements             = 10;
862         vector<float>                                   positiveFloats  (numElements, 0);
863         vector<float>                                   negativeFloats  (numElements, 0);
864
865         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
866
867         for (size_t ndx = 0; ndx < numElements; ++ndx)
868                 negativeFloats[ndx] = -positiveFloats[ndx];
869
870         spec.assembly =
871                 string(getComputeAsmShaderPreamble()) +
872                 "%fname = OpString \"negateInputs.comp\"\n"
873
874                 "OpSource GLSL 430\n"
875                 "OpName %main           \"main\"\n"
876                 "OpName %id             \"gl_GlobalInvocationID\"\n"
877                 "OpModuleProcessed \"VULKAN CTS\"\n"                                    //OpModuleProcessed;
878                 "OpModuleProcessed \"Negative values\"\n"
879                 "OpModuleProcessed \"Date: 2017/09/21\"\n"
880                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
881
882                 + string(getComputeAsmInputOutputBufferTraits())
883
884                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
885
886                 "OpLine %fname 0 1\n"
887
888                 "OpLine %fname 1000 1\n"
889
890                 "%id        = OpVariable %uvec3ptr Input\n"
891                 "%zero      = OpConstant %i32 0\n"
892                 "%main      = OpFunction %void None %voidf\n"
893
894                 "%label     = OpLabel\n"
895                 "%idval     = OpLoad %uvec3 %id\n"
896                 "%x         = OpCompositeExtract %u32 %idval 0\n"
897
898                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
899                 "%inval     = OpLoad %f32 %inloc\n"
900                 "%neg       = OpFNegate %f32 %inval\n"
901                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
902                 "             OpStore %outloc %neg\n"
903                 "             OpReturn\n"
904                 "             OpFunctionEnd\n";
905         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
906         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
907         spec.numWorkGroups = IVec3(numElements, 1, 1);
908         spec.verifyBinary = veryfiBinaryShader;
909         spec.spirvVersion = SPIRV_VERSION_1_3;
910
911         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpModuleProcessed Tests", spec));
912
913         return group.release();
914 }
915
916 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
917 {
918         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
919         ComputeShaderSpec                               spec;
920         de::Random                                              rnd                             (deStringHash(group->getName()));
921         const int                                               numElements             = 100;
922         vector<float>                                   positiveFloats  (numElements, 0);
923         vector<float>                                   negativeFloats  (numElements, 0);
924
925         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
926
927         for (size_t ndx = 0; ndx < numElements; ++ndx)
928                 negativeFloats[ndx] = -positiveFloats[ndx];
929
930         spec.assembly =
931                 string(getComputeAsmShaderPreamble()) +
932
933                 "%fname = OpString \"negateInputs.comp\"\n"
934
935                 "OpSource GLSL 430\n"
936                 "OpName %main           \"main\"\n"
937                 "OpName %id             \"gl_GlobalInvocationID\"\n"
938
939                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
940
941                 + string(getComputeAsmInputOutputBufferTraits()) +
942
943                 "OpNoLine\n" // At the earliest possible position, without preceding OpLine
944
945                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
946
947                 "OpLine %fname 0 1\n"
948                 "OpNoLine\n" // Immediately following a preceding OpLine
949
950                 "OpLine %fname 1000 1\n"
951
952                 "%id        = OpVariable %uvec3ptr Input\n"
953                 "%zero      = OpConstant %i32 0\n"
954
955                 "OpNoLine\n" // Contents after the previous OpLine
956
957                 "%main      = OpFunction %void None %voidf\n"
958                 "%label     = OpLabel\n"
959                 "%idval     = OpLoad %uvec3 %id\n"
960                 "%x         = OpCompositeExtract %u32 %idval 0\n"
961
962                 "OpNoLine\n" // Multiple OpNoLine
963                 "OpNoLine\n"
964                 "OpNoLine\n"
965
966                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
967                 "%inval     = OpLoad %f32 %inloc\n"
968                 "%neg       = OpFNegate %f32 %inval\n"
969                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
970                 "             OpStore %outloc %neg\n"
971                 "             OpReturn\n"
972                 "             OpFunctionEnd\n";
973         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
974         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
975         spec.numWorkGroups = IVec3(numElements, 1, 1);
976
977         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
978
979         return group.release();
980 }
981
982 // Compare instruction for the contraction compute case.
983 // Returns true if the output is what is expected from the test case.
984 bool compareNoContractCase(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
985 {
986         if (outputAllocs.size() != 1)
987                 return false;
988
989         // Only size is needed because we are not comparing the exact values.
990         size_t byteSize = expectedOutputs[0].getByteSize();
991
992         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
993
994         for(size_t i = 0; i < byteSize / sizeof(float); ++i) {
995                 if (outputAsFloat[i] != 0.f &&
996                         outputAsFloat[i] != -ldexp(1, -24)) {
997                         return false;
998                 }
999         }
1000
1001         return true;
1002 }
1003
1004 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
1005 {
1006         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
1007         vector<CaseParameter>                   cases;
1008         const int                                               numElements             = 100;
1009         vector<float>                                   inputFloats1    (numElements, 0);
1010         vector<float>                                   inputFloats2    (numElements, 0);
1011         vector<float>                                   outputFloats    (numElements, 0);
1012         const StringTemplate                    shaderTemplate  (
1013                 string(getComputeAsmShaderPreamble()) +
1014
1015                 "OpName %main           \"main\"\n"
1016                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1017
1018                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1019
1020                 "${DECORATION}\n"
1021
1022                 "OpDecorate %buf BufferBlock\n"
1023                 "OpDecorate %indata1 DescriptorSet 0\n"
1024                 "OpDecorate %indata1 Binding 0\n"
1025                 "OpDecorate %indata2 DescriptorSet 0\n"
1026                 "OpDecorate %indata2 Binding 1\n"
1027                 "OpDecorate %outdata DescriptorSet 0\n"
1028                 "OpDecorate %outdata Binding 2\n"
1029                 "OpDecorate %f32arr ArrayStride 4\n"
1030                 "OpMemberDecorate %buf 0 Offset 0\n"
1031
1032                 + string(getComputeAsmCommonTypes()) +
1033
1034                 "%buf        = OpTypeStruct %f32arr\n"
1035                 "%bufptr     = OpTypePointer Uniform %buf\n"
1036                 "%indata1    = OpVariable %bufptr Uniform\n"
1037                 "%indata2    = OpVariable %bufptr Uniform\n"
1038                 "%outdata    = OpVariable %bufptr Uniform\n"
1039
1040                 "%id         = OpVariable %uvec3ptr Input\n"
1041                 "%zero       = OpConstant %i32 0\n"
1042                 "%c_f_m1     = OpConstant %f32 -1.\n"
1043
1044                 "%main       = OpFunction %void None %voidf\n"
1045                 "%label      = OpLabel\n"
1046                 "%idval      = OpLoad %uvec3 %id\n"
1047                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1048                 "%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
1049                 "%inval1     = OpLoad %f32 %inloc1\n"
1050                 "%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
1051                 "%inval2     = OpLoad %f32 %inloc2\n"
1052                 "%mul        = OpFMul %f32 %inval1 %inval2\n"
1053                 "%add        = OpFAdd %f32 %mul %c_f_m1\n"
1054                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
1055                 "              OpStore %outloc %add\n"
1056                 "              OpReturn\n"
1057                 "              OpFunctionEnd\n");
1058
1059         cases.push_back(CaseParameter("multiplication", "OpDecorate %mul NoContraction"));
1060         cases.push_back(CaseParameter("addition",               "OpDecorate %add NoContraction"));
1061         cases.push_back(CaseParameter("both",                   "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
1062
1063         for (size_t ndx = 0; ndx < numElements; ++ndx)
1064         {
1065                 inputFloats1[ndx]       = 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
1066                 inputFloats2[ndx]       = 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
1067                 // Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
1068                 // conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
1069                 // So the final result will be 0.f or 0x1p-24.
1070                 // If the operation is combined into a precise fused multiply-add, then the result would be
1071                 // 2^-46 (0xa8800000).
1072                 outputFloats[ndx]       = 0.f;
1073         }
1074
1075         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
1076         {
1077                 map<string, string>             specializations;
1078                 ComputeShaderSpec               spec;
1079
1080                 specializations["DECORATION"] = cases[caseNdx].param;
1081                 spec.assembly = shaderTemplate.specialize(specializations);
1082                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1083                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1084                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1085                 spec.numWorkGroups = IVec3(numElements, 1, 1);
1086                 // Check against the two possible answers based on rounding mode.
1087                 spec.verifyIO = &compareNoContractCase;
1088
1089                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
1090         }
1091         return group.release();
1092 }
1093
1094 bool compareFRem(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1095 {
1096         if (outputAllocs.size() != 1)
1097                 return false;
1098
1099         vector<deUint8> expectedBytes;
1100         expectedOutputs[0].getBytes(expectedBytes);
1101
1102         const float*    expectedOutputAsFloat   = reinterpret_cast<const float*>(&expectedBytes.front());
1103         const float*    outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1104
1105         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(float); ++idx)
1106         {
1107                 const float f0 = expectedOutputAsFloat[idx];
1108                 const float f1 = outputAsFloat[idx];
1109                 // \todo relative error needs to be fairly high because FRem may be implemented as
1110                 // (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
1111                 if (deFloatAbs((f1 - f0) / f0) > 0.02)
1112                         return false;
1113         }
1114
1115         return true;
1116 }
1117
1118 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
1119 {
1120         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
1121         ComputeShaderSpec                               spec;
1122         de::Random                                              rnd                             (deStringHash(group->getName()));
1123         const int                                               numElements             = 200;
1124         vector<float>                                   inputFloats1    (numElements, 0);
1125         vector<float>                                   inputFloats2    (numElements, 0);
1126         vector<float>                                   outputFloats    (numElements, 0);
1127
1128         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1129         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
1130
1131         for (size_t ndx = 0; ndx < numElements; ++ndx)
1132         {
1133                 // Guard against divisors near zero.
1134                 if (std::fabs(inputFloats2[ndx]) < 1e-3)
1135                         inputFloats2[ndx] = 8.f;
1136
1137                 // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1138                 outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
1139         }
1140
1141         spec.assembly =
1142                 string(getComputeAsmShaderPreamble()) +
1143
1144                 "OpName %main           \"main\"\n"
1145                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1146
1147                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1148
1149                 "OpDecorate %buf BufferBlock\n"
1150                 "OpDecorate %indata1 DescriptorSet 0\n"
1151                 "OpDecorate %indata1 Binding 0\n"
1152                 "OpDecorate %indata2 DescriptorSet 0\n"
1153                 "OpDecorate %indata2 Binding 1\n"
1154                 "OpDecorate %outdata DescriptorSet 0\n"
1155                 "OpDecorate %outdata Binding 2\n"
1156                 "OpDecorate %f32arr ArrayStride 4\n"
1157                 "OpMemberDecorate %buf 0 Offset 0\n"
1158
1159                 + string(getComputeAsmCommonTypes()) +
1160
1161                 "%buf        = OpTypeStruct %f32arr\n"
1162                 "%bufptr     = OpTypePointer Uniform %buf\n"
1163                 "%indata1    = OpVariable %bufptr Uniform\n"
1164                 "%indata2    = OpVariable %bufptr Uniform\n"
1165                 "%outdata    = OpVariable %bufptr Uniform\n"
1166
1167                 "%id        = OpVariable %uvec3ptr Input\n"
1168                 "%zero      = OpConstant %i32 0\n"
1169
1170                 "%main      = OpFunction %void None %voidf\n"
1171                 "%label     = OpLabel\n"
1172                 "%idval     = OpLoad %uvec3 %id\n"
1173                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1174                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1175                 "%inval1    = OpLoad %f32 %inloc1\n"
1176                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1177                 "%inval2    = OpLoad %f32 %inloc2\n"
1178                 "%rem       = OpFRem %f32 %inval1 %inval2\n"
1179                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1180                 "             OpStore %outloc %rem\n"
1181                 "             OpReturn\n"
1182                 "             OpFunctionEnd\n";
1183
1184         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1185         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1186         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1187         spec.numWorkGroups = IVec3(numElements, 1, 1);
1188         spec.verifyIO = &compareFRem;
1189
1190         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1191
1192         return group.release();
1193 }
1194
1195 bool compareNMin (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1196 {
1197         if (outputAllocs.size() != 1)
1198                 return false;
1199
1200         const BufferSp&                 expectedOutput                  (expectedOutputs[0].getBuffer());
1201         std::vector<deUint8>    data;
1202         expectedOutput->getBytes(data);
1203
1204         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1205         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1206
1207         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1208         {
1209                 const float f0 = expectedOutputAsFloat[idx];
1210                 const float f1 = outputAsFloat[idx];
1211
1212                 // For NMin, we accept NaN as output if both inputs were NaN.
1213                 // Otherwise the NaN is the wrong choise, as on architectures that
1214                 // do not handle NaN, those are huge values.
1215                 if (!(tcu::Float32(f1).isNaN() && tcu::Float32(f0).isNaN()) && deFloatAbs(f1 - f0) > 0.00001f)
1216                         return false;
1217         }
1218
1219         return true;
1220 }
1221
1222 tcu::TestCaseGroup* createOpNMinGroup (tcu::TestContext& testCtx)
1223 {
1224         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnmin", "Test the OpNMin instruction"));
1225         ComputeShaderSpec                               spec;
1226         de::Random                                              rnd                             (deStringHash(group->getName()));
1227         const int                                               numElements             = 200;
1228         vector<float>                                   inputFloats1    (numElements, 0);
1229         vector<float>                                   inputFloats2    (numElements, 0);
1230         vector<float>                                   outputFloats    (numElements, 0);
1231
1232         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1233         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1234
1235         // Make the first case a full-NAN case.
1236         inputFloats1[0] = TCU_NAN;
1237         inputFloats2[0] = TCU_NAN;
1238
1239         for (size_t ndx = 0; ndx < numElements; ++ndx)
1240         {
1241                 // By default, pick the smallest
1242                 outputFloats[ndx] = std::min(inputFloats1[ndx], inputFloats2[ndx]);
1243
1244                 // Make half of the cases NaN cases
1245                 if ((ndx & 1) == 0)
1246                 {
1247                         // Alternate between the NaN operand
1248                         if ((ndx & 2) == 0)
1249                         {
1250                                 outputFloats[ndx] = inputFloats2[ndx];
1251                                 inputFloats1[ndx] = TCU_NAN;
1252                         }
1253                         else
1254                         {
1255                                 outputFloats[ndx] = inputFloats1[ndx];
1256                                 inputFloats2[ndx] = TCU_NAN;
1257                         }
1258                 }
1259         }
1260
1261         spec.assembly =
1262                 "OpCapability Shader\n"
1263                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1264                 "OpMemoryModel Logical GLSL450\n"
1265                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1266                 "OpExecutionMode %main LocalSize 1 1 1\n"
1267
1268                 "OpName %main           \"main\"\n"
1269                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1270
1271                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1272
1273                 "OpDecorate %buf BufferBlock\n"
1274                 "OpDecorate %indata1 DescriptorSet 0\n"
1275                 "OpDecorate %indata1 Binding 0\n"
1276                 "OpDecorate %indata2 DescriptorSet 0\n"
1277                 "OpDecorate %indata2 Binding 1\n"
1278                 "OpDecorate %outdata DescriptorSet 0\n"
1279                 "OpDecorate %outdata Binding 2\n"
1280                 "OpDecorate %f32arr ArrayStride 4\n"
1281                 "OpMemberDecorate %buf 0 Offset 0\n"
1282
1283                 + string(getComputeAsmCommonTypes()) +
1284
1285                 "%buf        = OpTypeStruct %f32arr\n"
1286                 "%bufptr     = OpTypePointer Uniform %buf\n"
1287                 "%indata1    = OpVariable %bufptr Uniform\n"
1288                 "%indata2    = OpVariable %bufptr Uniform\n"
1289                 "%outdata    = OpVariable %bufptr Uniform\n"
1290
1291                 "%id        = OpVariable %uvec3ptr Input\n"
1292                 "%zero      = OpConstant %i32 0\n"
1293
1294                 "%main      = OpFunction %void None %voidf\n"
1295                 "%label     = OpLabel\n"
1296                 "%idval     = OpLoad %uvec3 %id\n"
1297                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1298                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1299                 "%inval1    = OpLoad %f32 %inloc1\n"
1300                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1301                 "%inval2    = OpLoad %f32 %inloc2\n"
1302                 "%rem       = OpExtInst %f32 %std450 NMin %inval1 %inval2\n"
1303                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1304                 "             OpStore %outloc %rem\n"
1305                 "             OpReturn\n"
1306                 "             OpFunctionEnd\n";
1307
1308         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1309         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1310         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1311         spec.numWorkGroups = IVec3(numElements, 1, 1);
1312         spec.verifyIO = &compareNMin;
1313
1314         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1315
1316         return group.release();
1317 }
1318
1319 bool compareNMax (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1320 {
1321         if (outputAllocs.size() != 1)
1322                 return false;
1323
1324         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1325         std::vector<deUint8>    data;
1326         expectedOutput->getBytes(data);
1327
1328         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1329         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1330
1331         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1332         {
1333                 const float f0 = expectedOutputAsFloat[idx];
1334                 const float f1 = outputAsFloat[idx];
1335
1336                 // For NMax, NaN is considered acceptable result, since in
1337                 // architectures that do not handle NaNs, those are huge values.
1338                 if (!tcu::Float32(f1).isNaN() && deFloatAbs(f1 - f0) > 0.00001f)
1339                         return false;
1340         }
1341
1342         return true;
1343 }
1344
1345 tcu::TestCaseGroup* createOpNMaxGroup (tcu::TestContext& testCtx)
1346 {
1347         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opnmax", "Test the OpNMax instruction"));
1348         ComputeShaderSpec                               spec;
1349         de::Random                                              rnd                             (deStringHash(group->getName()));
1350         const int                                               numElements             = 200;
1351         vector<float>                                   inputFloats1    (numElements, 0);
1352         vector<float>                                   inputFloats2    (numElements, 0);
1353         vector<float>                                   outputFloats    (numElements, 0);
1354
1355         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1356         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1357
1358         // Make the first case a full-NAN case.
1359         inputFloats1[0] = TCU_NAN;
1360         inputFloats2[0] = TCU_NAN;
1361
1362         for (size_t ndx = 0; ndx < numElements; ++ndx)
1363         {
1364                 // By default, pick the biggest
1365                 outputFloats[ndx] = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1366
1367                 // Make half of the cases NaN cases
1368                 if ((ndx & 1) == 0)
1369                 {
1370                         // Alternate between the NaN operand
1371                         if ((ndx & 2) == 0)
1372                         {
1373                                 outputFloats[ndx] = inputFloats2[ndx];
1374                                 inputFloats1[ndx] = TCU_NAN;
1375                         }
1376                         else
1377                         {
1378                                 outputFloats[ndx] = inputFloats1[ndx];
1379                                 inputFloats2[ndx] = TCU_NAN;
1380                         }
1381                 }
1382         }
1383
1384         spec.assembly =
1385                 "OpCapability Shader\n"
1386                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1387                 "OpMemoryModel Logical GLSL450\n"
1388                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1389                 "OpExecutionMode %main LocalSize 1 1 1\n"
1390
1391                 "OpName %main           \"main\"\n"
1392                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1393
1394                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1395
1396                 "OpDecorate %buf BufferBlock\n"
1397                 "OpDecorate %indata1 DescriptorSet 0\n"
1398                 "OpDecorate %indata1 Binding 0\n"
1399                 "OpDecorate %indata2 DescriptorSet 0\n"
1400                 "OpDecorate %indata2 Binding 1\n"
1401                 "OpDecorate %outdata DescriptorSet 0\n"
1402                 "OpDecorate %outdata Binding 2\n"
1403                 "OpDecorate %f32arr ArrayStride 4\n"
1404                 "OpMemberDecorate %buf 0 Offset 0\n"
1405
1406                 + string(getComputeAsmCommonTypes()) +
1407
1408                 "%buf        = OpTypeStruct %f32arr\n"
1409                 "%bufptr     = OpTypePointer Uniform %buf\n"
1410                 "%indata1    = OpVariable %bufptr Uniform\n"
1411                 "%indata2    = OpVariable %bufptr Uniform\n"
1412                 "%outdata    = OpVariable %bufptr Uniform\n"
1413
1414                 "%id        = OpVariable %uvec3ptr Input\n"
1415                 "%zero      = OpConstant %i32 0\n"
1416
1417                 "%main      = OpFunction %void None %voidf\n"
1418                 "%label     = OpLabel\n"
1419                 "%idval     = OpLoad %uvec3 %id\n"
1420                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1421                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1422                 "%inval1    = OpLoad %f32 %inloc1\n"
1423                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1424                 "%inval2    = OpLoad %f32 %inloc2\n"
1425                 "%rem       = OpExtInst %f32 %std450 NMax %inval1 %inval2\n"
1426                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1427                 "             OpStore %outloc %rem\n"
1428                 "             OpReturn\n"
1429                 "             OpFunctionEnd\n";
1430
1431         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1432         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1433         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1434         spec.numWorkGroups = IVec3(numElements, 1, 1);
1435         spec.verifyIO = &compareNMax;
1436
1437         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1438
1439         return group.release();
1440 }
1441
1442 bool compareNClamp (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1443 {
1444         if (outputAllocs.size() != 1)
1445                 return false;
1446
1447         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1448         std::vector<deUint8>    data;
1449         expectedOutput->getBytes(data);
1450
1451         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1452         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1453
1454         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float) / 2; ++idx)
1455         {
1456                 const float e0 = expectedOutputAsFloat[idx * 2];
1457                 const float e1 = expectedOutputAsFloat[idx * 2 + 1];
1458                 const float res = outputAsFloat[idx];
1459
1460                 // For NClamp, we have two possible outcomes based on
1461                 // whether NaNs are handled or not.
1462                 // If either min or max value is NaN, the result is undefined,
1463                 // so this test doesn't stress those. If the clamped value is
1464                 // NaN, and NaNs are handled, the result is min; if NaNs are not
1465                 // handled, they are big values that result in max.
1466                 // If all three parameters are NaN, the result should be NaN.
1467                 if (!((tcu::Float32(e0).isNaN() && tcu::Float32(res).isNaN()) ||
1468                          (deFloatAbs(e0 - res) < 0.00001f) ||
1469                          (deFloatAbs(e1 - res) < 0.00001f)))
1470                         return false;
1471         }
1472
1473         return true;
1474 }
1475
1476 tcu::TestCaseGroup* createOpNClampGroup (tcu::TestContext& testCtx)
1477 {
1478         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnclamp", "Test the OpNClamp instruction"));
1479         ComputeShaderSpec                               spec;
1480         de::Random                                              rnd                             (deStringHash(group->getName()));
1481         const int                                               numElements             = 200;
1482         vector<float>                                   inputFloats1    (numElements, 0);
1483         vector<float>                                   inputFloats2    (numElements, 0);
1484         vector<float>                                   inputFloats3    (numElements, 0);
1485         vector<float>                                   outputFloats    (numElements * 2, 0);
1486
1487         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1488         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1489         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats3[0], numElements);
1490
1491         for (size_t ndx = 0; ndx < numElements; ++ndx)
1492         {
1493                 // Results are only defined if max value is bigger than min value.
1494                 if (inputFloats2[ndx] > inputFloats3[ndx])
1495                 {
1496                         float t = inputFloats2[ndx];
1497                         inputFloats2[ndx] = inputFloats3[ndx];
1498                         inputFloats3[ndx] = t;
1499                 }
1500
1501                 // By default, do the clamp, setting both possible answers
1502                 float defaultRes = std::min(std::max(inputFloats1[ndx], inputFloats2[ndx]), inputFloats3[ndx]);
1503
1504                 float maxResA = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1505                 float maxResB = maxResA;
1506
1507                 // Alternate between the NaN cases
1508                 if (ndx & 1)
1509                 {
1510                         inputFloats1[ndx] = TCU_NAN;
1511                         // If NaN is handled, the result should be same as the clamp minimum.
1512                         // If NaN is not handled, the result should clamp to the clamp maximum.
1513                         maxResA = inputFloats2[ndx];
1514                         maxResB = inputFloats3[ndx];
1515                 }
1516                 else
1517                 {
1518                         // Not a NaN case - only one legal result.
1519                         maxResA = defaultRes;
1520                         maxResB = defaultRes;
1521                 }
1522
1523                 outputFloats[ndx * 2] = maxResA;
1524                 outputFloats[ndx * 2 + 1] = maxResB;
1525         }
1526
1527         // Make the first case a full-NAN case.
1528         inputFloats1[0] = TCU_NAN;
1529         inputFloats2[0] = TCU_NAN;
1530         inputFloats3[0] = TCU_NAN;
1531         outputFloats[0] = TCU_NAN;
1532         outputFloats[1] = TCU_NAN;
1533
1534         spec.assembly =
1535                 "OpCapability Shader\n"
1536                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1537                 "OpMemoryModel Logical GLSL450\n"
1538                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1539                 "OpExecutionMode %main LocalSize 1 1 1\n"
1540
1541                 "OpName %main           \"main\"\n"
1542                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1543
1544                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1545
1546                 "OpDecorate %buf BufferBlock\n"
1547                 "OpDecorate %indata1 DescriptorSet 0\n"
1548                 "OpDecorate %indata1 Binding 0\n"
1549                 "OpDecorate %indata2 DescriptorSet 0\n"
1550                 "OpDecorate %indata2 Binding 1\n"
1551                 "OpDecorate %indata3 DescriptorSet 0\n"
1552                 "OpDecorate %indata3 Binding 2\n"
1553                 "OpDecorate %outdata DescriptorSet 0\n"
1554                 "OpDecorate %outdata Binding 3\n"
1555                 "OpDecorate %f32arr ArrayStride 4\n"
1556                 "OpMemberDecorate %buf 0 Offset 0\n"
1557
1558                 + string(getComputeAsmCommonTypes()) +
1559
1560                 "%buf        = OpTypeStruct %f32arr\n"
1561                 "%bufptr     = OpTypePointer Uniform %buf\n"
1562                 "%indata1    = OpVariable %bufptr Uniform\n"
1563                 "%indata2    = OpVariable %bufptr Uniform\n"
1564                 "%indata3    = OpVariable %bufptr Uniform\n"
1565                 "%outdata    = OpVariable %bufptr Uniform\n"
1566
1567                 "%id        = OpVariable %uvec3ptr Input\n"
1568                 "%zero      = OpConstant %i32 0\n"
1569
1570                 "%main      = OpFunction %void None %voidf\n"
1571                 "%label     = OpLabel\n"
1572                 "%idval     = OpLoad %uvec3 %id\n"
1573                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1574                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1575                 "%inval1    = OpLoad %f32 %inloc1\n"
1576                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1577                 "%inval2    = OpLoad %f32 %inloc2\n"
1578                 "%inloc3    = OpAccessChain %f32ptr %indata3 %zero %x\n"
1579                 "%inval3    = OpLoad %f32 %inloc3\n"
1580                 "%rem       = OpExtInst %f32 %std450 NClamp %inval1 %inval2 %inval3\n"
1581                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1582                 "             OpStore %outloc %rem\n"
1583                 "             OpReturn\n"
1584                 "             OpFunctionEnd\n";
1585
1586         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1587         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1588         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1589         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1590         spec.numWorkGroups = IVec3(numElements, 1, 1);
1591         spec.verifyIO = &compareNClamp;
1592
1593         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1594
1595         return group.release();
1596 }
1597
1598 tcu::TestCaseGroup* createOpSRemComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1599 {
1600         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem", "Test the OpSRem instruction"));
1601         de::Random                                              rnd                             (deStringHash(group->getName()));
1602         const int                                               numElements             = 200;
1603
1604         const struct CaseParams
1605         {
1606                 const char*             name;
1607                 const char*             failMessage;            // customized status message
1608                 qpTestResult    failResult;                     // override status on failure
1609                 int                             op1Min, op1Max;         // operand ranges
1610                 int                             op2Min, op2Max;
1611         } cases[] =
1612         {
1613                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1614                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1615         };
1616         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1617
1618         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1619         {
1620                 const CaseParams&       params          = cases[caseNdx];
1621                 ComputeShaderSpec       spec;
1622                 vector<deInt32>         inputInts1      (numElements, 0);
1623                 vector<deInt32>         inputInts2      (numElements, 0);
1624                 vector<deInt32>         outputInts      (numElements, 0);
1625
1626                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1627                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1628
1629                 for (int ndx = 0; ndx < numElements; ++ndx)
1630                 {
1631                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1632                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1633                 }
1634
1635                 spec.assembly =
1636                         string(getComputeAsmShaderPreamble()) +
1637
1638                         "OpName %main           \"main\"\n"
1639                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1640
1641                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1642
1643                         "OpDecorate %buf BufferBlock\n"
1644                         "OpDecorate %indata1 DescriptorSet 0\n"
1645                         "OpDecorate %indata1 Binding 0\n"
1646                         "OpDecorate %indata2 DescriptorSet 0\n"
1647                         "OpDecorate %indata2 Binding 1\n"
1648                         "OpDecorate %outdata DescriptorSet 0\n"
1649                         "OpDecorate %outdata Binding 2\n"
1650                         "OpDecorate %i32arr ArrayStride 4\n"
1651                         "OpMemberDecorate %buf 0 Offset 0\n"
1652
1653                         + string(getComputeAsmCommonTypes()) +
1654
1655                         "%buf        = OpTypeStruct %i32arr\n"
1656                         "%bufptr     = OpTypePointer Uniform %buf\n"
1657                         "%indata1    = OpVariable %bufptr Uniform\n"
1658                         "%indata2    = OpVariable %bufptr Uniform\n"
1659                         "%outdata    = OpVariable %bufptr Uniform\n"
1660
1661                         "%id        = OpVariable %uvec3ptr Input\n"
1662                         "%zero      = OpConstant %i32 0\n"
1663
1664                         "%main      = OpFunction %void None %voidf\n"
1665                         "%label     = OpLabel\n"
1666                         "%idval     = OpLoad %uvec3 %id\n"
1667                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1668                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1669                         "%inval1    = OpLoad %i32 %inloc1\n"
1670                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1671                         "%inval2    = OpLoad %i32 %inloc2\n"
1672                         "%rem       = OpSRem %i32 %inval1 %inval2\n"
1673                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1674                         "             OpStore %outloc %rem\n"
1675                         "             OpReturn\n"
1676                         "             OpFunctionEnd\n";
1677
1678                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1679                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1680                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1681                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1682                 spec.failResult                 = params.failResult;
1683                 spec.failMessage                = params.failMessage;
1684
1685                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1686         }
1687
1688         return group.release();
1689 }
1690
1691 tcu::TestCaseGroup* createOpSRemComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1692 {
1693         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem64", "Test the 64-bit OpSRem instruction"));
1694         de::Random                                              rnd                             (deStringHash(group->getName()));
1695         const int                                               numElements             = 200;
1696
1697         const struct CaseParams
1698         {
1699                 const char*             name;
1700                 const char*             failMessage;            // customized status message
1701                 qpTestResult    failResult;                     // override status on failure
1702                 bool                    positive;
1703         } cases[] =
1704         {
1705                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1706                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1707         };
1708         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1709
1710         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1711         {
1712                 const CaseParams&       params          = cases[caseNdx];
1713                 ComputeShaderSpec       spec;
1714                 vector<deInt64>         inputInts1      (numElements, 0);
1715                 vector<deInt64>         inputInts2      (numElements, 0);
1716                 vector<deInt64>         outputInts      (numElements, 0);
1717
1718                 if (params.positive)
1719                 {
1720                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1721                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1722                 }
1723                 else
1724                 {
1725                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1726                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1727                 }
1728
1729                 for (int ndx = 0; ndx < numElements; ++ndx)
1730                 {
1731                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1732                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1733                 }
1734
1735                 spec.assembly =
1736                         "OpCapability Int64\n"
1737
1738                         + string(getComputeAsmShaderPreamble()) +
1739
1740                         "OpName %main           \"main\"\n"
1741                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1742
1743                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1744
1745                         "OpDecorate %buf BufferBlock\n"
1746                         "OpDecorate %indata1 DescriptorSet 0\n"
1747                         "OpDecorate %indata1 Binding 0\n"
1748                         "OpDecorate %indata2 DescriptorSet 0\n"
1749                         "OpDecorate %indata2 Binding 1\n"
1750                         "OpDecorate %outdata DescriptorSet 0\n"
1751                         "OpDecorate %outdata Binding 2\n"
1752                         "OpDecorate %i64arr ArrayStride 8\n"
1753                         "OpMemberDecorate %buf 0 Offset 0\n"
1754
1755                         + string(getComputeAsmCommonTypes())
1756                         + string(getComputeAsmCommonInt64Types()) +
1757
1758                         "%buf        = OpTypeStruct %i64arr\n"
1759                         "%bufptr     = OpTypePointer Uniform %buf\n"
1760                         "%indata1    = OpVariable %bufptr Uniform\n"
1761                         "%indata2    = OpVariable %bufptr Uniform\n"
1762                         "%outdata    = OpVariable %bufptr Uniform\n"
1763
1764                         "%id        = OpVariable %uvec3ptr Input\n"
1765                         "%zero      = OpConstant %i64 0\n"
1766
1767                         "%main      = OpFunction %void None %voidf\n"
1768                         "%label     = OpLabel\n"
1769                         "%idval     = OpLoad %uvec3 %id\n"
1770                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1771                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1772                         "%inval1    = OpLoad %i64 %inloc1\n"
1773                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1774                         "%inval2    = OpLoad %i64 %inloc2\n"
1775                         "%rem       = OpSRem %i64 %inval1 %inval2\n"
1776                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1777                         "             OpStore %outloc %rem\n"
1778                         "             OpReturn\n"
1779                         "             OpFunctionEnd\n";
1780
1781                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1782                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1783                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1784                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1785                 spec.failResult                 = params.failResult;
1786                 spec.failMessage                = params.failMessage;
1787
1788                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
1789
1790                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1791         }
1792
1793         return group.release();
1794 }
1795
1796 tcu::TestCaseGroup* createOpSModComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1797 {
1798         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod", "Test the OpSMod instruction"));
1799         de::Random                                              rnd                             (deStringHash(group->getName()));
1800         const int                                               numElements             = 200;
1801
1802         const struct CaseParams
1803         {
1804                 const char*             name;
1805                 const char*             failMessage;            // customized status message
1806                 qpTestResult    failResult;                     // override status on failure
1807                 int                             op1Min, op1Max;         // operand ranges
1808                 int                             op2Min, op2Max;
1809         } cases[] =
1810         {
1811                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1812                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1813         };
1814         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1815
1816         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1817         {
1818                 const CaseParams&       params          = cases[caseNdx];
1819
1820                 ComputeShaderSpec       spec;
1821                 vector<deInt32>         inputInts1      (numElements, 0);
1822                 vector<deInt32>         inputInts2      (numElements, 0);
1823                 vector<deInt32>         outputInts      (numElements, 0);
1824
1825                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1826                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1827
1828                 for (int ndx = 0; ndx < numElements; ++ndx)
1829                 {
1830                         deInt32 rem = inputInts1[ndx] % inputInts2[ndx];
1831                         if (rem == 0)
1832                         {
1833                                 outputInts[ndx] = 0;
1834                         }
1835                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1836                         {
1837                                 // They have the same sign
1838                                 outputInts[ndx] = rem;
1839                         }
1840                         else
1841                         {
1842                                 // They have opposite sign.  The remainder operation takes the
1843                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1844                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1845                                 // the result has the correct sign and that it is still
1846                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1847                                 //
1848                                 // See also http://mathforum.org/library/drmath/view/52343.html
1849                                 outputInts[ndx] = rem + inputInts2[ndx];
1850                         }
1851                 }
1852
1853                 spec.assembly =
1854                         string(getComputeAsmShaderPreamble()) +
1855
1856                         "OpName %main           \"main\"\n"
1857                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1858
1859                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1860
1861                         "OpDecorate %buf BufferBlock\n"
1862                         "OpDecorate %indata1 DescriptorSet 0\n"
1863                         "OpDecorate %indata1 Binding 0\n"
1864                         "OpDecorate %indata2 DescriptorSet 0\n"
1865                         "OpDecorate %indata2 Binding 1\n"
1866                         "OpDecorate %outdata DescriptorSet 0\n"
1867                         "OpDecorate %outdata Binding 2\n"
1868                         "OpDecorate %i32arr ArrayStride 4\n"
1869                         "OpMemberDecorate %buf 0 Offset 0\n"
1870
1871                         + string(getComputeAsmCommonTypes()) +
1872
1873                         "%buf        = OpTypeStruct %i32arr\n"
1874                         "%bufptr     = OpTypePointer Uniform %buf\n"
1875                         "%indata1    = OpVariable %bufptr Uniform\n"
1876                         "%indata2    = OpVariable %bufptr Uniform\n"
1877                         "%outdata    = OpVariable %bufptr Uniform\n"
1878
1879                         "%id        = OpVariable %uvec3ptr Input\n"
1880                         "%zero      = OpConstant %i32 0\n"
1881
1882                         "%main      = OpFunction %void None %voidf\n"
1883                         "%label     = OpLabel\n"
1884                         "%idval     = OpLoad %uvec3 %id\n"
1885                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1886                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1887                         "%inval1    = OpLoad %i32 %inloc1\n"
1888                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1889                         "%inval2    = OpLoad %i32 %inloc2\n"
1890                         "%rem       = OpSMod %i32 %inval1 %inval2\n"
1891                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1892                         "             OpStore %outloc %rem\n"
1893                         "             OpReturn\n"
1894                         "             OpFunctionEnd\n";
1895
1896                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1897                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1898                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1899                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1900                 spec.failResult                 = params.failResult;
1901                 spec.failMessage                = params.failMessage;
1902
1903                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1904         }
1905
1906         return group.release();
1907 }
1908
1909 tcu::TestCaseGroup* createOpSModComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1910 {
1911         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod64", "Test the OpSMod instruction"));
1912         de::Random                                              rnd                             (deStringHash(group->getName()));
1913         const int                                               numElements             = 200;
1914
1915         const struct CaseParams
1916         {
1917                 const char*             name;
1918                 const char*             failMessage;            // customized status message
1919                 qpTestResult    failResult;                     // override status on failure
1920                 bool                    positive;
1921         } cases[] =
1922         {
1923                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1924                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1925         };
1926         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1927
1928         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1929         {
1930                 const CaseParams&       params          = cases[caseNdx];
1931
1932                 ComputeShaderSpec       spec;
1933                 vector<deInt64>         inputInts1      (numElements, 0);
1934                 vector<deInt64>         inputInts2      (numElements, 0);
1935                 vector<deInt64>         outputInts      (numElements, 0);
1936
1937
1938                 if (params.positive)
1939                 {
1940                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1941                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1942                 }
1943                 else
1944                 {
1945                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1946                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1947                 }
1948
1949                 for (int ndx = 0; ndx < numElements; ++ndx)
1950                 {
1951                         deInt64 rem = inputInts1[ndx] % inputInts2[ndx];
1952                         if (rem == 0)
1953                         {
1954                                 outputInts[ndx] = 0;
1955                         }
1956                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1957                         {
1958                                 // They have the same sign
1959                                 outputInts[ndx] = rem;
1960                         }
1961                         else
1962                         {
1963                                 // They have opposite sign.  The remainder operation takes the
1964                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1965                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1966                                 // the result has the correct sign and that it is still
1967                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1968                                 //
1969                                 // See also http://mathforum.org/library/drmath/view/52343.html
1970                                 outputInts[ndx] = rem + inputInts2[ndx];
1971                         }
1972                 }
1973
1974                 spec.assembly =
1975                         "OpCapability Int64\n"
1976
1977                         + string(getComputeAsmShaderPreamble()) +
1978
1979                         "OpName %main           \"main\"\n"
1980                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1981
1982                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1983
1984                         "OpDecorate %buf BufferBlock\n"
1985                         "OpDecorate %indata1 DescriptorSet 0\n"
1986                         "OpDecorate %indata1 Binding 0\n"
1987                         "OpDecorate %indata2 DescriptorSet 0\n"
1988                         "OpDecorate %indata2 Binding 1\n"
1989                         "OpDecorate %outdata DescriptorSet 0\n"
1990                         "OpDecorate %outdata Binding 2\n"
1991                         "OpDecorate %i64arr ArrayStride 8\n"
1992                         "OpMemberDecorate %buf 0 Offset 0\n"
1993
1994                         + string(getComputeAsmCommonTypes())
1995                         + string(getComputeAsmCommonInt64Types()) +
1996
1997                         "%buf        = OpTypeStruct %i64arr\n"
1998                         "%bufptr     = OpTypePointer Uniform %buf\n"
1999                         "%indata1    = OpVariable %bufptr Uniform\n"
2000                         "%indata2    = OpVariable %bufptr Uniform\n"
2001                         "%outdata    = OpVariable %bufptr Uniform\n"
2002
2003                         "%id        = OpVariable %uvec3ptr Input\n"
2004                         "%zero      = OpConstant %i64 0\n"
2005
2006                         "%main      = OpFunction %void None %voidf\n"
2007                         "%label     = OpLabel\n"
2008                         "%idval     = OpLoad %uvec3 %id\n"
2009                         "%x         = OpCompositeExtract %u32 %idval 0\n"
2010                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
2011                         "%inval1    = OpLoad %i64 %inloc1\n"
2012                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
2013                         "%inval2    = OpLoad %i64 %inloc2\n"
2014                         "%rem       = OpSMod %i64 %inval1 %inval2\n"
2015                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
2016                         "             OpStore %outloc %rem\n"
2017                         "             OpReturn\n"
2018                         "             OpFunctionEnd\n";
2019
2020                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
2021                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
2022                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
2023                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
2024                 spec.failResult                 = params.failResult;
2025                 spec.failMessage                = params.failMessage;
2026
2027                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
2028
2029                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2030         }
2031
2032         return group.release();
2033 }
2034
2035 // Copy contents in the input buffer to the output buffer.
2036 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
2037 {
2038         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
2039         de::Random                                              rnd                             (deStringHash(group->getName()));
2040         const int                                               numElements             = 100;
2041
2042         // 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.
2043         ComputeShaderSpec                               spec1;
2044         vector<Vec4>                                    inputFloats1    (numElements);
2045         vector<Vec4>                                    outputFloats1   (numElements);
2046
2047         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
2048
2049         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2050         floorAll(inputFloats1);
2051
2052         for (size_t ndx = 0; ndx < numElements; ++ndx)
2053                 outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
2054
2055         spec1.assembly =
2056                 string(getComputeAsmShaderPreamble()) +
2057
2058                 "OpName %main           \"main\"\n"
2059                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2060
2061                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2062                 "OpDecorate %vec4arr ArrayStride 16\n"
2063
2064                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2065
2066                 "%vec4       = OpTypeVector %f32 4\n"
2067                 "%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
2068                 "%vec4ptr_f  = OpTypePointer Function %vec4\n"
2069                 "%vec4arr    = OpTypeRuntimeArray %vec4\n"
2070                 "%buf        = OpTypeStruct %vec4arr\n"
2071                 "%bufptr     = OpTypePointer Uniform %buf\n"
2072                 "%indata     = OpVariable %bufptr Uniform\n"
2073                 "%outdata    = OpVariable %bufptr Uniform\n"
2074
2075                 "%id         = OpVariable %uvec3ptr Input\n"
2076                 "%zero       = OpConstant %i32 0\n"
2077                 "%c_f_0      = OpConstant %f32 0.\n"
2078                 "%c_f_0_5    = OpConstant %f32 0.5\n"
2079                 "%c_f_1_5    = OpConstant %f32 1.5\n"
2080                 "%c_f_2_5    = OpConstant %f32 2.5\n"
2081                 "%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
2082
2083                 "%main       = OpFunction %void None %voidf\n"
2084                 "%label      = OpLabel\n"
2085                 "%v_vec4     = OpVariable %vec4ptr_f Function\n"
2086                 "%idval      = OpLoad %uvec3 %id\n"
2087                 "%x          = OpCompositeExtract %u32 %idval 0\n"
2088                 "%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
2089                 "%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
2090                 "              OpCopyMemory %v_vec4 %inloc\n"
2091                 "%v_vec4_val = OpLoad %vec4 %v_vec4\n"
2092                 "%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
2093                 "              OpStore %outloc %add\n"
2094                 "              OpReturn\n"
2095                 "              OpFunctionEnd\n";
2096
2097         spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
2098         spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
2099         spec1.numWorkGroups = IVec3(numElements, 1, 1);
2100
2101         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
2102
2103         // The following case copies a float[100] variable from the input buffer to the output buffer.
2104         ComputeShaderSpec                               spec2;
2105         vector<float>                                   inputFloats2    (numElements);
2106         vector<float>                                   outputFloats2   (numElements);
2107
2108         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
2109
2110         for (size_t ndx = 0; ndx < numElements; ++ndx)
2111                 outputFloats2[ndx] = inputFloats2[ndx];
2112
2113         spec2.assembly =
2114                 string(getComputeAsmShaderPreamble()) +
2115
2116                 "OpName %main           \"main\"\n"
2117                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2118
2119                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2120                 "OpDecorate %f32arr100 ArrayStride 4\n"
2121
2122                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2123
2124                 "%hundred        = OpConstant %u32 100\n"
2125                 "%f32arr100      = OpTypeArray %f32 %hundred\n"
2126                 "%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
2127                 "%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
2128                 "%buf            = OpTypeStruct %f32arr100\n"
2129                 "%bufptr         = OpTypePointer Uniform %buf\n"
2130                 "%indata         = OpVariable %bufptr Uniform\n"
2131                 "%outdata        = OpVariable %bufptr Uniform\n"
2132
2133                 "%id             = OpVariable %uvec3ptr Input\n"
2134                 "%zero           = OpConstant %i32 0\n"
2135
2136                 "%main           = OpFunction %void None %voidf\n"
2137                 "%label          = OpLabel\n"
2138                 "%var            = OpVariable %f32arr100ptr_f Function\n"
2139                 "%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
2140                 "%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
2141                 "                  OpCopyMemory %var %inarr\n"
2142                 "                  OpCopyMemory %outarr %var\n"
2143                 "                  OpReturn\n"
2144                 "                  OpFunctionEnd\n";
2145
2146         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2147         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2148         spec2.numWorkGroups = IVec3(1, 1, 1);
2149
2150         group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
2151
2152         // The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
2153         ComputeShaderSpec                               spec3;
2154         vector<float>                                   inputFloats3    (16);
2155         vector<float>                                   outputFloats3   (16);
2156
2157         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
2158
2159         for (size_t ndx = 0; ndx < 16; ++ndx)
2160                 outputFloats3[ndx] = inputFloats3[ndx];
2161
2162         spec3.assembly =
2163                 string(getComputeAsmShaderPreamble()) +
2164
2165                 "OpName %main           \"main\"\n"
2166                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2167
2168                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2169                 //"OpMemberDecorate %buf 0 Offset 0\n"  - exists in getComputeAsmInputOutputBufferTraits
2170                 "OpMemberDecorate %buf 1 Offset 16\n"
2171                 "OpMemberDecorate %buf 2 Offset 32\n"
2172                 "OpMemberDecorate %buf 3 Offset 48\n"
2173
2174                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2175
2176                 "%vec4      = OpTypeVector %f32 4\n"
2177                 "%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
2178                 "%bufptr    = OpTypePointer Uniform %buf\n"
2179                 "%indata    = OpVariable %bufptr Uniform\n"
2180                 "%outdata   = OpVariable %bufptr Uniform\n"
2181                 "%vec4stptr = OpTypePointer Function %buf\n"
2182
2183                 "%id        = OpVariable %uvec3ptr Input\n"
2184                 "%zero      = OpConstant %i32 0\n"
2185
2186                 "%main      = OpFunction %void None %voidf\n"
2187                 "%label     = OpLabel\n"
2188                 "%var       = OpVariable %vec4stptr Function\n"
2189                 "             OpCopyMemory %var %indata\n"
2190                 "             OpCopyMemory %outdata %var\n"
2191                 "             OpReturn\n"
2192                 "             OpFunctionEnd\n";
2193
2194         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2195         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
2196         spec3.numWorkGroups = IVec3(1, 1, 1);
2197
2198         group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
2199
2200         // The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
2201         ComputeShaderSpec                               spec4;
2202         vector<float>                                   inputFloats4    (numElements);
2203         vector<float>                                   outputFloats4   (numElements);
2204
2205         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
2206
2207         for (size_t ndx = 0; ndx < numElements; ++ndx)
2208                 outputFloats4[ndx] = -inputFloats4[ndx];
2209
2210         spec4.assembly =
2211                 string(getComputeAsmShaderPreamble()) +
2212
2213                 "OpName %main           \"main\"\n"
2214                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2215
2216                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2217
2218                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2219
2220                 "%f32ptr_f  = OpTypePointer Function %f32\n"
2221                 "%id        = OpVariable %uvec3ptr Input\n"
2222                 "%zero      = OpConstant %i32 0\n"
2223
2224                 "%main      = OpFunction %void None %voidf\n"
2225                 "%label     = OpLabel\n"
2226                 "%var       = OpVariable %f32ptr_f Function\n"
2227                 "%idval     = OpLoad %uvec3 %id\n"
2228                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2229                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2230                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2231                 "             OpCopyMemory %var %inloc\n"
2232                 "%val       = OpLoad %f32 %var\n"
2233                 "%neg       = OpFNegate %f32 %val\n"
2234                 "             OpStore %outloc %neg\n"
2235                 "             OpReturn\n"
2236                 "             OpFunctionEnd\n";
2237
2238         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2239         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
2240         spec4.numWorkGroups = IVec3(numElements, 1, 1);
2241
2242         group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
2243
2244         return group.release();
2245 }
2246
2247 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
2248 {
2249         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
2250         ComputeShaderSpec                               spec;
2251         de::Random                                              rnd                             (deStringHash(group->getName()));
2252         const int                                               numElements             = 100;
2253         vector<float>                                   inputFloats             (numElements, 0);
2254         vector<float>                                   outputFloats    (numElements, 0);
2255
2256         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2257
2258         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2259         floorAll(inputFloats);
2260
2261         for (size_t ndx = 0; ndx < numElements; ++ndx)
2262                 outputFloats[ndx] = inputFloats[ndx] + 7.5f;
2263
2264         spec.assembly =
2265                 string(getComputeAsmShaderPreamble()) +
2266
2267                 "OpName %main           \"main\"\n"
2268                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2269
2270                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2271
2272                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2273
2274                 "%fmat     = OpTypeMatrix %fvec3 3\n"
2275                 "%three    = OpConstant %u32 3\n"
2276                 "%farr     = OpTypeArray %f32 %three\n"
2277                 "%fst      = OpTypeStruct %f32 %f32\n"
2278
2279                 + string(getComputeAsmInputOutputBuffer()) +
2280
2281                 "%id            = OpVariable %uvec3ptr Input\n"
2282                 "%zero          = OpConstant %i32 0\n"
2283                 "%c_f           = OpConstant %f32 1.5\n"
2284                 "%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
2285                 "%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
2286                 "%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
2287                 "%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
2288
2289                 "%main          = OpFunction %void None %voidf\n"
2290                 "%label         = OpLabel\n"
2291                 "%c_f_copy      = OpCopyObject %f32   %c_f\n"
2292                 "%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
2293                 "%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
2294                 "%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
2295                 "%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
2296                 "%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
2297                 "%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
2298                 "%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
2299                 "%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
2300                 // Add up. 1.5 * 5 = 7.5.
2301                 "%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
2302                 "%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
2303                 "%add3          = OpFAdd %f32 %add2     %farr_elem\n"
2304                 "%add4          = OpFAdd %f32 %add3     %fst_elem\n"
2305
2306                 "%idval         = OpLoad %uvec3 %id\n"
2307                 "%x             = OpCompositeExtract %u32 %idval 0\n"
2308                 "%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
2309                 "%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
2310                 "%inval         = OpLoad %f32 %inloc\n"
2311                 "%add           = OpFAdd %f32 %add4 %inval\n"
2312                 "                 OpStore %outloc %add\n"
2313                 "                 OpReturn\n"
2314                 "                 OpFunctionEnd\n";
2315         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2316         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2317         spec.numWorkGroups = IVec3(numElements, 1, 1);
2318
2319         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
2320
2321         return group.release();
2322 }
2323 // Assembly code used for testing OpUnreachable is based on GLSL source code:
2324 //
2325 // #version 430
2326 //
2327 // layout(std140, set = 0, binding = 0) readonly buffer Input {
2328 //   float elements[];
2329 // } input_data;
2330 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
2331 //   float elements[];
2332 // } output_data;
2333 //
2334 // void not_called_func() {
2335 //   // place OpUnreachable here
2336 // }
2337 //
2338 // uint modulo4(uint val) {
2339 //   switch (val % uint(4)) {
2340 //     case 0:  return 3;
2341 //     case 1:  return 2;
2342 //     case 2:  return 1;
2343 //     case 3:  return 0;
2344 //     default: return 100; // place OpUnreachable here
2345 //   }
2346 // }
2347 //
2348 // uint const5() {
2349 //   return 5;
2350 //   // place OpUnreachable here
2351 // }
2352 //
2353 // void main() {
2354 //   uint x = gl_GlobalInvocationID.x;
2355 //   if (const5() > modulo4(1000)) {
2356 //     output_data.elements[x] = -input_data.elements[x];
2357 //   } else {
2358 //     // place OpUnreachable here
2359 //     output_data.elements[x] = input_data.elements[x];
2360 //   }
2361 // }
2362
2363 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
2364 {
2365         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
2366         ComputeShaderSpec                               spec;
2367         de::Random                                              rnd                             (deStringHash(group->getName()));
2368         const int                                               numElements             = 100;
2369         vector<float>                                   positiveFloats  (numElements, 0);
2370         vector<float>                                   negativeFloats  (numElements, 0);
2371
2372         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2373
2374         for (size_t ndx = 0; ndx < numElements; ++ndx)
2375                 negativeFloats[ndx] = -positiveFloats[ndx];
2376
2377         spec.assembly =
2378                 string(getComputeAsmShaderPreamble()) +
2379
2380                 "OpSource GLSL 430\n"
2381                 "OpName %main            \"main\"\n"
2382                 "OpName %func_not_called_func \"not_called_func(\"\n"
2383                 "OpName %func_modulo4         \"modulo4(u1;\"\n"
2384                 "OpName %func_const5          \"const5(\"\n"
2385                 "OpName %id                   \"gl_GlobalInvocationID\"\n"
2386
2387                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2388
2389                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2390
2391                 "%u32ptr    = OpTypePointer Function %u32\n"
2392                 "%uintfuint = OpTypeFunction %u32 %u32ptr\n"
2393                 "%unitf     = OpTypeFunction %u32\n"
2394
2395                 "%id        = OpVariable %uvec3ptr Input\n"
2396                 "%zero      = OpConstant %u32 0\n"
2397                 "%one       = OpConstant %u32 1\n"
2398                 "%two       = OpConstant %u32 2\n"
2399                 "%three     = OpConstant %u32 3\n"
2400                 "%four      = OpConstant %u32 4\n"
2401                 "%five      = OpConstant %u32 5\n"
2402                 "%hundred   = OpConstant %u32 100\n"
2403                 "%thousand  = OpConstant %u32 1000\n"
2404
2405                 + string(getComputeAsmInputOutputBuffer()) +
2406
2407                 // Main()
2408                 "%main   = OpFunction %void None %voidf\n"
2409                 "%main_entry  = OpLabel\n"
2410                 "%v_thousand  = OpVariable %u32ptr Function %thousand\n"
2411                 "%idval       = OpLoad %uvec3 %id\n"
2412                 "%x           = OpCompositeExtract %u32 %idval 0\n"
2413                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
2414                 "%inval       = OpLoad %f32 %inloc\n"
2415                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
2416                 "%ret_const5  = OpFunctionCall %u32 %func_const5\n"
2417                 "%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
2418                 "%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
2419                 "               OpSelectionMerge %if_end None\n"
2420                 "               OpBranchConditional %cmp_gt %if_true %if_false\n"
2421                 "%if_true     = OpLabel\n"
2422                 "%negate      = OpFNegate %f32 %inval\n"
2423                 "               OpStore %outloc %negate\n"
2424                 "               OpBranch %if_end\n"
2425                 "%if_false    = OpLabel\n"
2426                 "               OpUnreachable\n" // Unreachable else branch for if statement
2427                 "%if_end      = OpLabel\n"
2428                 "               OpReturn\n"
2429                 "               OpFunctionEnd\n"
2430
2431                 // not_called_function()
2432                 "%func_not_called_func  = OpFunction %void None %voidf\n"
2433                 "%not_called_func_entry = OpLabel\n"
2434                 "                         OpUnreachable\n" // Unreachable entry block in not called static function
2435                 "                         OpFunctionEnd\n"
2436
2437                 // modulo4()
2438                 "%func_modulo4  = OpFunction %u32 None %uintfuint\n"
2439                 "%valptr        = OpFunctionParameter %u32ptr\n"
2440                 "%modulo4_entry = OpLabel\n"
2441                 "%val           = OpLoad %u32 %valptr\n"
2442                 "%modulo        = OpUMod %u32 %val %four\n"
2443                 "                 OpSelectionMerge %switch_merge None\n"
2444                 "                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
2445                 "%case0         = OpLabel\n"
2446                 "                 OpReturnValue %three\n"
2447                 "%case1         = OpLabel\n"
2448                 "                 OpReturnValue %two\n"
2449                 "%case2         = OpLabel\n"
2450                 "                 OpReturnValue %one\n"
2451                 "%case3         = OpLabel\n"
2452                 "                 OpReturnValue %zero\n"
2453                 "%default       = OpLabel\n"
2454                 "                 OpUnreachable\n" // Unreachable default case for switch statement
2455                 "%switch_merge  = OpLabel\n"
2456                 "                 OpUnreachable\n" // Unreachable merge block for switch statement
2457                 "                 OpFunctionEnd\n"
2458
2459                 // const5()
2460                 "%func_const5  = OpFunction %u32 None %unitf\n"
2461                 "%const5_entry = OpLabel\n"
2462                 "                OpReturnValue %five\n"
2463                 "%unreachable  = OpLabel\n"
2464                 "                OpUnreachable\n" // Unreachable block in function
2465                 "                OpFunctionEnd\n";
2466         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2467         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2468         spec.numWorkGroups = IVec3(numElements, 1, 1);
2469
2470         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
2471
2472         return group.release();
2473 }
2474
2475 // Assembly code used for testing decoration group is based on GLSL source code:
2476 //
2477 // #version 430
2478 //
2479 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
2480 //   float elements[];
2481 // } input_data0;
2482 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
2483 //   float elements[];
2484 // } input_data1;
2485 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
2486 //   float elements[];
2487 // } input_data2;
2488 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
2489 //   float elements[];
2490 // } input_data3;
2491 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
2492 //   float elements[];
2493 // } input_data4;
2494 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
2495 //   float elements[];
2496 // } output_data;
2497 //
2498 // void main() {
2499 //   uint x = gl_GlobalInvocationID.x;
2500 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
2501 // }
2502 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
2503 {
2504         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
2505         ComputeShaderSpec                               spec;
2506         de::Random                                              rnd                             (deStringHash(group->getName()));
2507         const int                                               numElements             = 100;
2508         vector<float>                                   inputFloats0    (numElements, 0);
2509         vector<float>                                   inputFloats1    (numElements, 0);
2510         vector<float>                                   inputFloats2    (numElements, 0);
2511         vector<float>                                   inputFloats3    (numElements, 0);
2512         vector<float>                                   inputFloats4    (numElements, 0);
2513         vector<float>                                   outputFloats    (numElements, 0);
2514
2515         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
2516         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
2517         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
2518         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
2519         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
2520
2521         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2522         floorAll(inputFloats0);
2523         floorAll(inputFloats1);
2524         floorAll(inputFloats2);
2525         floorAll(inputFloats3);
2526         floorAll(inputFloats4);
2527
2528         for (size_t ndx = 0; ndx < numElements; ++ndx)
2529                 outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
2530
2531         spec.assembly =
2532                 string(getComputeAsmShaderPreamble()) +
2533
2534                 "OpSource GLSL 430\n"
2535                 "OpName %main \"main\"\n"
2536                 "OpName %id \"gl_GlobalInvocationID\"\n"
2537
2538                 // Not using group decoration on variable.
2539                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2540                 // Not using group decoration on type.
2541                 "OpDecorate %f32arr ArrayStride 4\n"
2542
2543                 "OpDecorate %groups BufferBlock\n"
2544                 "OpDecorate %groupm Offset 0\n"
2545                 "%groups = OpDecorationGroup\n"
2546                 "%groupm = OpDecorationGroup\n"
2547
2548                 // Group decoration on multiple structs.
2549                 "OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
2550                 // Group decoration on multiple struct members.
2551                 "OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
2552
2553                 "OpDecorate %group1 DescriptorSet 0\n"
2554                 "OpDecorate %group3 DescriptorSet 0\n"
2555                 "OpDecorate %group3 NonWritable\n"
2556                 "OpDecorate %group3 Restrict\n"
2557                 "%group0 = OpDecorationGroup\n"
2558                 "%group1 = OpDecorationGroup\n"
2559                 "%group3 = OpDecorationGroup\n"
2560
2561                 // Applying the same decoration group multiple times.
2562                 "OpGroupDecorate %group1 %outdata\n"
2563                 "OpGroupDecorate %group1 %outdata\n"
2564                 "OpGroupDecorate %group1 %outdata\n"
2565                 "OpDecorate %outdata DescriptorSet 0\n"
2566                 "OpDecorate %outdata Binding 5\n"
2567                 // Applying decoration group containing nothing.
2568                 "OpGroupDecorate %group0 %indata0\n"
2569                 "OpDecorate %indata0 DescriptorSet 0\n"
2570                 "OpDecorate %indata0 Binding 0\n"
2571                 // Applying decoration group containing one decoration.
2572                 "OpGroupDecorate %group1 %indata1\n"
2573                 "OpDecorate %indata1 Binding 1\n"
2574                 // Applying decoration group containing multiple decorations.
2575                 "OpGroupDecorate %group3 %indata2 %indata3\n"
2576                 "OpDecorate %indata2 Binding 2\n"
2577                 "OpDecorate %indata3 Binding 3\n"
2578                 // Applying multiple decoration groups (with overlapping).
2579                 "OpGroupDecorate %group0 %indata4\n"
2580                 "OpGroupDecorate %group1 %indata4\n"
2581                 "OpGroupDecorate %group3 %indata4\n"
2582                 "OpDecorate %indata4 Binding 4\n"
2583
2584                 + string(getComputeAsmCommonTypes()) +
2585
2586                 "%id   = OpVariable %uvec3ptr Input\n"
2587                 "%zero = OpConstant %i32 0\n"
2588
2589                 "%outbuf    = OpTypeStruct %f32arr\n"
2590                 "%outbufptr = OpTypePointer Uniform %outbuf\n"
2591                 "%outdata   = OpVariable %outbufptr Uniform\n"
2592                 "%inbuf0    = OpTypeStruct %f32arr\n"
2593                 "%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
2594                 "%indata0   = OpVariable %inbuf0ptr Uniform\n"
2595                 "%inbuf1    = OpTypeStruct %f32arr\n"
2596                 "%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
2597                 "%indata1   = OpVariable %inbuf1ptr Uniform\n"
2598                 "%inbuf2    = OpTypeStruct %f32arr\n"
2599                 "%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
2600                 "%indata2   = OpVariable %inbuf2ptr Uniform\n"
2601                 "%inbuf3    = OpTypeStruct %f32arr\n"
2602                 "%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
2603                 "%indata3   = OpVariable %inbuf3ptr Uniform\n"
2604                 "%inbuf4    = OpTypeStruct %f32arr\n"
2605                 "%inbufptr  = OpTypePointer Uniform %inbuf4\n"
2606                 "%indata4   = OpVariable %inbufptr Uniform\n"
2607
2608                 "%main   = OpFunction %void None %voidf\n"
2609                 "%label  = OpLabel\n"
2610                 "%idval  = OpLoad %uvec3 %id\n"
2611                 "%x      = OpCompositeExtract %u32 %idval 0\n"
2612                 "%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
2613                 "%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
2614                 "%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
2615                 "%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
2616                 "%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
2617                 "%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
2618                 "%inval0 = OpLoad %f32 %inloc0\n"
2619                 "%inval1 = OpLoad %f32 %inloc1\n"
2620                 "%inval2 = OpLoad %f32 %inloc2\n"
2621                 "%inval3 = OpLoad %f32 %inloc3\n"
2622                 "%inval4 = OpLoad %f32 %inloc4\n"
2623                 "%add0   = OpFAdd %f32 %inval0 %inval1\n"
2624                 "%add1   = OpFAdd %f32 %add0 %inval2\n"
2625                 "%add2   = OpFAdd %f32 %add1 %inval3\n"
2626                 "%add    = OpFAdd %f32 %add2 %inval4\n"
2627                 "          OpStore %outloc %add\n"
2628                 "          OpReturn\n"
2629                 "          OpFunctionEnd\n";
2630         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
2631         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
2632         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2633         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2634         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2635         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2636         spec.numWorkGroups = IVec3(numElements, 1, 1);
2637
2638         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
2639
2640         return group.release();
2641 }
2642
2643 struct SpecConstantTwoIntCase
2644 {
2645         const char*             caseName;
2646         const char*             scDefinition0;
2647         const char*             scDefinition1;
2648         const char*             scResultType;
2649         const char*             scOperation;
2650         deInt32                 scActualValue0;
2651         deInt32                 scActualValue1;
2652         const char*             resultOperation;
2653         vector<deInt32> expectedOutput;
2654         deInt32                 scActualValueLength;
2655
2656                                         SpecConstantTwoIntCase (const char* name,
2657                                                                                         const char* definition0,
2658                                                                                         const char* definition1,
2659                                                                                         const char* resultType,
2660                                                                                         const char* operation,
2661                                                                                         deInt32 value0,
2662                                                                                         deInt32 value1,
2663                                                                                         const char* resultOp,
2664                                                                                         const vector<deInt32>& output,
2665                                                                                         const deInt32   valueLength = sizeof(deInt32))
2666                                                 : caseName                              (name)
2667                                                 , scDefinition0                 (definition0)
2668                                                 , scDefinition1                 (definition1)
2669                                                 , scResultType                  (resultType)
2670                                                 , scOperation                   (operation)
2671                                                 , scActualValue0                (value0)
2672                                                 , scActualValue1                (value1)
2673                                                 , resultOperation               (resultOp)
2674                                                 , expectedOutput                (output)
2675                                                 , scActualValueLength   (valueLength)
2676                                                 {}
2677 };
2678
2679 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
2680 {
2681         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
2682         vector<SpecConstantTwoIntCase>  cases;
2683         de::Random                                              rnd                             (deStringHash(group->getName()));
2684         const int                                               numElements             = 100;
2685         const deInt32                                   p1AsFloat16             = 0x3c00; // +1(fp16) == 0 01111 0000000000 == 0011 1100 0000 0000
2686         vector<deInt32>                                 inputInts               (numElements, 0);
2687         vector<deInt32>                                 outputInts1             (numElements, 0);
2688         vector<deInt32>                                 outputInts2             (numElements, 0);
2689         vector<deInt32>                                 outputInts3             (numElements, 0);
2690         vector<deInt32>                                 outputInts4             (numElements, 0);
2691         const StringTemplate                    shaderTemplate  (
2692                 "${CAPABILITIES:opt}"
2693                 + string(getComputeAsmShaderPreamble()) +
2694
2695                 "OpName %main           \"main\"\n"
2696                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2697
2698                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2699                 "OpDecorate %sc_0  SpecId 0\n"
2700                 "OpDecorate %sc_1  SpecId 1\n"
2701                 "OpDecorate %i32arr ArrayStride 4\n"
2702
2703                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2704
2705                 "${OPTYPE_DEFINITIONS:opt}"
2706                 "%buf     = OpTypeStruct %i32arr\n"
2707                 "%bufptr  = OpTypePointer Uniform %buf\n"
2708                 "%indata    = OpVariable %bufptr Uniform\n"
2709                 "%outdata   = OpVariable %bufptr Uniform\n"
2710
2711                 "%id        = OpVariable %uvec3ptr Input\n"
2712                 "%zero      = OpConstant %i32 0\n"
2713
2714                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
2715                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
2716                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2717
2718                 "%main      = OpFunction %void None %voidf\n"
2719                 "%label     = OpLabel\n"
2720                 "${TYPE_CONVERT:opt}"
2721                 "%idval     = OpLoad %uvec3 %id\n"
2722                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2723                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2724                 "%inval     = OpLoad %i32 %inloc\n"
2725                 "%final     = ${GEN_RESULT}\n"
2726                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2727                 "             OpStore %outloc %final\n"
2728                 "             OpReturn\n"
2729                 "             OpFunctionEnd\n");
2730
2731         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2732
2733         for (size_t ndx = 0; ndx < numElements; ++ndx)
2734         {
2735                 outputInts1[ndx] = inputInts[ndx] + 42;
2736                 outputInts2[ndx] = inputInts[ndx];
2737                 outputInts3[ndx] = inputInts[ndx] - 11200;
2738                 outputInts4[ndx] = inputInts[ndx] + 1;
2739         }
2740
2741         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
2742         const char addSc32ToInput[]             = "OpIAdd %i32 %inval %sc_final32";
2743         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
2744         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
2745
2746         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
2747         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
2748         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
2749         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
2750         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
2751         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2752         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2753         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
2754         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
2755         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
2756         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
2757         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2758         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2759         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
2760         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
2761         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
2762         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2763         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
2764         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
2765         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
2766         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2767         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
2768         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
2769         cases.push_back(SpecConstantTwoIntCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                     42,             24,             selectTrueUsingSc,      outputInts2));
2770         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2771         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2772         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2773         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2774         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
2775         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
2776         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
2777         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
2778         cases.push_back(SpecConstantTwoIntCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                           -11200, 0,              addSc32ToInput,         outputInts3));
2779         // -969998336 stored as 32-bit two's complement is the binary representation of -11200 as IEEE-754 Float
2780         cases.push_back(SpecConstantTwoIntCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                           -969998336, 0,  addSc32ToInput,         outputInts3));
2781         cases.push_back(SpecConstantTwoIntCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                           p1AsFloat16, 0, addSc32ToInput,         outputInts4, sizeof(deFloat16)));
2782
2783         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2784         {
2785                 map<string, string>             specializations;
2786                 ComputeShaderSpec               spec;
2787
2788                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
2789                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
2790                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
2791                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
2792                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
2793
2794                 // Special SPIR-V code for SConvert-case
2795                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
2796                 {
2797                         spec.requestedVulkanFeatures.coreFeatures.shaderInt16   = VK_TRUE;
2798                         specializations["CAPABILITIES"]                                                 = "OpCapability Int16\n";                                                       // Adds 16-bit integer capability
2799                         specializations["OPTYPE_DEFINITIONS"]                                   = "%i16 = OpTypeInt 16 1\n";                                            // Adds 16-bit integer type
2800                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpSConvert %i32 %sc_final\n";          // Converts 16-bit integer to 32-bit integer
2801                 }
2802
2803                 // Special SPIR-V code for FConvert-case
2804                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
2805                 {
2806                         spec.requestedVulkanFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
2807                         specializations["CAPABILITIES"]                                                 = "OpCapability Float64\n";                                                     // Adds 64-bit float capability
2808                         specializations["OPTYPE_DEFINITIONS"]                                   = "%f64 = OpTypeFloat 64\n";                                            // Adds 64-bit float type
2809                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 64-bit float to 32-bit integer
2810                 }
2811
2812                 // Special SPIR-V code for FConvert-case for 16-bit floats
2813                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
2814                 {
2815                         spec.extensions.push_back("VK_KHR_shader_float16_int8");
2816                         spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
2817                         specializations["CAPABILITIES"]                 = "OpCapability Float16\n";                                                     // Adds 16-bit float capability
2818                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                                            // Adds 16-bit float type
2819                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 16-bit float to 32-bit integer
2820                 }
2821
2822                 spec.assembly = shaderTemplate.specialize(specializations);
2823                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2824                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2825                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2826                 spec.specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
2827                 spec.specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
2828
2829                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec));
2830         }
2831
2832         ComputeShaderSpec                               spec;
2833
2834         spec.assembly =
2835                 string(getComputeAsmShaderPreamble()) +
2836
2837                 "OpName %main           \"main\"\n"
2838                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2839
2840                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2841                 "OpDecorate %sc_0  SpecId 0\n"
2842                 "OpDecorate %sc_1  SpecId 1\n"
2843                 "OpDecorate %sc_2  SpecId 2\n"
2844                 "OpDecorate %i32arr ArrayStride 4\n"
2845
2846                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2847
2848                 "%ivec3       = OpTypeVector %i32 3\n"
2849                 "%buf         = OpTypeStruct %i32arr\n"
2850                 "%bufptr      = OpTypePointer Uniform %buf\n"
2851                 "%indata      = OpVariable %bufptr Uniform\n"
2852                 "%outdata     = OpVariable %bufptr Uniform\n"
2853
2854                 "%id          = OpVariable %uvec3ptr Input\n"
2855                 "%zero        = OpConstant %i32 0\n"
2856                 "%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
2857                 "%vec3_undef  = OpUndef %ivec3\n"
2858
2859                 "%sc_0        = OpSpecConstant %i32 0\n"
2860                 "%sc_1        = OpSpecConstant %i32 0\n"
2861                 "%sc_2        = OpSpecConstant %i32 0\n"
2862                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"                                                 // (sc_0, 0, 0)
2863                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"                                                 // (0, sc_1, 0)
2864                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"                                                 // (0, 0, sc_2)
2865                 "%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
2866                 "%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
2867                 "%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
2868                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
2869                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
2870                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
2871                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
2872                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
2873                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
2874                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"                                                              // (sc_2 - sc_0) * sc_1
2875
2876                 "%main      = OpFunction %void None %voidf\n"
2877                 "%label     = OpLabel\n"
2878                 "%idval     = OpLoad %uvec3 %id\n"
2879                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2880                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2881                 "%inval     = OpLoad %i32 %inloc\n"
2882                 "%final     = OpIAdd %i32 %inval %sc_final\n"
2883                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2884                 "             OpStore %outloc %final\n"
2885                 "             OpReturn\n"
2886                 "             OpFunctionEnd\n";
2887         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2888         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
2889         spec.numWorkGroups = IVec3(numElements, 1, 1);
2890         spec.specConstants.append<deInt32>(123);
2891         spec.specConstants.append<deInt32>(56);
2892         spec.specConstants.append<deInt32>(-77);
2893
2894         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
2895
2896         return group.release();
2897 }
2898
2899 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
2900 {
2901         ComputeShaderSpec       specInt;
2902         ComputeShaderSpec       specFloat;
2903         ComputeShaderSpec       specFloat16;
2904         ComputeShaderSpec       specVec3;
2905         ComputeShaderSpec       specMat4;
2906         ComputeShaderSpec       specArray;
2907         ComputeShaderSpec       specStruct;
2908         de::Random                      rnd                             (deStringHash(group->getName()));
2909         const int                       numElements             = 100;
2910         vector<float>           inputFloats             (numElements, 0);
2911         vector<float>           outputFloats    (numElements, 0);
2912         vector<deFloat16>       inputFloats16   (numElements, 0);
2913         vector<deFloat16>       outputFloats16  (numElements, 0);
2914
2915         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
2916
2917         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2918         floorAll(inputFloats);
2919
2920         for (size_t ndx = 0; ndx < numElements; ++ndx)
2921         {
2922                 // Just check if the value is positive or not
2923                 outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
2924         }
2925
2926         for (size_t ndx = 0; ndx < numElements; ++ndx)
2927         {
2928                 inputFloats16[ndx] = tcu::Float16(inputFloats[ndx]).bits();
2929                 outputFloats16[ndx] = tcu::Float16(outputFloats[ndx]).bits();
2930         }
2931
2932         // All of the tests are of the form:
2933         //
2934         // testtype r
2935         //
2936         // if (inputdata > 0)
2937         //   r = 1
2938         // else
2939         //   r = -1
2940         //
2941         // return (float)r
2942
2943         specFloat.assembly =
2944                 string(getComputeAsmShaderPreamble()) +
2945
2946                 "OpSource GLSL 430\n"
2947                 "OpName %main \"main\"\n"
2948                 "OpName %id \"gl_GlobalInvocationID\"\n"
2949
2950                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2951
2952                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2953
2954                 "%id = OpVariable %uvec3ptr Input\n"
2955                 "%zero       = OpConstant %i32 0\n"
2956                 "%float_0    = OpConstant %f32 0.0\n"
2957                 "%float_1    = OpConstant %f32 1.0\n"
2958                 "%float_n1   = OpConstant %f32 -1.0\n"
2959
2960                 "%main     = OpFunction %void None %voidf\n"
2961                 "%entry    = OpLabel\n"
2962                 "%idval    = OpLoad %uvec3 %id\n"
2963                 "%x        = OpCompositeExtract %u32 %idval 0\n"
2964                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
2965                 "%inval    = OpLoad %f32 %inloc\n"
2966
2967                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
2968                 "            OpSelectionMerge %cm None\n"
2969                 "            OpBranchConditional %comp %tb %fb\n"
2970                 "%tb       = OpLabel\n"
2971                 "            OpBranch %cm\n"
2972                 "%fb       = OpLabel\n"
2973                 "            OpBranch %cm\n"
2974                 "%cm       = OpLabel\n"
2975                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
2976
2977                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
2978                 "            OpStore %outloc %res\n"
2979                 "            OpReturn\n"
2980
2981                 "            OpFunctionEnd\n";
2982         specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2983         specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2984         specFloat.numWorkGroups = IVec3(numElements, 1, 1);
2985
2986         specFloat16.assembly =
2987                 "OpCapability Shader\n"
2988                 "OpCapability StorageUniformBufferBlock16\n"
2989                 "OpExtension \"SPV_KHR_16bit_storage\"\n"
2990                 "OpMemoryModel Logical GLSL450\n"
2991                 "OpEntryPoint GLCompute %main \"main\" %id\n"
2992                 "OpExecutionMode %main LocalSize 1 1 1\n"
2993
2994                 "OpSource GLSL 430\n"
2995                 "OpName %main \"main\"\n"
2996                 "OpName %id \"gl_GlobalInvocationID\"\n"
2997
2998                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2999
3000                 "OpDecorate %buf BufferBlock\n"
3001                 "OpDecorate %indata DescriptorSet 0\n"
3002                 "OpDecorate %indata Binding 0\n"
3003                 "OpDecorate %outdata DescriptorSet 0\n"
3004                 "OpDecorate %outdata Binding 1\n"
3005                 "OpDecorate %f16arr ArrayStride 2\n"
3006                 "OpMemberDecorate %buf 0 Offset 0\n"
3007
3008                 "%f16      = OpTypeFloat 16\n"
3009                 "%f16ptr   = OpTypePointer Uniform %f16\n"
3010                 "%f16arr   = OpTypeRuntimeArray %f16\n"
3011
3012                 + string(getComputeAsmCommonTypes()) +
3013
3014                 "%buf      = OpTypeStruct %f16arr\n"
3015                 "%bufptr   = OpTypePointer Uniform %buf\n"
3016                 "%indata   = OpVariable %bufptr Uniform\n"
3017                 "%outdata  = OpVariable %bufptr Uniform\n"
3018
3019                 "%id       = OpVariable %uvec3ptr Input\n"
3020                 "%zero     = OpConstant %i32 0\n"
3021                 "%float_0  = OpConstant %f16 0.0\n"
3022                 "%float_1  = OpConstant %f16 1.0\n"
3023                 "%float_n1 = OpConstant %f16 -1.0\n"
3024
3025                 "%main     = OpFunction %void None %voidf\n"
3026                 "%entry    = OpLabel\n"
3027                 "%idval    = OpLoad %uvec3 %id\n"
3028                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3029                 "%inloc    = OpAccessChain %f16ptr %indata %zero %x\n"
3030                 "%inval    = OpLoad %f16 %inloc\n"
3031
3032                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3033                 "            OpSelectionMerge %cm None\n"
3034                 "            OpBranchConditional %comp %tb %fb\n"
3035                 "%tb       = OpLabel\n"
3036                 "            OpBranch %cm\n"
3037                 "%fb       = OpLabel\n"
3038                 "            OpBranch %cm\n"
3039                 "%cm       = OpLabel\n"
3040                 "%res      = OpPhi %f16 %float_1 %tb %float_n1 %fb\n"
3041
3042                 "%outloc   = OpAccessChain %f16ptr %outdata %zero %x\n"
3043                 "            OpStore %outloc %res\n"
3044                 "            OpReturn\n"
3045
3046                 "            OpFunctionEnd\n";
3047         specFloat16.inputs.push_back(BufferSp(new Float16Buffer(inputFloats16)));
3048         specFloat16.outputs.push_back(BufferSp(new Float16Buffer(outputFloats16)));
3049         specFloat16.numWorkGroups = IVec3(numElements, 1, 1);
3050         specFloat16.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
3051         specFloat16.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
3052
3053         specMat4.assembly =
3054                 string(getComputeAsmShaderPreamble()) +
3055
3056                 "OpSource GLSL 430\n"
3057                 "OpName %main \"main\"\n"
3058                 "OpName %id \"gl_GlobalInvocationID\"\n"
3059
3060                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3061
3062                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3063
3064                 "%id = OpVariable %uvec3ptr Input\n"
3065                 "%v4f32      = OpTypeVector %f32 4\n"
3066                 "%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
3067                 "%zero       = OpConstant %i32 0\n"
3068                 "%float_0    = OpConstant %f32 0.0\n"
3069                 "%float_1    = OpConstant %f32 1.0\n"
3070                 "%float_n1   = OpConstant %f32 -1.0\n"
3071                 "%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
3072                 "%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
3073                 "%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
3074                 "%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
3075                 "%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
3076                 "%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
3077                 "%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
3078                 "%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
3079                 "%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
3080                 "%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
3081
3082                 "%main     = OpFunction %void None %voidf\n"
3083                 "%entry    = OpLabel\n"
3084                 "%idval    = OpLoad %uvec3 %id\n"
3085                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3086                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3087                 "%inval    = OpLoad %f32 %inloc\n"
3088
3089                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3090                 "            OpSelectionMerge %cm None\n"
3091                 "            OpBranchConditional %comp %tb %fb\n"
3092                 "%tb       = OpLabel\n"
3093                 "            OpBranch %cm\n"
3094                 "%fb       = OpLabel\n"
3095                 "            OpBranch %cm\n"
3096                 "%cm       = OpLabel\n"
3097                 "%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
3098                 "%res      = OpCompositeExtract %f32 %mres 2 2\n"
3099
3100                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3101                 "            OpStore %outloc %res\n"
3102                 "            OpReturn\n"
3103
3104                 "            OpFunctionEnd\n";
3105         specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3106         specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3107         specMat4.numWorkGroups = IVec3(numElements, 1, 1);
3108
3109         specVec3.assembly =
3110                 string(getComputeAsmShaderPreamble()) +
3111
3112                 "OpSource GLSL 430\n"
3113                 "OpName %main \"main\"\n"
3114                 "OpName %id \"gl_GlobalInvocationID\"\n"
3115
3116                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3117
3118                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3119
3120                 "%id = OpVariable %uvec3ptr Input\n"
3121                 "%zero       = OpConstant %i32 0\n"
3122                 "%float_0    = OpConstant %f32 0.0\n"
3123                 "%float_1    = OpConstant %f32 1.0\n"
3124                 "%float_n1   = OpConstant %f32 -1.0\n"
3125                 "%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
3126                 "%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
3127
3128                 "%main     = OpFunction %void None %voidf\n"
3129                 "%entry    = OpLabel\n"
3130                 "%idval    = OpLoad %uvec3 %id\n"
3131                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3132                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3133                 "%inval    = OpLoad %f32 %inloc\n"
3134
3135                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3136                 "            OpSelectionMerge %cm None\n"
3137                 "            OpBranchConditional %comp %tb %fb\n"
3138                 "%tb       = OpLabel\n"
3139                 "            OpBranch %cm\n"
3140                 "%fb       = OpLabel\n"
3141                 "            OpBranch %cm\n"
3142                 "%cm       = OpLabel\n"
3143                 "%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
3144                 "%res      = OpCompositeExtract %f32 %vres 2\n"
3145
3146                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3147                 "            OpStore %outloc %res\n"
3148                 "            OpReturn\n"
3149
3150                 "            OpFunctionEnd\n";
3151         specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3152         specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3153         specVec3.numWorkGroups = IVec3(numElements, 1, 1);
3154
3155         specInt.assembly =
3156                 string(getComputeAsmShaderPreamble()) +
3157
3158                 "OpSource GLSL 430\n"
3159                 "OpName %main \"main\"\n"
3160                 "OpName %id \"gl_GlobalInvocationID\"\n"
3161
3162                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3163
3164                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3165
3166                 "%id = OpVariable %uvec3ptr Input\n"
3167                 "%zero       = OpConstant %i32 0\n"
3168                 "%float_0    = OpConstant %f32 0.0\n"
3169                 "%i1         = OpConstant %i32 1\n"
3170                 "%i2         = OpConstant %i32 -1\n"
3171
3172                 "%main     = OpFunction %void None %voidf\n"
3173                 "%entry    = OpLabel\n"
3174                 "%idval    = OpLoad %uvec3 %id\n"
3175                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3176                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3177                 "%inval    = OpLoad %f32 %inloc\n"
3178
3179                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3180                 "            OpSelectionMerge %cm None\n"
3181                 "            OpBranchConditional %comp %tb %fb\n"
3182                 "%tb       = OpLabel\n"
3183                 "            OpBranch %cm\n"
3184                 "%fb       = OpLabel\n"
3185                 "            OpBranch %cm\n"
3186                 "%cm       = OpLabel\n"
3187                 "%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
3188                 "%res      = OpConvertSToF %f32 %ires\n"
3189
3190                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3191                 "            OpStore %outloc %res\n"
3192                 "            OpReturn\n"
3193
3194                 "            OpFunctionEnd\n";
3195         specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3196         specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3197         specInt.numWorkGroups = IVec3(numElements, 1, 1);
3198
3199         specArray.assembly =
3200                 string(getComputeAsmShaderPreamble()) +
3201
3202                 "OpSource GLSL 430\n"
3203                 "OpName %main \"main\"\n"
3204                 "OpName %id \"gl_GlobalInvocationID\"\n"
3205
3206                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3207
3208                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3209
3210                 "%id = OpVariable %uvec3ptr Input\n"
3211                 "%zero       = OpConstant %i32 0\n"
3212                 "%u7         = OpConstant %u32 7\n"
3213                 "%float_0    = OpConstant %f32 0.0\n"
3214                 "%float_1    = OpConstant %f32 1.0\n"
3215                 "%float_n1   = OpConstant %f32 -1.0\n"
3216                 "%f32a7      = OpTypeArray %f32 %u7\n"
3217                 "%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
3218                 "%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
3219                 "%main     = OpFunction %void None %voidf\n"
3220                 "%entry    = OpLabel\n"
3221                 "%idval    = OpLoad %uvec3 %id\n"
3222                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3223                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3224                 "%inval    = OpLoad %f32 %inloc\n"
3225
3226                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3227                 "            OpSelectionMerge %cm None\n"
3228                 "            OpBranchConditional %comp %tb %fb\n"
3229                 "%tb       = OpLabel\n"
3230                 "            OpBranch %cm\n"
3231                 "%fb       = OpLabel\n"
3232                 "            OpBranch %cm\n"
3233                 "%cm       = OpLabel\n"
3234                 "%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
3235                 "%res      = OpCompositeExtract %f32 %ares 5\n"
3236
3237                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3238                 "            OpStore %outloc %res\n"
3239                 "            OpReturn\n"
3240
3241                 "            OpFunctionEnd\n";
3242         specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3243         specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3244         specArray.numWorkGroups = IVec3(numElements, 1, 1);
3245
3246         specStruct.assembly =
3247                 string(getComputeAsmShaderPreamble()) +
3248
3249                 "OpSource GLSL 430\n"
3250                 "OpName %main \"main\"\n"
3251                 "OpName %id \"gl_GlobalInvocationID\"\n"
3252
3253                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3254
3255                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3256
3257                 "%id = OpVariable %uvec3ptr Input\n"
3258                 "%zero       = OpConstant %i32 0\n"
3259                 "%float_0    = OpConstant %f32 0.0\n"
3260                 "%float_1    = OpConstant %f32 1.0\n"
3261                 "%float_n1   = OpConstant %f32 -1.0\n"
3262
3263                 "%v2f32      = OpTypeVector %f32 2\n"
3264                 "%Data2      = OpTypeStruct %f32 %v2f32\n"
3265                 "%Data       = OpTypeStruct %Data2 %f32\n"
3266
3267                 "%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
3268                 "%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
3269                 "%s1         = OpConstantComposite %Data %in1b %float_1\n"
3270                 "%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
3271                 "%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
3272                 "%s2         = OpConstantComposite %Data %in2b %float_n1\n"
3273
3274                 "%main     = OpFunction %void None %voidf\n"
3275                 "%entry    = OpLabel\n"
3276                 "%idval    = OpLoad %uvec3 %id\n"
3277                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3278                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3279                 "%inval    = OpLoad %f32 %inloc\n"
3280
3281                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3282                 "            OpSelectionMerge %cm None\n"
3283                 "            OpBranchConditional %comp %tb %fb\n"
3284                 "%tb       = OpLabel\n"
3285                 "            OpBranch %cm\n"
3286                 "%fb       = OpLabel\n"
3287                 "            OpBranch %cm\n"
3288                 "%cm       = OpLabel\n"
3289                 "%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
3290                 "%res      = OpCompositeExtract %f32 %sres 0 0\n"
3291
3292                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3293                 "            OpStore %outloc %res\n"
3294                 "            OpReturn\n"
3295
3296                 "            OpFunctionEnd\n";
3297         specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3298         specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3299         specStruct.numWorkGroups = IVec3(numElements, 1, 1);
3300
3301         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
3302         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
3303         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float16", "OpPhi with 16bit float variables", specFloat16));
3304         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
3305         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
3306         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
3307         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
3308 }
3309
3310 string generateConstantDefinitions (int count)
3311 {
3312         std::ostringstream      r;
3313         for (int i = 0; i < count; i++)
3314                 r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
3315         r << "\n";
3316         return r.str();
3317 }
3318
3319 string generateSwitchCases (int count)
3320 {
3321         std::ostringstream      r;
3322         for (int i = 0; i < count; i++)
3323                 r << " " << i << " %case" << i;
3324         r << "\n";
3325         return r.str();
3326 }
3327
3328 string generateSwitchTargets (int count)
3329 {
3330         std::ostringstream      r;
3331         for (int i = 0; i < count; i++)
3332                 r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3333         r << "\n";
3334         return r.str();
3335 }
3336
3337 string generateOpPhiParams (int count)
3338 {
3339         std::ostringstream      r;
3340         for (int i = 0; i < count; i++)
3341                 r << " %cf" << (i * 10 + 5) << " %case" << i;
3342         r << "\n";
3343         return r.str();
3344 }
3345
3346 string generateIntWidth (int value)
3347 {
3348         std::ostringstream      r;
3349         r << value;
3350         return r.str();
3351 }
3352
3353 // Expand input string by injecting "ABC" between the input
3354 // string characters. The acc/add/treshold parameters are used
3355 // to skip some of the injections to make the result less
3356 // uniform (and a lot shorter).
3357 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3358 {
3359         std::ostringstream      res;
3360         const char*                     p = s.c_str();
3361
3362         while (*p)
3363         {
3364                 res << *p;
3365                 acc += add;
3366                 if (acc > treshold)
3367                 {
3368                         acc -= treshold;
3369                         res << "ABC";
3370                 }
3371                 p++;
3372         }
3373         return res.str();
3374 }
3375
3376 // Calculate expected result based on the code string
3377 float calcOpPhiCase5 (float val, const string& s)
3378 {
3379         const char*             p               = s.c_str();
3380         float                   x[8];
3381         bool                    b[8];
3382         const float             tv[8]   = { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3383         const float             v               = deFloatAbs(val);
3384         float                   res             = 0;
3385         int                             depth   = -1;
3386         int                             skip    = 0;
3387
3388         for (int i = 7; i >= 0; --i)
3389                 x[i] = std::fmod((float)v, (float)(2 << i));
3390         for (int i = 7; i >= 0; --i)
3391                 b[i] = x[i] > tv[i];
3392
3393         while (*p)
3394         {
3395                 if (*p == 'A')
3396                 {
3397                         depth++;
3398                         if (skip == 0 && b[depth])
3399                         {
3400                                 res++;
3401                         }
3402                         else
3403                                 skip++;
3404                 }
3405                 if (*p == 'B')
3406                 {
3407                         if (skip)
3408                                 skip--;
3409                         if (b[depth] || skip)
3410                                 skip++;
3411                 }
3412                 if (*p == 'C')
3413                 {
3414                         depth--;
3415                         if (skip)
3416                                 skip--;
3417                 }
3418                 p++;
3419         }
3420         return res;
3421 }
3422
3423 // In the code string, the letters represent the following:
3424 //
3425 // A:
3426 //     if (certain bit is set)
3427 //     {
3428 //       result++;
3429 //
3430 // B:
3431 //     } else {
3432 //
3433 // C:
3434 //     }
3435 //
3436 // examples:
3437 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3438 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3439 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3440 //
3441 // Code generation gets a bit complicated due to the else-branches,
3442 // which do not generate new values. Thus, the generator needs to
3443 // keep track of the previous variable change seen by the else
3444 // branch.
3445 string generateOpPhiCase5 (const string& s)
3446 {
3447         std::stack<int>                         idStack;
3448         std::stack<std::string>         value;
3449         std::stack<std::string>         valueLabel;
3450         std::stack<std::string>         mergeLeft;
3451         std::stack<std::string>         mergeRight;
3452         std::ostringstream                      res;
3453         const char*                                     p                       = s.c_str();
3454         int                                                     depth           = -1;
3455         int                                                     currId          = 0;
3456         int                                                     iter            = 0;
3457
3458         idStack.push(-1);
3459         value.push("%f32_0");
3460         valueLabel.push("%f32_0 %entry");
3461
3462         while (*p)
3463         {
3464                 if (*p == 'A')
3465                 {
3466                         depth++;
3467                         currId = iter;
3468                         idStack.push(currId);
3469                         res << "\tOpSelectionMerge %m" << currId << " None\n";
3470                         res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3471                         res << "%t" << currId << " = OpLabel\n";
3472                         res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3473                         std::ostringstream tag;
3474                         tag << "%rt" << currId;
3475                         value.push(tag.str());
3476                         tag << " %t" << currId;
3477                         valueLabel.push(tag.str());
3478                 }
3479
3480                 if (*p == 'B')
3481                 {
3482                         mergeLeft.push(valueLabel.top());
3483                         value.pop();
3484                         valueLabel.pop();
3485                         res << "\tOpBranch %m" << currId << "\n";
3486                         res << "%f" << currId << " = OpLabel\n";
3487                         std::ostringstream tag;
3488                         tag << value.top() << " %f" << currId;
3489                         valueLabel.pop();
3490                         valueLabel.push(tag.str());
3491                 }
3492
3493                 if (*p == 'C')
3494                 {
3495                         mergeRight.push(valueLabel.top());
3496                         res << "\tOpBranch %m" << currId << "\n";
3497                         res << "%m" << currId << " = OpLabel\n";
3498                         if (*(p + 1) == 0)
3499                                 res << "%res"; // last result goes to %res
3500                         else
3501                                 res << "%rm" << currId;
3502                         res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3503                         std::ostringstream tag;
3504                         tag << "%rm" << currId;
3505                         value.pop();
3506                         value.push(tag.str());
3507                         tag << " %m" << currId;
3508                         valueLabel.pop();
3509                         valueLabel.push(tag.str());
3510                         mergeLeft.pop();
3511                         mergeRight.pop();
3512                         depth--;
3513                         idStack.pop();
3514                         currId = idStack.top();
3515                 }
3516                 p++;
3517                 iter++;
3518         }
3519         return res.str();
3520 }
3521
3522 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3523 {
3524         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3525         ComputeShaderSpec                               spec1;
3526         ComputeShaderSpec                               spec2;
3527         ComputeShaderSpec                               spec3;
3528         ComputeShaderSpec                               spec4;
3529         ComputeShaderSpec                               spec5;
3530         de::Random                                              rnd                             (deStringHash(group->getName()));
3531         const int                                               numElements             = 100;
3532         vector<float>                                   inputFloats             (numElements, 0);
3533         vector<float>                                   outputFloats1   (numElements, 0);
3534         vector<float>                                   outputFloats2   (numElements, 0);
3535         vector<float>                                   outputFloats3   (numElements, 0);
3536         vector<float>                                   outputFloats4   (numElements, 0);
3537         vector<float>                                   outputFloats5   (numElements, 0);
3538         std::string                                             codestring              = "ABC";
3539         const int                                               test4Width              = 1024;
3540
3541         // Build case 5 code string. Each iteration makes the hierarchy more complicated.
3542         // 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3543         // shader code.
3544         for (int i = 0, acc = 0; i < 9; i++)
3545                 codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3546
3547         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3548
3549         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3550         floorAll(inputFloats);
3551
3552         for (size_t ndx = 0; ndx < numElements; ++ndx)
3553         {
3554                 switch (ndx % 3)
3555                 {
3556                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
3557                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
3558                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
3559                         default:        break;
3560                 }
3561                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3562                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3563
3564                 int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3565                 outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3566
3567                 outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3568         }
3569
3570         spec1.assembly =
3571                 string(getComputeAsmShaderPreamble()) +
3572
3573                 "OpSource GLSL 430\n"
3574                 "OpName %main \"main\"\n"
3575                 "OpName %id \"gl_GlobalInvocationID\"\n"
3576
3577                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3578
3579                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3580
3581                 "%id = OpVariable %uvec3ptr Input\n"
3582                 "%zero       = OpConstant %i32 0\n"
3583                 "%three      = OpConstant %u32 3\n"
3584                 "%constf5p5  = OpConstant %f32 5.5\n"
3585                 "%constf20p5 = OpConstant %f32 20.5\n"
3586                 "%constf1p75 = OpConstant %f32 1.75\n"
3587                 "%constf8p5  = OpConstant %f32 8.5\n"
3588                 "%constf6p5  = OpConstant %f32 6.5\n"
3589
3590                 "%main     = OpFunction %void None %voidf\n"
3591                 "%entry    = OpLabel\n"
3592                 "%idval    = OpLoad %uvec3 %id\n"
3593                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3594                 "%selector = OpUMod %u32 %x %three\n"
3595                 "            OpSelectionMerge %phi None\n"
3596                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3597
3598                 // Case 1 before OpPhi.
3599                 "%case1    = OpLabel\n"
3600                 "            OpBranch %phi\n"
3601
3602                 "%default  = OpLabel\n"
3603                 "            OpUnreachable\n"
3604
3605                 "%phi      = OpLabel\n"
3606                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3607                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3608                 "%inval    = OpLoad %f32 %inloc\n"
3609                 "%add      = OpFAdd %f32 %inval %operand\n"
3610                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3611                 "            OpStore %outloc %add\n"
3612                 "            OpReturn\n"
3613
3614                 // Case 0 after OpPhi.
3615                 "%case0    = OpLabel\n"
3616                 "            OpBranch %phi\n"
3617
3618
3619                 // Case 2 after OpPhi.
3620                 "%case2    = OpLabel\n"
3621                 "            OpBranch %phi\n"
3622
3623                 "            OpFunctionEnd\n";
3624         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3625         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3626         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3627
3628         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3629
3630         spec2.assembly =
3631                 string(getComputeAsmShaderPreamble()) +
3632
3633                 "OpName %main \"main\"\n"
3634                 "OpName %id \"gl_GlobalInvocationID\"\n"
3635
3636                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3637
3638                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3639
3640                 "%id         = OpVariable %uvec3ptr Input\n"
3641                 "%zero       = OpConstant %i32 0\n"
3642                 "%one        = OpConstant %i32 1\n"
3643                 "%three      = OpConstant %i32 3\n"
3644                 "%constf6p5  = OpConstant %f32 6.5\n"
3645
3646                 "%main       = OpFunction %void None %voidf\n"
3647                 "%entry      = OpLabel\n"
3648                 "%idval      = OpLoad %uvec3 %id\n"
3649                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3650                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3651                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3652                 "%inval      = OpLoad %f32 %inloc\n"
3653                 "              OpBranch %phi\n"
3654
3655                 "%phi        = OpLabel\n"
3656                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3657                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3658                 "%step_next  = OpIAdd %i32 %step %one\n"
3659                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3660                 "%still_loop = OpSLessThan %bool %step %three\n"
3661                 "              OpLoopMerge %exit %phi None\n"
3662                 "              OpBranchConditional %still_loop %phi %exit\n"
3663
3664                 "%exit       = OpLabel\n"
3665                 "              OpStore %outloc %accum\n"
3666                 "              OpReturn\n"
3667                 "              OpFunctionEnd\n";
3668         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3669         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3670         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3671
3672         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3673
3674         spec3.assembly =
3675                 string(getComputeAsmShaderPreamble()) +
3676
3677                 "OpName %main \"main\"\n"
3678                 "OpName %id \"gl_GlobalInvocationID\"\n"
3679
3680                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3681
3682                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3683
3684                 "%f32ptr_f   = OpTypePointer Function %f32\n"
3685                 "%id         = OpVariable %uvec3ptr Input\n"
3686                 "%true       = OpConstantTrue %bool\n"
3687                 "%false      = OpConstantFalse %bool\n"
3688                 "%zero       = OpConstant %i32 0\n"
3689                 "%constf8p5  = OpConstant %f32 8.5\n"
3690
3691                 "%main       = OpFunction %void None %voidf\n"
3692                 "%entry      = OpLabel\n"
3693                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3694                 "%idval      = OpLoad %uvec3 %id\n"
3695                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3696                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3697                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3698                 "%a_init     = OpLoad %f32 %inloc\n"
3699                 "%b_init     = OpLoad %f32 %b\n"
3700                 "              OpBranch %phi\n"
3701
3702                 "%phi        = OpLabel\n"
3703                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3704                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3705                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3706                 "              OpLoopMerge %exit %phi None\n"
3707                 "              OpBranchConditional %still_loop %phi %exit\n"
3708
3709                 "%exit       = OpLabel\n"
3710                 "%sub        = OpFSub %f32 %a_next %b_next\n"
3711                 "              OpStore %outloc %sub\n"
3712                 "              OpReturn\n"
3713                 "              OpFunctionEnd\n";
3714         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3715         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3716         spec3.numWorkGroups = IVec3(numElements, 1, 1);
3717
3718         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3719
3720         spec4.assembly =
3721                 "OpCapability Shader\n"
3722                 "%ext = OpExtInstImport \"GLSL.std.450\"\n"
3723                 "OpMemoryModel Logical GLSL450\n"
3724                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3725                 "OpExecutionMode %main LocalSize 1 1 1\n"
3726
3727                 "OpSource GLSL 430\n"
3728                 "OpName %main \"main\"\n"
3729                 "OpName %id \"gl_GlobalInvocationID\"\n"
3730
3731                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3732
3733                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3734
3735                 "%id       = OpVariable %uvec3ptr Input\n"
3736                 "%zero     = OpConstant %i32 0\n"
3737                 "%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3738
3739                 + generateConstantDefinitions(test4Width) +
3740
3741                 "%main     = OpFunction %void None %voidf\n"
3742                 "%entry    = OpLabel\n"
3743                 "%idval    = OpLoad %uvec3 %id\n"
3744                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3745                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3746                 "%inval    = OpLoad %f32 %inloc\n"
3747                 "%xf       = OpConvertUToF %f32 %x\n"
3748                 "%xm       = OpFMul %f32 %xf %inval\n"
3749                 "%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3750                 "%xi       = OpConvertFToU %u32 %xa\n"
3751                 "%selector = OpUMod %u32 %xi %cimod\n"
3752                 "            OpSelectionMerge %phi None\n"
3753                 "            OpSwitch %selector %default "
3754
3755                 + generateSwitchCases(test4Width) +
3756
3757                 "%default  = OpLabel\n"
3758                 "            OpUnreachable\n"
3759
3760                 + generateSwitchTargets(test4Width) +
3761
3762                 "%phi      = OpLabel\n"
3763                 "%result   = OpPhi %f32"
3764
3765                 + generateOpPhiParams(test4Width) +
3766
3767                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3768                 "            OpStore %outloc %result\n"
3769                 "            OpReturn\n"
3770
3771                 "            OpFunctionEnd\n";
3772         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3773         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3774         spec4.numWorkGroups = IVec3(numElements, 1, 1);
3775
3776         group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3777
3778         spec5.assembly =
3779                 "OpCapability Shader\n"
3780                 "%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3781                 "OpMemoryModel Logical GLSL450\n"
3782                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3783                 "OpExecutionMode %main LocalSize 1 1 1\n"
3784                 "%code     = OpString \"" + codestring + "\"\n"
3785
3786                 "OpSource GLSL 430\n"
3787                 "OpName %main \"main\"\n"
3788                 "OpName %id \"gl_GlobalInvocationID\"\n"
3789
3790                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3791
3792                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3793
3794                 "%id       = OpVariable %uvec3ptr Input\n"
3795                 "%zero     = OpConstant %i32 0\n"
3796                 "%f32_0    = OpConstant %f32 0.0\n"
3797                 "%f32_0_5  = OpConstant %f32 0.5\n"
3798                 "%f32_1    = OpConstant %f32 1.0\n"
3799                 "%f32_1_5  = OpConstant %f32 1.5\n"
3800                 "%f32_2    = OpConstant %f32 2.0\n"
3801                 "%f32_3_5  = OpConstant %f32 3.5\n"
3802                 "%f32_4    = OpConstant %f32 4.0\n"
3803                 "%f32_7_5  = OpConstant %f32 7.5\n"
3804                 "%f32_8    = OpConstant %f32 8.0\n"
3805                 "%f32_15_5 = OpConstant %f32 15.5\n"
3806                 "%f32_16   = OpConstant %f32 16.0\n"
3807                 "%f32_31_5 = OpConstant %f32 31.5\n"
3808                 "%f32_32   = OpConstant %f32 32.0\n"
3809                 "%f32_63_5 = OpConstant %f32 63.5\n"
3810                 "%f32_64   = OpConstant %f32 64.0\n"
3811                 "%f32_127_5 = OpConstant %f32 127.5\n"
3812                 "%f32_128  = OpConstant %f32 128.0\n"
3813                 "%f32_256  = OpConstant %f32 256.0\n"
3814
3815                 "%main     = OpFunction %void None %voidf\n"
3816                 "%entry    = OpLabel\n"
3817                 "%idval    = OpLoad %uvec3 %id\n"
3818                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3819                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3820                 "%inval    = OpLoad %f32 %inloc\n"
3821
3822                 "%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3823                 "%x8       = OpFMod %f32 %xabs %f32_256\n"
3824                 "%x7       = OpFMod %f32 %xabs %f32_128\n"
3825                 "%x6       = OpFMod %f32 %xabs %f32_64\n"
3826                 "%x5       = OpFMod %f32 %xabs %f32_32\n"
3827                 "%x4       = OpFMod %f32 %xabs %f32_16\n"
3828                 "%x3       = OpFMod %f32 %xabs %f32_8\n"
3829                 "%x2       = OpFMod %f32 %xabs %f32_4\n"
3830                 "%x1       = OpFMod %f32 %xabs %f32_2\n"
3831
3832                 "%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3833                 "%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3834                 "%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3835                 "%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3836                 "%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3837                 "%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3838                 "%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3839                 "%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3840
3841                 + generateOpPhiCase5(codestring) +
3842
3843                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3844                 "            OpStore %outloc %res\n"
3845                 "            OpReturn\n"
3846
3847                 "            OpFunctionEnd\n";
3848         spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3849         spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
3850         spec5.numWorkGroups = IVec3(numElements, 1, 1);
3851
3852         group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
3853
3854         createOpPhiVartypeTests(group, testCtx);
3855
3856         return group.release();
3857 }
3858
3859 // Assembly code used for testing block order is based on GLSL source code:
3860 //
3861 // #version 430
3862 //
3863 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3864 //   float elements[];
3865 // } input_data;
3866 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3867 //   float elements[];
3868 // } output_data;
3869 //
3870 // void main() {
3871 //   uint x = gl_GlobalInvocationID.x;
3872 //   output_data.elements[x] = input_data.elements[x];
3873 //   if (x > uint(50)) {
3874 //     switch (x % uint(3)) {
3875 //       case 0: output_data.elements[x] += 1.5f; break;
3876 //       case 1: output_data.elements[x] += 42.f; break;
3877 //       case 2: output_data.elements[x] -= 27.f; break;
3878 //       default: break;
3879 //     }
3880 //   } else {
3881 //     output_data.elements[x] = -input_data.elements[x];
3882 //   }
3883 // }
3884 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
3885 {
3886         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
3887         ComputeShaderSpec                               spec;
3888         de::Random                                              rnd                             (deStringHash(group->getName()));
3889         const int                                               numElements             = 100;
3890         vector<float>                                   inputFloats             (numElements, 0);
3891         vector<float>                                   outputFloats    (numElements, 0);
3892
3893         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
3894
3895         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3896         floorAll(inputFloats);
3897
3898         for (size_t ndx = 0; ndx <= 50; ++ndx)
3899                 outputFloats[ndx] = -inputFloats[ndx];
3900
3901         for (size_t ndx = 51; ndx < numElements; ++ndx)
3902         {
3903                 switch (ndx % 3)
3904                 {
3905                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
3906                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
3907                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
3908                         default:        break;
3909                 }
3910         }
3911
3912         spec.assembly =
3913                 string(getComputeAsmShaderPreamble()) +
3914
3915                 "OpSource GLSL 430\n"
3916                 "OpName %main \"main\"\n"
3917                 "OpName %id \"gl_GlobalInvocationID\"\n"
3918
3919                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3920
3921                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
3922
3923                 "%u32ptr       = OpTypePointer Function %u32\n"
3924                 "%u32ptr_input = OpTypePointer Input %u32\n"
3925
3926                 + string(getComputeAsmInputOutputBuffer()) +
3927
3928                 "%id        = OpVariable %uvec3ptr Input\n"
3929                 "%zero      = OpConstant %i32 0\n"
3930                 "%const3    = OpConstant %u32 3\n"
3931                 "%const50   = OpConstant %u32 50\n"
3932                 "%constf1p5 = OpConstant %f32 1.5\n"
3933                 "%constf27  = OpConstant %f32 27.0\n"
3934                 "%constf42  = OpConstant %f32 42.0\n"
3935
3936                 "%main = OpFunction %void None %voidf\n"
3937
3938                 // entry block.
3939                 "%entry    = OpLabel\n"
3940
3941                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
3942                 "%xvar     = OpVariable %u32ptr Function\n"
3943                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
3944                 "%x        = OpLoad %u32 %xptr\n"
3945                 "            OpStore %xvar %x\n"
3946
3947                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
3948                 "            OpSelectionMerge %if_merge None\n"
3949                 "            OpBranchConditional %cmp %if_true %if_false\n"
3950
3951                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
3952                 "%if_false = OpLabel\n"
3953                 "%x_f      = OpLoad %u32 %xvar\n"
3954                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
3955                 "%inval_f  = OpLoad %f32 %inloc_f\n"
3956                 "%negate   = OpFNegate %f32 %inval_f\n"
3957                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
3958                 "            OpStore %outloc_f %negate\n"
3959                 "            OpBranch %if_merge\n"
3960
3961                 // Merge block for if-statement: placed in the middle of true and false branch.
3962                 "%if_merge = OpLabel\n"
3963                 "            OpReturn\n"
3964
3965                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
3966                 "%if_true  = OpLabel\n"
3967                 "%xval_t   = OpLoad %u32 %xvar\n"
3968                 "%mod      = OpUMod %u32 %xval_t %const3\n"
3969                 "            OpSelectionMerge %switch_merge None\n"
3970                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
3971
3972                 // Merge block for switch-statement: placed before the case
3973                 // bodies.  But it must follow OpSwitch which dominates it.
3974                 "%switch_merge = OpLabel\n"
3975                 "                OpBranch %if_merge\n"
3976
3977                 // Case 1 for switch-statement: placed before case 0.
3978                 // It must follow the OpSwitch that dominates it.
3979                 "%case1    = OpLabel\n"
3980                 "%x_1      = OpLoad %u32 %xvar\n"
3981                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
3982                 "%inval_1  = OpLoad %f32 %inloc_1\n"
3983                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
3984                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
3985                 "            OpStore %outloc_1 %addf42\n"
3986                 "            OpBranch %switch_merge\n"
3987
3988                 // Case 2 for switch-statement.
3989                 "%case2    = OpLabel\n"
3990                 "%x_2      = OpLoad %u32 %xvar\n"
3991                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
3992                 "%inval_2  = OpLoad %f32 %inloc_2\n"
3993                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
3994                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
3995                 "            OpStore %outloc_2 %subf27\n"
3996                 "            OpBranch %switch_merge\n"
3997
3998                 // Default case for switch-statement: placed in the middle of normal cases.
3999                 "%default = OpLabel\n"
4000                 "           OpBranch %switch_merge\n"
4001
4002                 // Case 0 for switch-statement: out of order.
4003                 "%case0    = OpLabel\n"
4004                 "%x_0      = OpLoad %u32 %xvar\n"
4005                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
4006                 "%inval_0  = OpLoad %f32 %inloc_0\n"
4007                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
4008                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
4009                 "            OpStore %outloc_0 %addf1p5\n"
4010                 "            OpBranch %switch_merge\n"
4011
4012                 "            OpFunctionEnd\n";
4013         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4014         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4015         spec.numWorkGroups = IVec3(numElements, 1, 1);
4016
4017         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
4018
4019         return group.release();
4020 }
4021
4022 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
4023 {
4024         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
4025         ComputeShaderSpec                               spec1;
4026         ComputeShaderSpec                               spec2;
4027         de::Random                                              rnd                             (deStringHash(group->getName()));
4028         const int                                               numElements             = 100;
4029         vector<float>                                   inputFloats             (numElements, 0);
4030         vector<float>                                   outputFloats1   (numElements, 0);
4031         vector<float>                                   outputFloats2   (numElements, 0);
4032         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
4033
4034         for (size_t ndx = 0; ndx < numElements; ++ndx)
4035         {
4036                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
4037                 outputFloats2[ndx] = -inputFloats[ndx];
4038         }
4039
4040         const string assembly(
4041                 "OpCapability Shader\n"
4042                 "OpMemoryModel Logical GLSL450\n"
4043                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
4044                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
4045                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
4046                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
4047                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
4048                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
4049
4050                 "OpName %comp_main1              \"entrypoint1\"\n"
4051                 "OpName %comp_main2              \"entrypoint2\"\n"
4052                 "OpName %vert_main               \"entrypoint2\"\n"
4053                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
4054                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
4055                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
4056                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
4057                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
4058                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
4059                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
4060
4061                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
4062                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
4063                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
4064                 "OpDecorate %vert_builtin_st         Block\n"
4065                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
4066                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
4067                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
4068
4069                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4070
4071                 "%zero       = OpConstant %i32 0\n"
4072                 "%one        = OpConstant %u32 1\n"
4073                 "%c_f32_1    = OpConstant %f32 1\n"
4074
4075                 "%i32inputptr         = OpTypePointer Input %i32\n"
4076                 "%vec4                = OpTypeVector %f32 4\n"
4077                 "%vec4ptr             = OpTypePointer Output %vec4\n"
4078                 "%f32arr1             = OpTypeArray %f32 %one\n"
4079                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
4080                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
4081                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
4082
4083                 "%id         = OpVariable %uvec3ptr Input\n"
4084                 "%vertexIndex = OpVariable %i32inputptr Input\n"
4085                 "%instanceIndex = OpVariable %i32inputptr Input\n"
4086                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
4087
4088                 // gl_Position = vec4(1.);
4089                 "%vert_main  = OpFunction %void None %voidf\n"
4090                 "%vert_entry = OpLabel\n"
4091                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
4092                 "              OpStore %position %c_vec4_1\n"
4093                 "              OpReturn\n"
4094                 "              OpFunctionEnd\n"
4095
4096                 // Double inputs.
4097                 "%comp_main1  = OpFunction %void None %voidf\n"
4098                 "%comp1_entry = OpLabel\n"
4099                 "%idval1      = OpLoad %uvec3 %id\n"
4100                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
4101                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
4102                 "%inval1      = OpLoad %f32 %inloc1\n"
4103                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
4104                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
4105                 "               OpStore %outloc1 %add\n"
4106                 "               OpReturn\n"
4107                 "               OpFunctionEnd\n"
4108
4109                 // Negate inputs.
4110                 "%comp_main2  = OpFunction %void None %voidf\n"
4111                 "%comp2_entry = OpLabel\n"
4112                 "%idval2      = OpLoad %uvec3 %id\n"
4113                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
4114                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
4115                 "%inval2      = OpLoad %f32 %inloc2\n"
4116                 "%neg         = OpFNegate %f32 %inval2\n"
4117                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
4118                 "               OpStore %outloc2 %neg\n"
4119                 "               OpReturn\n"
4120                 "               OpFunctionEnd\n");
4121
4122         spec1.assembly = assembly;
4123         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4124         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
4125         spec1.numWorkGroups = IVec3(numElements, 1, 1);
4126         spec1.entryPoint = "entrypoint1";
4127
4128         spec2.assembly = assembly;
4129         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4130         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
4131         spec2.numWorkGroups = IVec3(numElements, 1, 1);
4132         spec2.entryPoint = "entrypoint2";
4133
4134         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
4135         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
4136
4137         return group.release();
4138 }
4139
4140 inline std::string makeLongUTF8String (size_t num4ByteChars)
4141 {
4142         // An example of a longest valid UTF-8 character.  Be explicit about the
4143         // character type because Microsoft compilers can otherwise interpret the
4144         // character string as being over wide (16-bit) characters. Ideally, we
4145         // would just use a C++11 UTF-8 string literal, but we want to support older
4146         // Microsoft compilers.
4147         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
4148         std::string longString;
4149         longString.reserve(num4ByteChars * 4);
4150         for (size_t count = 0; count < num4ByteChars; count++)
4151         {
4152                 longString += earthAfrica;
4153         }
4154         return longString;
4155 }
4156
4157 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
4158 {
4159         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
4160         vector<CaseParameter>                   cases;
4161         de::Random                                              rnd                             (deStringHash(group->getName()));
4162         const int                                               numElements             = 100;
4163         vector<float>                                   positiveFloats  (numElements, 0);
4164         vector<float>                                   negativeFloats  (numElements, 0);
4165         const StringTemplate                    shaderTemplate  (
4166                 "OpCapability Shader\n"
4167                 "OpMemoryModel Logical GLSL450\n"
4168
4169                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4170                 "OpExecutionMode %main LocalSize 1 1 1\n"
4171
4172                 "${SOURCE}\n"
4173
4174                 "OpName %main           \"main\"\n"
4175                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4176
4177                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4178
4179                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4180
4181                 "%id        = OpVariable %uvec3ptr Input\n"
4182                 "%zero      = OpConstant %i32 0\n"
4183
4184                 "%main      = OpFunction %void None %voidf\n"
4185                 "%label     = OpLabel\n"
4186                 "%idval     = OpLoad %uvec3 %id\n"
4187                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4188                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4189                 "%inval     = OpLoad %f32 %inloc\n"
4190                 "%neg       = OpFNegate %f32 %inval\n"
4191                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4192                 "             OpStore %outloc %neg\n"
4193                 "             OpReturn\n"
4194                 "             OpFunctionEnd\n");
4195
4196         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
4197         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
4198         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
4199                                                                                                                                                         "OpSource GLSL 430 %fname"));
4200         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
4201                                                                                                                                                         "OpSource GLSL 430 %fname"));
4202         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
4203                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
4204         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
4205                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
4206         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
4207                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
4208         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
4209                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
4210         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
4211                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
4212                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
4213         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4214                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4215                                                                                                                                                         "OpSourceContinued \"\""));
4216         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4217                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4218                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
4219         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4220                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4221                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
4222         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4223                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
4224                                                                                                                                                         "OpSourceContinued \"void\"\n"
4225                                                                                                                                                         "OpSourceContinued \"main()\"\n"
4226                                                                                                                                                         "OpSourceContinued \"{}\""));
4227         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
4228                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
4229                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
4230
4231         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4232
4233         for (size_t ndx = 0; ndx < numElements; ++ndx)
4234                 negativeFloats[ndx] = -positiveFloats[ndx];
4235
4236         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4237         {
4238                 map<string, string>             specializations;
4239                 ComputeShaderSpec               spec;
4240
4241                 specializations["SOURCE"] = cases[caseNdx].param;
4242                 spec.assembly = shaderTemplate.specialize(specializations);
4243                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4244                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4245                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4246
4247                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4248         }
4249
4250         return group.release();
4251 }
4252
4253 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
4254 {
4255         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
4256         vector<CaseParameter>                   cases;
4257         de::Random                                              rnd                             (deStringHash(group->getName()));
4258         const int                                               numElements             = 100;
4259         vector<float>                                   inputFloats             (numElements, 0);
4260         vector<float>                                   outputFloats    (numElements, 0);
4261         const StringTemplate                    shaderTemplate  (
4262                 string(getComputeAsmShaderPreamble()) +
4263
4264                 "OpSourceExtension \"${EXTENSION}\"\n"
4265
4266                 "OpName %main           \"main\"\n"
4267                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4268
4269                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4270
4271                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4272
4273                 "%id        = OpVariable %uvec3ptr Input\n"
4274                 "%zero      = OpConstant %i32 0\n"
4275
4276                 "%main      = OpFunction %void None %voidf\n"
4277                 "%label     = OpLabel\n"
4278                 "%idval     = OpLoad %uvec3 %id\n"
4279                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4280                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4281                 "%inval     = OpLoad %f32 %inloc\n"
4282                 "%neg       = OpFNegate %f32 %inval\n"
4283                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4284                 "             OpStore %outloc %neg\n"
4285                 "             OpReturn\n"
4286                 "             OpFunctionEnd\n");
4287
4288         cases.push_back(CaseParameter("empty_extension",        ""));
4289         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
4290         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
4291         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
4292         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
4293
4294         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
4295
4296         for (size_t ndx = 0; ndx < numElements; ++ndx)
4297                 outputFloats[ndx] = -inputFloats[ndx];
4298
4299         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4300         {
4301                 map<string, string>             specializations;
4302                 ComputeShaderSpec               spec;
4303
4304                 specializations["EXTENSION"] = cases[caseNdx].param;
4305                 spec.assembly = shaderTemplate.specialize(specializations);
4306                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4307                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4308                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4309
4310                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4311         }
4312
4313         return group.release();
4314 }
4315
4316 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
4317 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
4318 {
4319         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
4320         vector<CaseParameter>                   cases;
4321         de::Random                                              rnd                             (deStringHash(group->getName()));
4322         const int                                               numElements             = 100;
4323         vector<float>                                   positiveFloats  (numElements, 0);
4324         vector<float>                                   negativeFloats  (numElements, 0);
4325         const StringTemplate                    shaderTemplate  (
4326                 string(getComputeAsmShaderPreamble()) +
4327
4328                 "OpSource GLSL 430\n"
4329                 "OpName %main           \"main\"\n"
4330                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4331
4332                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4333
4334                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4335                 "%uvec2     = OpTypeVector %u32 2\n"
4336                 "%bvec3     = OpTypeVector %bool 3\n"
4337                 "%fvec4     = OpTypeVector %f32 4\n"
4338                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
4339                 "%const100  = OpConstant %u32 100\n"
4340                 "%uarr100   = OpTypeArray %i32 %const100\n"
4341                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
4342                 "%pointer   = OpTypePointer Function %i32\n"
4343                 + string(getComputeAsmInputOutputBuffer()) +
4344
4345                 "%null      = OpConstantNull ${TYPE}\n"
4346
4347                 "%id        = OpVariable %uvec3ptr Input\n"
4348                 "%zero      = OpConstant %i32 0\n"
4349
4350                 "%main      = OpFunction %void None %voidf\n"
4351                 "%label     = OpLabel\n"
4352                 "%idval     = OpLoad %uvec3 %id\n"
4353                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4354                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4355                 "%inval     = OpLoad %f32 %inloc\n"
4356                 "%neg       = OpFNegate %f32 %inval\n"
4357                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4358                 "             OpStore %outloc %neg\n"
4359                 "             OpReturn\n"
4360                 "             OpFunctionEnd\n");
4361
4362         cases.push_back(CaseParameter("bool",                   "%bool"));
4363         cases.push_back(CaseParameter("sint32",                 "%i32"));
4364         cases.push_back(CaseParameter("uint32",                 "%u32"));
4365         cases.push_back(CaseParameter("float32",                "%f32"));
4366         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
4367         cases.push_back(CaseParameter("vec3bool",               "%bvec3"));
4368         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
4369         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
4370         cases.push_back(CaseParameter("array",                  "%uarr100"));
4371         cases.push_back(CaseParameter("struct",                 "%struct"));
4372         cases.push_back(CaseParameter("pointer",                "%pointer"));
4373
4374         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4375
4376         for (size_t ndx = 0; ndx < numElements; ++ndx)
4377                 negativeFloats[ndx] = -positiveFloats[ndx];
4378
4379         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4380         {
4381                 map<string, string>             specializations;
4382                 ComputeShaderSpec               spec;
4383
4384                 specializations["TYPE"] = cases[caseNdx].param;
4385                 spec.assembly = shaderTemplate.specialize(specializations);
4386                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4387                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4388                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4389
4390                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4391         }
4392
4393         return group.release();
4394 }
4395
4396 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4397 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4398 {
4399         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4400         vector<CaseParameter>                   cases;
4401         de::Random                                              rnd                             (deStringHash(group->getName()));
4402         const int                                               numElements             = 100;
4403         vector<float>                                   positiveFloats  (numElements, 0);
4404         vector<float>                                   negativeFloats  (numElements, 0);
4405         const StringTemplate                    shaderTemplate  (
4406                 string(getComputeAsmShaderPreamble()) +
4407
4408                 "OpSource GLSL 430\n"
4409                 "OpName %main           \"main\"\n"
4410                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4411
4412                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4413
4414                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4415
4416                 "%id        = OpVariable %uvec3ptr Input\n"
4417                 "%zero      = OpConstant %i32 0\n"
4418
4419                 "${CONSTANT}\n"
4420
4421                 "%main      = OpFunction %void None %voidf\n"
4422                 "%label     = OpLabel\n"
4423                 "%idval     = OpLoad %uvec3 %id\n"
4424                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4425                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4426                 "%inval     = OpLoad %f32 %inloc\n"
4427                 "%neg       = OpFNegate %f32 %inval\n"
4428                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4429                 "             OpStore %outloc %neg\n"
4430                 "             OpReturn\n"
4431                 "             OpFunctionEnd\n");
4432
4433         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
4434                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
4435         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4436                                                                                                         "%ten = OpConstant %f32 10.\n"
4437                                                                                                         "%fzero = OpConstant %f32 0.\n"
4438                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4439                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4440         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
4441                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4442                                                                                                         "%fzero = OpConstant %f32 0.\n"
4443                                                                                                         "%one = OpConstant %f32 1.\n"
4444                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4445                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4446                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4447                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4448         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
4449                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
4450                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
4451                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4452                                                                                                         "%one = OpConstant %u32 1\n"
4453                                                                                                         "%ten = OpConstant %i32 10\n"
4454                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
4455                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
4456                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
4457
4458         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4459
4460         for (size_t ndx = 0; ndx < numElements; ++ndx)
4461                 negativeFloats[ndx] = -positiveFloats[ndx];
4462
4463         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4464         {
4465                 map<string, string>             specializations;
4466                 ComputeShaderSpec               spec;
4467
4468                 specializations["CONSTANT"] = cases[caseNdx].param;
4469                 spec.assembly = shaderTemplate.specialize(specializations);
4470                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4471                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4472                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4473
4474                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4475         }
4476
4477         return group.release();
4478 }
4479
4480 // Creates a floating point number with the given exponent, and significand
4481 // bits set. It can only create normalized numbers. Only the least significant
4482 // 24 bits of the significand will be examined. The final bit of the
4483 // significand will also be ignored. This allows alignment to be written
4484 // similarly to C99 hex-floats.
4485 // For example if you wanted to write 0x1.7f34p-12 you would call
4486 // constructNormalizedFloat(-12, 0x7f3400)
4487 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4488 {
4489         float f = 1.0f;
4490
4491         for (deInt32 idx = 0; idx < 23; ++idx)
4492         {
4493                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4494                 significand <<= 1;
4495         }
4496
4497         return std::ldexp(f, exponent);
4498 }
4499
4500 // Compare instruction for the OpQuantizeF16 compute exact case.
4501 // Returns true if the output is what is expected from the test case.
4502 bool compareOpQuantizeF16ComputeExactCase (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4503 {
4504         if (outputAllocs.size() != 1)
4505                 return false;
4506
4507         // Only size is needed because we cannot compare Nans.
4508         size_t byteSize = expectedOutputs[0].getByteSize();
4509
4510         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4511
4512         if (byteSize != 4*sizeof(float)) {
4513                 return false;
4514         }
4515
4516         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4517                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4518                 return false;
4519         }
4520         outputAsFloat++;
4521
4522         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4523                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4524                 return false;
4525         }
4526         outputAsFloat++;
4527
4528         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4529                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4530                 return false;
4531         }
4532         outputAsFloat++;
4533
4534         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4535                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4536                 return false;
4537         }
4538
4539         return true;
4540 }
4541
4542 // Checks that every output from a test-case is a float NaN.
4543 bool compareNan (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4544 {
4545         if (outputAllocs.size() != 1)
4546                 return false;
4547
4548         // Only size is needed because we cannot compare Nans.
4549         size_t byteSize = expectedOutputs[0].getByteSize();
4550
4551         const float* const      output_as_float = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4552
4553         for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4554         {
4555                 if (!deFloatIsNaN(output_as_float[idx]))
4556                 {
4557                         return false;
4558                 }
4559         }
4560
4561         return true;
4562 }
4563
4564 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4565 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4566 {
4567         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4568
4569         const std::string shader (
4570                 string(getComputeAsmShaderPreamble()) +
4571
4572                 "OpSource GLSL 430\n"
4573                 "OpName %main           \"main\"\n"
4574                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4575
4576                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4577
4578                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4579
4580                 "%id        = OpVariable %uvec3ptr Input\n"
4581                 "%zero      = OpConstant %i32 0\n"
4582
4583                 "%main      = OpFunction %void None %voidf\n"
4584                 "%label     = OpLabel\n"
4585                 "%idval     = OpLoad %uvec3 %id\n"
4586                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4587                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4588                 "%inval     = OpLoad %f32 %inloc\n"
4589                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
4590                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4591                 "             OpStore %outloc %quant\n"
4592                 "             OpReturn\n"
4593                 "             OpFunctionEnd\n");
4594
4595         {
4596                 ComputeShaderSpec       spec;
4597                 const deUint32          numElements             = 100;
4598                 vector<float>           infinities;
4599                 vector<float>           results;
4600
4601                 infinities.reserve(numElements);
4602                 results.reserve(numElements);
4603
4604                 for (size_t idx = 0; idx < numElements; ++idx)
4605                 {
4606                         switch(idx % 4)
4607                         {
4608                                 case 0:
4609                                         infinities.push_back(std::numeric_limits<float>::infinity());
4610                                         results.push_back(std::numeric_limits<float>::infinity());
4611                                         break;
4612                                 case 1:
4613                                         infinities.push_back(-std::numeric_limits<float>::infinity());
4614                                         results.push_back(-std::numeric_limits<float>::infinity());
4615                                         break;
4616                                 case 2:
4617                                         infinities.push_back(std::ldexp(1.0f, 16));
4618                                         results.push_back(std::numeric_limits<float>::infinity());
4619                                         break;
4620                                 case 3:
4621                                         infinities.push_back(std::ldexp(-1.0f, 32));
4622                                         results.push_back(-std::numeric_limits<float>::infinity());
4623                                         break;
4624                         }
4625                 }
4626
4627                 spec.assembly = shader;
4628                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4629                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4630                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4631
4632                 group->addChild(new SpvAsmComputeShaderCase(
4633                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4634         }
4635
4636         {
4637                 ComputeShaderSpec       spec;
4638                 vector<float>           nans;
4639                 const deUint32          numElements             = 100;
4640
4641                 nans.reserve(numElements);
4642
4643                 for (size_t idx = 0; idx < numElements; ++idx)
4644                 {
4645                         if (idx % 2 == 0)
4646                         {
4647                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
4648                         }
4649                         else
4650                         {
4651                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4652                         }
4653                 }
4654
4655                 spec.assembly = shader;
4656                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4657                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4658                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4659                 spec.verifyIO = &compareNan;
4660
4661                 group->addChild(new SpvAsmComputeShaderCase(
4662                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4663         }
4664
4665         {
4666                 ComputeShaderSpec       spec;
4667                 vector<float>           small;
4668                 vector<float>           zeros;
4669                 const deUint32          numElements             = 100;
4670
4671                 small.reserve(numElements);
4672                 zeros.reserve(numElements);
4673
4674                 for (size_t idx = 0; idx < numElements; ++idx)
4675                 {
4676                         switch(idx % 6)
4677                         {
4678                                 case 0:
4679                                         small.push_back(0.f);
4680                                         zeros.push_back(0.f);
4681                                         break;
4682                                 case 1:
4683                                         small.push_back(-0.f);
4684                                         zeros.push_back(-0.f);
4685                                         break;
4686                                 case 2:
4687                                         small.push_back(std::ldexp(1.0f, -16));
4688                                         zeros.push_back(0.f);
4689                                         break;
4690                                 case 3:
4691                                         small.push_back(std::ldexp(-1.0f, -32));
4692                                         zeros.push_back(-0.f);
4693                                         break;
4694                                 case 4:
4695                                         small.push_back(std::ldexp(1.0f, -127));
4696                                         zeros.push_back(0.f);
4697                                         break;
4698                                 case 5:
4699                                         small.push_back(-std::ldexp(1.0f, -128));
4700                                         zeros.push_back(-0.f);
4701                                         break;
4702                         }
4703                 }
4704
4705                 spec.assembly = shader;
4706                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4707                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4708                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4709
4710                 group->addChild(new SpvAsmComputeShaderCase(
4711                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4712         }
4713
4714         {
4715                 ComputeShaderSpec       spec;
4716                 vector<float>           exact;
4717                 const deUint32          numElements             = 200;
4718
4719                 exact.reserve(numElements);
4720
4721                 for (size_t idx = 0; idx < numElements; ++idx)
4722                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4723
4724                 spec.assembly = shader;
4725                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4726                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4727                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4728
4729                 group->addChild(new SpvAsmComputeShaderCase(
4730                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4731         }
4732
4733         {
4734                 ComputeShaderSpec       spec;
4735                 vector<float>           inputs;
4736                 const deUint32          numElements             = 4;
4737
4738                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
4739                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
4740                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
4741                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
4742
4743                 spec.assembly = shader;
4744                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4745                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4746                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4747                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4748
4749                 group->addChild(new SpvAsmComputeShaderCase(
4750                         testCtx, "rounded", "Check that are rounded when needed", spec));
4751         }
4752
4753         return group.release();
4754 }
4755
4756 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4757 {
4758         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4759
4760         const std::string shader (
4761                 string(getComputeAsmShaderPreamble()) +
4762
4763                 "OpName %main           \"main\"\n"
4764                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4765
4766                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4767
4768                 "OpDecorate %sc_0  SpecId 0\n"
4769                 "OpDecorate %sc_1  SpecId 1\n"
4770                 "OpDecorate %sc_2  SpecId 2\n"
4771                 "OpDecorate %sc_3  SpecId 3\n"
4772                 "OpDecorate %sc_4  SpecId 4\n"
4773                 "OpDecorate %sc_5  SpecId 5\n"
4774
4775                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4776
4777                 "%id        = OpVariable %uvec3ptr Input\n"
4778                 "%zero      = OpConstant %i32 0\n"
4779                 "%c_u32_6   = OpConstant %u32 6\n"
4780
4781                 "%sc_0      = OpSpecConstant %f32 0.\n"
4782                 "%sc_1      = OpSpecConstant %f32 0.\n"
4783                 "%sc_2      = OpSpecConstant %f32 0.\n"
4784                 "%sc_3      = OpSpecConstant %f32 0.\n"
4785                 "%sc_4      = OpSpecConstant %f32 0.\n"
4786                 "%sc_5      = OpSpecConstant %f32 0.\n"
4787
4788                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4789                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4790                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4791                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4792                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4793                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4794
4795                 "%main      = OpFunction %void None %voidf\n"
4796                 "%label     = OpLabel\n"
4797                 "%idval     = OpLoad %uvec3 %id\n"
4798                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4799                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4800                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
4801                 "            OpSelectionMerge %exit None\n"
4802                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4803
4804                 "%case0     = OpLabel\n"
4805                 "             OpStore %outloc %sc_0_quant\n"
4806                 "             OpBranch %exit\n"
4807
4808                 "%case1     = OpLabel\n"
4809                 "             OpStore %outloc %sc_1_quant\n"
4810                 "             OpBranch %exit\n"
4811
4812                 "%case2     = OpLabel\n"
4813                 "             OpStore %outloc %sc_2_quant\n"
4814                 "             OpBranch %exit\n"
4815
4816                 "%case3     = OpLabel\n"
4817                 "             OpStore %outloc %sc_3_quant\n"
4818                 "             OpBranch %exit\n"
4819
4820                 "%case4     = OpLabel\n"
4821                 "             OpStore %outloc %sc_4_quant\n"
4822                 "             OpBranch %exit\n"
4823
4824                 "%case5     = OpLabel\n"
4825                 "             OpStore %outloc %sc_5_quant\n"
4826                 "             OpBranch %exit\n"
4827
4828                 "%exit      = OpLabel\n"
4829                 "             OpReturn\n"
4830
4831                 "             OpFunctionEnd\n");
4832
4833         {
4834                 ComputeShaderSpec       spec;
4835                 const deUint8           numCases        = 4;
4836                 vector<float>           inputs          (numCases, 0.f);
4837                 vector<float>           outputs;
4838
4839                 spec.assembly           = shader;
4840                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4841
4842                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4843                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4844                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4845                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4846
4847                 outputs.push_back(std::numeric_limits<float>::infinity());
4848                 outputs.push_back(-std::numeric_limits<float>::infinity());
4849                 outputs.push_back(std::numeric_limits<float>::infinity());
4850                 outputs.push_back(-std::numeric_limits<float>::infinity());
4851
4852                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4853                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4854
4855                 group->addChild(new SpvAsmComputeShaderCase(
4856                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4857         }
4858
4859         {
4860                 ComputeShaderSpec       spec;
4861                 const deUint8           numCases        = 2;
4862                 vector<float>           inputs          (numCases, 0.f);
4863                 vector<float>           outputs;
4864
4865                 spec.assembly           = shader;
4866                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4867                 spec.verifyIO           = &compareNan;
4868
4869                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
4870                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
4871
4872                 for (deUint8 idx = 0; idx < numCases; ++idx)
4873                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4874
4875                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4876                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4877
4878                 group->addChild(new SpvAsmComputeShaderCase(
4879                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4880         }
4881
4882         {
4883                 ComputeShaderSpec       spec;
4884                 const deUint8           numCases        = 6;
4885                 vector<float>           inputs          (numCases, 0.f);
4886                 vector<float>           outputs;
4887
4888                 spec.assembly           = shader;
4889                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4890
4891                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(0.f));
4892                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-0.f));
4893                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
4894                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
4895                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
4896                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
4897
4898                 outputs.push_back(0.f);
4899                 outputs.push_back(-0.f);
4900                 outputs.push_back(0.f);
4901                 outputs.push_back(-0.f);
4902                 outputs.push_back(0.f);
4903                 outputs.push_back(-0.f);
4904
4905                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4906                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4907
4908                 group->addChild(new SpvAsmComputeShaderCase(
4909                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4910         }
4911
4912         {
4913                 ComputeShaderSpec       spec;
4914                 const deUint8           numCases        = 6;
4915                 vector<float>           inputs          (numCases, 0.f);
4916                 vector<float>           outputs;
4917
4918                 spec.assembly           = shader;
4919                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4920
4921                 for (deUint8 idx = 0; idx < 6; ++idx)
4922                 {
4923                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
4924                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(f));
4925                         outputs.push_back(f);
4926                 }
4927
4928                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4929                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4930
4931                 group->addChild(new SpvAsmComputeShaderCase(
4932                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4933         }
4934
4935         {
4936                 ComputeShaderSpec       spec;
4937                 const deUint8           numCases        = 4;
4938                 vector<float>           inputs          (numCases, 0.f);
4939                 vector<float>           outputs;
4940
4941                 spec.assembly           = shader;
4942                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4943                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
4944
4945                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
4946                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
4947                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
4948                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
4949
4950                 for (deUint8 idx = 0; idx < numCases; ++idx)
4951                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4952
4953                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4954                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4955
4956                 group->addChild(new SpvAsmComputeShaderCase(
4957                         testCtx, "rounded", "Check that are rounded when needed", spec));
4958         }
4959
4960         return group.release();
4961 }
4962
4963 // Checks that constant null/composite values can be used in computation.
4964 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
4965 {
4966         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
4967         ComputeShaderSpec                               spec;
4968         de::Random                                              rnd                             (deStringHash(group->getName()));
4969         const int                                               numElements             = 100;
4970         vector<float>                                   positiveFloats  (numElements, 0);
4971         vector<float>                                   negativeFloats  (numElements, 0);
4972
4973         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4974
4975         for (size_t ndx = 0; ndx < numElements; ++ndx)
4976                 negativeFloats[ndx] = -positiveFloats[ndx];
4977
4978         spec.assembly =
4979                 "OpCapability Shader\n"
4980                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
4981                 "OpMemoryModel Logical GLSL450\n"
4982                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4983                 "OpExecutionMode %main LocalSize 1 1 1\n"
4984
4985                 "OpSource GLSL 430\n"
4986                 "OpName %main           \"main\"\n"
4987                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4988
4989                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4990
4991                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4992
4993                 "%fmat      = OpTypeMatrix %fvec3 3\n"
4994                 "%ten       = OpConstant %u32 10\n"
4995                 "%f32arr10  = OpTypeArray %f32 %ten\n"
4996                 "%fst       = OpTypeStruct %f32 %f32\n"
4997
4998                 + string(getComputeAsmInputOutputBuffer()) +
4999
5000                 "%id        = OpVariable %uvec3ptr Input\n"
5001                 "%zero      = OpConstant %i32 0\n"
5002
5003                 // Create a bunch of null values
5004                 "%unull     = OpConstantNull %u32\n"
5005                 "%fnull     = OpConstantNull %f32\n"
5006                 "%vnull     = OpConstantNull %fvec3\n"
5007                 "%mnull     = OpConstantNull %fmat\n"
5008                 "%anull     = OpConstantNull %f32arr10\n"
5009                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
5010
5011                 "%main      = OpFunction %void None %voidf\n"
5012                 "%label     = OpLabel\n"
5013                 "%idval     = OpLoad %uvec3 %id\n"
5014                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5015                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5016                 "%inval     = OpLoad %f32 %inloc\n"
5017                 "%neg       = OpFNegate %f32 %inval\n"
5018
5019                 // Get the abs() of (a certain element of) those null values
5020                 "%unull_cov = OpConvertUToF %f32 %unull\n"
5021                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
5022                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
5023                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
5024                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
5025                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
5026                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
5027                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
5028                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
5029                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
5030                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
5031
5032                 // Add them all
5033                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
5034                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
5035                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
5036                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
5037                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
5038                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
5039
5040                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5041                 "             OpStore %outloc %final\n" // write to output
5042                 "             OpReturn\n"
5043                 "             OpFunctionEnd\n";
5044         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5045         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5046         spec.numWorkGroups = IVec3(numElements, 1, 1);
5047
5048         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
5049
5050         return group.release();
5051 }
5052
5053 // Assembly code used for testing loop control is based on GLSL source code:
5054 // #version 430
5055 //
5056 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5057 //   float elements[];
5058 // } input_data;
5059 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5060 //   float elements[];
5061 // } output_data;
5062 //
5063 // void main() {
5064 //   uint x = gl_GlobalInvocationID.x;
5065 //   output_data.elements[x] = input_data.elements[x];
5066 //   for (uint i = 0; i < 4; ++i)
5067 //     output_data.elements[x] += 1.f;
5068 // }
5069 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
5070 {
5071         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
5072         vector<CaseParameter>                   cases;
5073         de::Random                                              rnd                             (deStringHash(group->getName()));
5074         const int                                               numElements             = 100;
5075         vector<float>                                   inputFloats             (numElements, 0);
5076         vector<float>                                   outputFloats    (numElements, 0);
5077         const StringTemplate                    shaderTemplate  (
5078                 string(getComputeAsmShaderPreamble()) +
5079
5080                 "OpSource GLSL 430\n"
5081                 "OpName %main \"main\"\n"
5082                 "OpName %id \"gl_GlobalInvocationID\"\n"
5083
5084                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5085
5086                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5087
5088                 "%u32ptr      = OpTypePointer Function %u32\n"
5089
5090                 "%id          = OpVariable %uvec3ptr Input\n"
5091                 "%zero        = OpConstant %i32 0\n"
5092                 "%uzero       = OpConstant %u32 0\n"
5093                 "%one         = OpConstant %i32 1\n"
5094                 "%constf1     = OpConstant %f32 1.0\n"
5095                 "%four        = OpConstant %u32 4\n"
5096
5097                 "%main        = OpFunction %void None %voidf\n"
5098                 "%entry       = OpLabel\n"
5099                 "%i           = OpVariable %u32ptr Function\n"
5100                 "               OpStore %i %uzero\n"
5101
5102                 "%idval       = OpLoad %uvec3 %id\n"
5103                 "%x           = OpCompositeExtract %u32 %idval 0\n"
5104                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
5105                 "%inval       = OpLoad %f32 %inloc\n"
5106                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
5107                 "               OpStore %outloc %inval\n"
5108                 "               OpBranch %loop_entry\n"
5109
5110                 "%loop_entry  = OpLabel\n"
5111                 "%i_val       = OpLoad %u32 %i\n"
5112                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
5113                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
5114                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
5115                 "%loop_body   = OpLabel\n"
5116                 "%outval      = OpLoad %f32 %outloc\n"
5117                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
5118                 "               OpStore %outloc %addf1\n"
5119                 "%new_i       = OpIAdd %u32 %i_val %one\n"
5120                 "               OpStore %i %new_i\n"
5121                 "               OpBranch %loop_entry\n"
5122                 "%loop_merge  = OpLabel\n"
5123                 "               OpReturn\n"
5124                 "               OpFunctionEnd\n");
5125
5126         cases.push_back(CaseParameter("none",                           "None"));
5127         cases.push_back(CaseParameter("unroll",                         "Unroll"));
5128         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
5129         cases.push_back(CaseParameter("unroll_dont_unroll",     "Unroll|DontUnroll"));
5130
5131         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5132
5133         for (size_t ndx = 0; ndx < numElements; ++ndx)
5134                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
5135
5136         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5137         {
5138                 map<string, string>             specializations;
5139                 ComputeShaderSpec               spec;
5140
5141                 specializations["CONTROL"] = cases[caseNdx].param;
5142                 spec.assembly = shaderTemplate.specialize(specializations);
5143                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5144                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5145                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5146
5147                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5148         }
5149
5150         group->addChild(new SpvAsmLoopControlDependencyLengthCase(testCtx, "dependency_length", "dependency_length"));
5151         group->addChild(new SpvAsmLoopControlDependencyInfiniteCase(testCtx, "dependency_infinite", "dependency_infinite"));
5152
5153         return group.release();
5154 }
5155
5156 // Assembly code used for testing selection control is based on GLSL source code:
5157 // #version 430
5158 //
5159 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5160 //   float elements[];
5161 // } input_data;
5162 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5163 //   float elements[];
5164 // } output_data;
5165 //
5166 // void main() {
5167 //   uint x = gl_GlobalInvocationID.x;
5168 //   float val = input_data.elements[x];
5169 //   if (val > 10.f)
5170 //     output_data.elements[x] = val + 1.f;
5171 //   else
5172 //     output_data.elements[x] = val - 1.f;
5173 // }
5174 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
5175 {
5176         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
5177         vector<CaseParameter>                   cases;
5178         de::Random                                              rnd                             (deStringHash(group->getName()));
5179         const int                                               numElements             = 100;
5180         vector<float>                                   inputFloats             (numElements, 0);
5181         vector<float>                                   outputFloats    (numElements, 0);
5182         const StringTemplate                    shaderTemplate  (
5183                 string(getComputeAsmShaderPreamble()) +
5184
5185                 "OpSource GLSL 430\n"
5186                 "OpName %main \"main\"\n"
5187                 "OpName %id \"gl_GlobalInvocationID\"\n"
5188
5189                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5190
5191                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5192
5193                 "%id       = OpVariable %uvec3ptr Input\n"
5194                 "%zero     = OpConstant %i32 0\n"
5195                 "%constf1  = OpConstant %f32 1.0\n"
5196                 "%constf10 = OpConstant %f32 10.0\n"
5197
5198                 "%main     = OpFunction %void None %voidf\n"
5199                 "%entry    = OpLabel\n"
5200                 "%idval    = OpLoad %uvec3 %id\n"
5201                 "%x        = OpCompositeExtract %u32 %idval 0\n"
5202                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
5203                 "%inval    = OpLoad %f32 %inloc\n"
5204                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
5205                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
5206
5207                 "            OpSelectionMerge %if_end ${CONTROL}\n"
5208                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
5209                 "%if_true  = OpLabel\n"
5210                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
5211                 "            OpStore %outloc %addf1\n"
5212                 "            OpBranch %if_end\n"
5213                 "%if_false = OpLabel\n"
5214                 "%subf1    = OpFSub %f32 %inval %constf1\n"
5215                 "            OpStore %outloc %subf1\n"
5216                 "            OpBranch %if_end\n"
5217                 "%if_end   = OpLabel\n"
5218                 "            OpReturn\n"
5219                 "            OpFunctionEnd\n");
5220
5221         cases.push_back(CaseParameter("none",                                   "None"));
5222         cases.push_back(CaseParameter("flatten",                                "Flatten"));
5223         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
5224         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
5225
5226         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5227
5228         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5229         floorAll(inputFloats);
5230
5231         for (size_t ndx = 0; ndx < numElements; ++ndx)
5232                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
5233
5234         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5235         {
5236                 map<string, string>             specializations;
5237                 ComputeShaderSpec               spec;
5238
5239                 specializations["CONTROL"] = cases[caseNdx].param;
5240                 spec.assembly = shaderTemplate.specialize(specializations);
5241                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5242                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5243                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5244
5245                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5246         }
5247
5248         return group.release();
5249 }
5250
5251 void getOpNameAbuseCases (vector<CaseParameter> &abuseCases)
5252 {
5253         // Generate a long name.
5254         std::string longname;
5255         longname.resize(65535, 'k'); // max string literal, spir-v 2.17
5256
5257         // Some bad names, abusing utf-8 encoding. This may also cause problems
5258         // with the logs.
5259         // 1. Various illegal code points in utf-8
5260         std::string utf8illegal =
5261                 "Illegal bytes in UTF-8: "
5262                 "\xc0 \xc1 \xf5 \xf6 \xf7 \xf8 \xf9 \xfa \xfb \xfc \xfd \xfe \xff"
5263                 "illegal surrogates: \xed\xad\xbf \xed\xbe\x80";
5264
5265         // 2. Zero encoded as overlong, not exactly legal but often supported to differentiate from terminating zero
5266         std::string utf8nul = "UTF-8 encoded nul \xC0\x80 (should not end name)";
5267
5268         // 3. Some overlong encodings
5269         std::string utf8overlong =
5270                 "UTF-8 overlong \xF0\x82\x82\xAC \xfc\x83\xbf\xbf\xbf\xbf \xf8\x87\xbf\xbf\xbf "
5271                 "\xf0\x8f\xbf\xbf";
5272
5273         // 4. Internet "zalgo" meme "bleeding text"
5274         std::string utf8zalgo =
5275                 "\x56\xcc\xb5\xcc\x85\xcc\x94\xcc\x88\xcd\x8a\xcc\x91\xcc\x88\xcd\x91\xcc\x83\xcd\x82"
5276                 "\xcc\x83\xcd\x90\xcc\x8a\xcc\x92\xcc\x92\xcd\x8b\xcc\x94\xcd\x9d\xcc\x98\xcc\xab\xcc"
5277                 "\xae\xcc\xa9\xcc\xad\xcc\x97\xcc\xb0\x75\xcc\xb6\xcc\xbe\xcc\x80\xcc\x82\xcc\x84\xcd"
5278                 "\x84\xcc\x90\xcd\x86\xcc\x9a\xcd\x84\xcc\x9b\xcd\x86\xcd\x92\xcc\x9a\xcd\x99\xcd\x99"
5279                 "\xcc\xbb\xcc\x98\xcd\x8e\xcd\x88\xcd\x9a\xcc\xa6\xcc\x9c\xcc\xab\xcc\x99\xcd\x94\xcd"
5280                 "\x99\xcd\x95\xcc\xa5\xcc\xab\xcd\x89\x6c\xcc\xb8\xcc\x8e\xcc\x8b\xcc\x8b\xcc\x9a\xcc"
5281                 "\x8e\xcd\x9d\xcc\x80\xcc\xa1\xcc\xad\xcd\x9c\xcc\xba\xcc\x96\xcc\xb3\xcc\xa2\xcd\x8e"
5282                 "\xcc\xa2\xcd\x96\x6b\xcc\xb8\xcc\x84\xcd\x81\xcc\xbf\xcc\x8d\xcc\x89\xcc\x85\xcc\x92"
5283                 "\xcc\x84\xcc\x90\xcd\x81\xcc\x93\xcd\x90\xcd\x92\xcd\x9d\xcc\x84\xcd\x98\xcd\x9d\xcd"
5284                 "\xa0\xcd\x91\xcc\x94\xcc\xb9\xcd\x93\xcc\xa5\xcd\x87\xcc\xad\xcc\xa7\xcd\x96\xcd\x99"
5285                 "\xcc\x9d\xcc\xbc\xcd\x96\xcd\x93\xcc\x9d\xcc\x99\xcc\xa8\xcc\xb1\xcd\x85\xcc\xba\xcc"
5286                 "\xa7\x61\xcc\xb8\xcc\x8e\xcc\x81\xcd\x90\xcd\x84\xcd\x8c\xcc\x8c\xcc\x85\xcd\x86\xcc"
5287                 "\x84\xcd\x84\xcc\x90\xcc\x84\xcc\x8d\xcd\x99\xcd\x8d\xcc\xb0\xcc\xa3\xcc\xa6\xcd\x89"
5288                 "\xcd\x8d\xcd\x87\xcc\x98\xcd\x8d\xcc\xa4\xcd\x9a\xcd\x8e\xcc\xab\xcc\xb9\xcc\xac\xcc"
5289                 "\xa2\xcd\x87\xcc\xa0\xcc\xb3\xcd\x89\xcc\xb9\xcc\xa7\xcc\xa6\xcd\x89\xcd\x95\x6e\xcc"
5290                 "\xb8\xcd\x8a\xcc\x8a\xcd\x82\xcc\x9b\xcd\x81\xcd\x90\xcc\x85\xcc\x9b\xcd\x80\xcd\x91"
5291                 "\xcd\x9b\xcc\x81\xcd\x81\xcc\x9a\xcc\xb3\xcd\x9c\xcc\x9e\xcc\x9d\xcd\x99\xcc\xa2\xcd"
5292                 "\x93\xcd\x96\xcc\x97\xff";
5293
5294         // General name abuses
5295         abuseCases.push_back(CaseParameter("_has_very_long_name", longname));
5296         abuseCases.push_back(CaseParameter("_utf8_illegal", utf8illegal));
5297         abuseCases.push_back(CaseParameter("_utf8_nul", utf8nul));
5298         abuseCases.push_back(CaseParameter("_utf8_overlong", utf8overlong));
5299         abuseCases.push_back(CaseParameter("_utf8_zalgo", utf8zalgo));
5300
5301         // GL keywords
5302         abuseCases.push_back(CaseParameter("_is_gl_Position", "gl_Position"));
5303         abuseCases.push_back(CaseParameter("_is_gl_InstanceID", "gl_InstanceID"));
5304         abuseCases.push_back(CaseParameter("_is_gl_PrimitiveID", "gl_PrimitiveID"));
5305         abuseCases.push_back(CaseParameter("_is_gl_TessCoord", "gl_TessCoord"));
5306         abuseCases.push_back(CaseParameter("_is_gl_PerVertex", "gl_PerVertex"));
5307         abuseCases.push_back(CaseParameter("_is_gl_InvocationID", "gl_InvocationID"));
5308         abuseCases.push_back(CaseParameter("_is_gl_PointSize", "gl_PointSize"));
5309         abuseCases.push_back(CaseParameter("_is_gl_PointCoord", "gl_PointCoord"));
5310         abuseCases.push_back(CaseParameter("_is_gl_Layer", "gl_Layer"));
5311         abuseCases.push_back(CaseParameter("_is_gl_FragDepth", "gl_FragDepth"));
5312         abuseCases.push_back(CaseParameter("_is_gl_NumWorkGroups", "gl_NumWorkGroups"));
5313         abuseCases.push_back(CaseParameter("_is_gl_WorkGroupID", "gl_WorkGroupID"));
5314         abuseCases.push_back(CaseParameter("_is_gl_LocalInvocationID", "gl_LocalInvocationID"));
5315         abuseCases.push_back(CaseParameter("_is_gl_GlobalInvocationID", "gl_GlobalInvocationID"));
5316         abuseCases.push_back(CaseParameter("_is_gl_MaxVertexAttribs", "gl_MaxVertexAttribs"));
5317         abuseCases.push_back(CaseParameter("_is_gl_MaxViewports", "gl_MaxViewports"));
5318         abuseCases.push_back(CaseParameter("_is_gl_MaxComputeWorkGroupCount", "gl_MaxComputeWorkGroupCount"));
5319         abuseCases.push_back(CaseParameter("_is_mat3", "mat3"));
5320         abuseCases.push_back(CaseParameter("_is_volatile", "volatile"));
5321         abuseCases.push_back(CaseParameter("_is_inout", "inout"));
5322         abuseCases.push_back(CaseParameter("_is_isampler3d", "isampler3d"));
5323 }
5324
5325 tcu::TestCaseGroup* createOpNameGroup (tcu::TestContext& testCtx)
5326 {
5327         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opname", "Tests OpName cases"));
5328         de::MovePtr<tcu::TestCaseGroup> entryMainGroup  (new tcu::TestCaseGroup(testCtx, "entry_main", "OpName tests with entry main"));
5329         de::MovePtr<tcu::TestCaseGroup> entryNotGroup   (new tcu::TestCaseGroup(testCtx, "entry_rdc", "OpName tests with entry rdc"));
5330         de::MovePtr<tcu::TestCaseGroup> abuseGroup              (new tcu::TestCaseGroup(testCtx, "abuse", "OpName abuse tests"));
5331         vector<CaseParameter>                   cases;
5332         vector<CaseParameter>                   abuseCases;
5333         vector<string>                                  testFunc;
5334         de::Random                                              rnd                             (deStringHash(group->getName()));
5335         const int                                               numElements             = 128;
5336         vector<float>                                   inputFloats             (numElements, 0);
5337         vector<float>                                   outputFloats    (numElements, 0);
5338
5339         getOpNameAbuseCases(abuseCases);
5340
5341         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5342
5343         for(size_t ndx = 0; ndx < numElements; ++ndx)
5344                 outputFloats[ndx] = -inputFloats[ndx];
5345
5346         const string commonShaderHeader =
5347                 "OpCapability Shader\n"
5348                 "OpMemoryModel Logical GLSL450\n"
5349                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5350                 "OpExecutionMode %main LocalSize 1 1 1\n";
5351
5352         const string commonShaderFooter =
5353                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5354
5355                 + string(getComputeAsmInputOutputBufferTraits())
5356                 + string(getComputeAsmCommonTypes())
5357                 + string(getComputeAsmInputOutputBuffer()) +
5358
5359                 "%id        = OpVariable %uvec3ptr Input\n"
5360                 "%zero      = OpConstant %i32 0\n"
5361
5362                 "%func      = OpFunction %void None %voidf\n"
5363                 "%5         = OpLabel\n"
5364                 "             OpReturn\n"
5365                 "             OpFunctionEnd\n"
5366
5367                 "%main      = OpFunction %void None %voidf\n"
5368                 "%entry     = OpLabel\n"
5369                 "%7         = OpFunctionCall %void %func\n"
5370
5371                 "%idval     = OpLoad %uvec3 %id\n"
5372                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5373
5374                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5375                 "%inval     = OpLoad %f32 %inloc\n"
5376                 "%neg       = OpFNegate %f32 %inval\n"
5377                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5378                 "             OpStore %outloc %neg\n"
5379
5380                 "             OpReturn\n"
5381                 "             OpFunctionEnd\n";
5382
5383         const StringTemplate shaderTemplate (
5384                 "OpCapability Shader\n"
5385                 "OpMemoryModel Logical GLSL450\n"
5386                 "OpEntryPoint GLCompute %main \"${ENTRY}\" %id\n"
5387                 "OpExecutionMode %main LocalSize 1 1 1\n"
5388                 "OpName %${ID} \"${NAME}\"\n" +
5389                 commonShaderFooter);
5390
5391         const std::string multipleNames =
5392                 commonShaderHeader +
5393                 "OpName %main \"to_be\"\n"
5394                 "OpName %id   \"or_not\"\n"
5395                 "OpName %main \"to_be\"\n"
5396                 "OpName %main \"makes_no\"\n"
5397                 "OpName %func \"difference\"\n"
5398                 "OpName %5    \"to_me\"\n" +
5399                 commonShaderFooter;
5400
5401         {
5402                 ComputeShaderSpec       spec;
5403
5404                 spec.assembly           = multipleNames;
5405                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5406                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5407                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5408
5409                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "main_has_multiple_names", "multiple_names", spec));
5410         }
5411
5412         const std::string everythingNamed =
5413                 commonShaderHeader +
5414                 "OpName %main   \"name1\"\n"
5415                 "OpName %id     \"name2\"\n"
5416                 "OpName %zero   \"name3\"\n"
5417                 "OpName %entry  \"name4\"\n"
5418                 "OpName %func   \"name5\"\n"
5419                 "OpName %5      \"name6\"\n"
5420                 "OpName %7      \"name7\"\n"
5421                 "OpName %idval  \"name8\"\n"
5422                 "OpName %inloc  \"name9\"\n"
5423                 "OpName %inval  \"name10\"\n"
5424                 "OpName %neg    \"name11\"\n"
5425                 "OpName %outloc \"name12\"\n"+
5426                 commonShaderFooter;
5427         {
5428                 ComputeShaderSpec       spec;
5429
5430                 spec.assembly           = everythingNamed;
5431                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5432                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5433                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5434
5435                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named", "everything_named", spec));
5436         }
5437
5438         const std::string everythingNamedTheSame =
5439                 commonShaderHeader +
5440                 "OpName %main   \"the_same\"\n"
5441                 "OpName %id     \"the_same\"\n"
5442                 "OpName %zero   \"the_same\"\n"
5443                 "OpName %entry  \"the_same\"\n"
5444                 "OpName %func   \"the_same\"\n"
5445                 "OpName %5      \"the_same\"\n"
5446                 "OpName %7      \"the_same\"\n"
5447                 "OpName %idval  \"the_same\"\n"
5448                 "OpName %inloc  \"the_same\"\n"
5449                 "OpName %inval  \"the_same\"\n"
5450                 "OpName %neg    \"the_same\"\n"
5451                 "OpName %outloc \"the_same\"\n"+
5452                 commonShaderFooter;
5453         {
5454                 ComputeShaderSpec       spec;
5455
5456                 spec.assembly           = everythingNamedTheSame;
5457                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5458                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5459                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5460
5461                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5462         }
5463
5464         // main_is_...
5465         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5466         {
5467                 map<string, string>     specializations;
5468                 ComputeShaderSpec       spec;
5469
5470                 specializations["ENTRY"]        = "main";
5471                 specializations["ID"]           = "main";
5472                 specializations["NAME"]         = abuseCases[ndx].param;
5473                 spec.assembly                           = shaderTemplate.specialize(specializations);
5474                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5475                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5476                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5477
5478                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("main") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5479         }
5480
5481         // x_is_....
5482         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5483         {
5484                 map<string, string>     specializations;
5485                 ComputeShaderSpec       spec;
5486
5487                 specializations["ENTRY"]        = "main";
5488                 specializations["ID"]           = "x";
5489                 specializations["NAME"]         = abuseCases[ndx].param;
5490                 spec.assembly                           = shaderTemplate.specialize(specializations);
5491                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5492                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5493                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5494
5495                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5496         }
5497
5498         cases.push_back(CaseParameter("_is_main", "main"));
5499         cases.push_back(CaseParameter("_is_not_main", "not_main"));
5500         testFunc.push_back("main");
5501         testFunc.push_back("func");
5502
5503         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5504         {
5505                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5506                 {
5507                         map<string, string>     specializations;
5508                         ComputeShaderSpec       spec;
5509
5510                         specializations["ENTRY"]        = "main";
5511                         specializations["ID"]           = testFunc[fNdx];
5512                         specializations["NAME"]         = cases[ndx].param;
5513                         spec.assembly                           = shaderTemplate.specialize(specializations);
5514                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5515                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5516                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5517
5518                         entryMainGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5519                 }
5520         }
5521
5522         cases.push_back(CaseParameter("_is_entry", "rdc"));
5523
5524         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5525         {
5526                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5527                 {
5528                         map<string, string>     specializations;
5529                         ComputeShaderSpec       spec;
5530
5531                         specializations["ENTRY"]        = "rdc";
5532                         specializations["ID"]           = testFunc[fNdx];
5533                         specializations["NAME"]         = cases[ndx].param;
5534                         spec.assembly                           = shaderTemplate.specialize(specializations);
5535                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5536                         spec.entryPoint                         = "rdc";
5537                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5538                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5539
5540                         entryNotGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5541                 }
5542         }
5543
5544         group->addChild(entryMainGroup.release());
5545         group->addChild(entryNotGroup.release());
5546         group->addChild(abuseGroup.release());
5547
5548         return group.release();
5549 }
5550
5551 tcu::TestCaseGroup* createOpMemberNameGroup (tcu::TestContext& testCtx)
5552 {
5553         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opmembername", "Tests OpMemberName cases"));
5554         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "abuse", "OpMemberName abuse tests"));
5555         vector<CaseParameter>                   abuseCases;
5556         vector<string>                                  testFunc;
5557         de::Random                                              rnd(deStringHash(group->getName()));
5558         const int                                               numElements = 128;
5559         vector<float>                                   inputFloats(numElements, 0);
5560         vector<float>                                   outputFloats(numElements, 0);
5561
5562         getOpNameAbuseCases(abuseCases);
5563
5564         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5565
5566         for (size_t ndx = 0; ndx < numElements; ++ndx)
5567                 outputFloats[ndx] = -inputFloats[ndx];
5568
5569         const string commonShaderHeader =
5570                 "OpCapability Shader\n"
5571                 "OpMemoryModel Logical GLSL450\n"
5572                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5573                 "OpExecutionMode %main LocalSize 1 1 1\n";
5574
5575         const string commonShaderFooter =
5576                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5577
5578                 + string(getComputeAsmInputOutputBufferTraits())
5579                 + string(getComputeAsmCommonTypes())
5580                 + string(getComputeAsmInputOutputBuffer()) +
5581
5582                 "%u3str     = OpTypeStruct %u32 %u32 %u32\n"
5583
5584                 "%id        = OpVariable %uvec3ptr Input\n"
5585                 "%zero      = OpConstant %i32 0\n"
5586
5587                 "%main      = OpFunction %void None %voidf\n"
5588                 "%entry     = OpLabel\n"
5589
5590                 "%idval     = OpLoad %uvec3 %id\n"
5591                 "%x0        = OpCompositeExtract %u32 %idval 0\n"
5592
5593                 "%idstr     = OpCompositeConstruct %u3str %x0 %x0 %x0\n"
5594                 "%x         = OpCompositeExtract %u32 %idstr 0\n"
5595
5596                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5597                 "%inval     = OpLoad %f32 %inloc\n"
5598                 "%neg       = OpFNegate %f32 %inval\n"
5599                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5600                 "             OpStore %outloc %neg\n"
5601
5602                 "             OpReturn\n"
5603                 "             OpFunctionEnd\n";
5604
5605         const StringTemplate shaderTemplate(
5606                 commonShaderHeader +
5607                 "OpMemberName %u3str 0 \"${NAME}\"\n" +
5608                 commonShaderFooter);
5609
5610         const std::string multipleNames =
5611                 commonShaderHeader +
5612                 "OpMemberName %u3str 0 \"to_be\"\n"
5613                 "OpMemberName %u3str 1 \"or_not\"\n"
5614                 "OpMemberName %u3str 0 \"to_be\"\n"
5615                 "OpMemberName %u3str 2 \"makes_no\"\n"
5616                 "OpMemberName %u3str 0 \"difference\"\n"
5617                 "OpMemberName %u3str 0 \"to_me\"\n" +
5618                 commonShaderFooter;
5619         {
5620                 ComputeShaderSpec       spec;
5621
5622                 spec.assembly = multipleNames;
5623                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5624                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5625                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5626
5627                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "u3str_x_has_multiple_names", "multiple_names", spec));
5628         }
5629
5630         const std::string everythingNamedTheSame =
5631                 commonShaderHeader +
5632                 "OpMemberName %u3str 0 \"the_same\"\n"
5633                 "OpMemberName %u3str 1 \"the_same\"\n"
5634                 "OpMemberName %u3str 2 \"the_same\"\n" +
5635                 commonShaderFooter;
5636
5637         {
5638                 ComputeShaderSpec       spec;
5639
5640                 spec.assembly = everythingNamedTheSame;
5641                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5642                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5643                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5644
5645                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5646         }
5647
5648         // u3str_x_is_....
5649         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5650         {
5651                 map<string, string>     specializations;
5652                 ComputeShaderSpec       spec;
5653
5654                 specializations["NAME"] = abuseCases[ndx].param;
5655                 spec.assembly = shaderTemplate.specialize(specializations);
5656                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5657                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5658                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5659
5660                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("u3str_x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5661         }
5662
5663         group->addChild(abuseGroup.release());
5664
5665         return group.release();
5666 }
5667
5668 // Assembly code used for testing function control is based on GLSL source code:
5669 //
5670 // #version 430
5671 //
5672 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5673 //   float elements[];
5674 // } input_data;
5675 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5676 //   float elements[];
5677 // } output_data;
5678 //
5679 // float const10() { return 10.f; }
5680 //
5681 // void main() {
5682 //   uint x = gl_GlobalInvocationID.x;
5683 //   output_data.elements[x] = input_data.elements[x] + const10();
5684 // }
5685 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
5686 {
5687         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
5688         vector<CaseParameter>                   cases;
5689         de::Random                                              rnd                             (deStringHash(group->getName()));
5690         const int                                               numElements             = 100;
5691         vector<float>                                   inputFloats             (numElements, 0);
5692         vector<float>                                   outputFloats    (numElements, 0);
5693         const StringTemplate                    shaderTemplate  (
5694                 string(getComputeAsmShaderPreamble()) +
5695
5696                 "OpSource GLSL 430\n"
5697                 "OpName %main \"main\"\n"
5698                 "OpName %func_const10 \"const10(\"\n"
5699                 "OpName %id \"gl_GlobalInvocationID\"\n"
5700
5701                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5702
5703                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5704
5705                 "%f32f = OpTypeFunction %f32\n"
5706                 "%id = OpVariable %uvec3ptr Input\n"
5707                 "%zero = OpConstant %i32 0\n"
5708                 "%constf10 = OpConstant %f32 10.0\n"
5709
5710                 "%main         = OpFunction %void None %voidf\n"
5711                 "%entry        = OpLabel\n"
5712                 "%idval        = OpLoad %uvec3 %id\n"
5713                 "%x            = OpCompositeExtract %u32 %idval 0\n"
5714                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
5715                 "%inval        = OpLoad %f32 %inloc\n"
5716                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
5717                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
5718                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
5719                 "                OpStore %outloc %fadd\n"
5720                 "                OpReturn\n"
5721                 "                OpFunctionEnd\n"
5722
5723                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
5724                 "%label        = OpLabel\n"
5725                 "                OpReturnValue %constf10\n"
5726                 "                OpFunctionEnd\n");
5727
5728         cases.push_back(CaseParameter("none",                                           "None"));
5729         cases.push_back(CaseParameter("inline",                                         "Inline"));
5730         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
5731         cases.push_back(CaseParameter("pure",                                           "Pure"));
5732         cases.push_back(CaseParameter("const",                                          "Const"));
5733         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
5734         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
5735         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
5736         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
5737
5738         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5739
5740         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5741         floorAll(inputFloats);
5742
5743         for (size_t ndx = 0; ndx < numElements; ++ndx)
5744                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
5745
5746         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5747         {
5748                 map<string, string>             specializations;
5749                 ComputeShaderSpec               spec;
5750
5751                 specializations["CONTROL"] = cases[caseNdx].param;
5752                 spec.assembly = shaderTemplate.specialize(specializations);
5753                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5754                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5755                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5756
5757                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5758         }
5759
5760         return group.release();
5761 }
5762
5763 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5764 {
5765         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5766         vector<CaseParameter>                   cases;
5767         de::Random                                              rnd                             (deStringHash(group->getName()));
5768         const int                                               numElements             = 100;
5769         vector<float>                                   inputFloats             (numElements, 0);
5770         vector<float>                                   outputFloats    (numElements, 0);
5771         const StringTemplate                    shaderTemplate  (
5772                 string(getComputeAsmShaderPreamble()) +
5773
5774                 "OpSource GLSL 430\n"
5775                 "OpName %main           \"main\"\n"
5776                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5777
5778                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5779
5780                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5781
5782                 "%f32ptr_f  = OpTypePointer Function %f32\n"
5783
5784                 "%id        = OpVariable %uvec3ptr Input\n"
5785                 "%zero      = OpConstant %i32 0\n"
5786                 "%four      = OpConstant %i32 4\n"
5787
5788                 "%main      = OpFunction %void None %voidf\n"
5789                 "%label     = OpLabel\n"
5790                 "%copy      = OpVariable %f32ptr_f Function\n"
5791                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5792                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5793                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5794                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5795                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
5796                 "%val1      = OpLoad %f32 %copy\n"
5797                 "%val2      = OpLoad %f32 %inloc\n"
5798                 "%add       = OpFAdd %f32 %val1 %val2\n"
5799                 "             OpStore %outloc %add ${ACCESS}\n"
5800                 "             OpReturn\n"
5801                 "             OpFunctionEnd\n");
5802
5803         cases.push_back(CaseParameter("null",                                   ""));
5804         cases.push_back(CaseParameter("none",                                   "None"));
5805         cases.push_back(CaseParameter("volatile",                               "Volatile"));
5806         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
5807         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
5808         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
5809         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
5810
5811         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5812
5813         for (size_t ndx = 0; ndx < numElements; ++ndx)
5814                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5815
5816         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5817         {
5818                 map<string, string>             specializations;
5819                 ComputeShaderSpec               spec;
5820
5821                 specializations["ACCESS"] = cases[caseNdx].param;
5822                 spec.assembly = shaderTemplate.specialize(specializations);
5823                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5824                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5825                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5826
5827                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5828         }
5829
5830         return group.release();
5831 }
5832
5833 // Checks that we can get undefined values for various types, without exercising a computation with it.
5834 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5835 {
5836         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5837         vector<CaseParameter>                   cases;
5838         de::Random                                              rnd                             (deStringHash(group->getName()));
5839         const int                                               numElements             = 100;
5840         vector<float>                                   positiveFloats  (numElements, 0);
5841         vector<float>                                   negativeFloats  (numElements, 0);
5842         const StringTemplate                    shaderTemplate  (
5843                 string(getComputeAsmShaderPreamble()) +
5844
5845                 "OpSource GLSL 430\n"
5846                 "OpName %main           \"main\"\n"
5847                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5848
5849                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5850
5851                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5852                 "%uvec2     = OpTypeVector %u32 2\n"
5853                 "%fvec4     = OpTypeVector %f32 4\n"
5854                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
5855                 "%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
5856                 "%sampler   = OpTypeSampler\n"
5857                 "%simage    = OpTypeSampledImage %image\n"
5858                 "%const100  = OpConstant %u32 100\n"
5859                 "%uarr100   = OpTypeArray %i32 %const100\n"
5860                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
5861                 "%pointer   = OpTypePointer Function %i32\n"
5862                 + string(getComputeAsmInputOutputBuffer()) +
5863
5864                 "%id        = OpVariable %uvec3ptr Input\n"
5865                 "%zero      = OpConstant %i32 0\n"
5866
5867                 "%main      = OpFunction %void None %voidf\n"
5868                 "%label     = OpLabel\n"
5869
5870                 "%undef     = OpUndef ${TYPE}\n"
5871
5872                 "%idval     = OpLoad %uvec3 %id\n"
5873                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5874
5875                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5876                 "%inval     = OpLoad %f32 %inloc\n"
5877                 "%neg       = OpFNegate %f32 %inval\n"
5878                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5879                 "             OpStore %outloc %neg\n"
5880                 "             OpReturn\n"
5881                 "             OpFunctionEnd\n");
5882
5883         cases.push_back(CaseParameter("bool",                   "%bool"));
5884         cases.push_back(CaseParameter("sint32",                 "%i32"));
5885         cases.push_back(CaseParameter("uint32",                 "%u32"));
5886         cases.push_back(CaseParameter("float32",                "%f32"));
5887         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
5888         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
5889         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
5890         cases.push_back(CaseParameter("image",                  "%image"));
5891         cases.push_back(CaseParameter("sampler",                "%sampler"));
5892         cases.push_back(CaseParameter("sampledimage",   "%simage"));
5893         cases.push_back(CaseParameter("array",                  "%uarr100"));
5894         cases.push_back(CaseParameter("runtimearray",   "%f32arr"));
5895         cases.push_back(CaseParameter("struct",                 "%struct"));
5896         cases.push_back(CaseParameter("pointer",                "%pointer"));
5897
5898         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5899
5900         for (size_t ndx = 0; ndx < numElements; ++ndx)
5901                 negativeFloats[ndx] = -positiveFloats[ndx];
5902
5903         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5904         {
5905                 map<string, string>             specializations;
5906                 ComputeShaderSpec               spec;
5907
5908                 specializations["TYPE"] = cases[caseNdx].param;
5909                 spec.assembly = shaderTemplate.specialize(specializations);
5910                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5911                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5912                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5913
5914                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5915         }
5916
5917                 return group.release();
5918 }
5919
5920 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
5921 tcu::TestCaseGroup* createFloat16OpConstantCompositeGroup (tcu::TestContext& testCtx)
5922 {
5923         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
5924         vector<CaseParameter>                   cases;
5925         de::Random                                              rnd                             (deStringHash(group->getName()));
5926         const int                                               numElements             = 100;
5927         vector<float>                                   positiveFloats  (numElements, 0);
5928         vector<float>                                   negativeFloats  (numElements, 0);
5929         const StringTemplate                    shaderTemplate  (
5930                 "OpCapability Shader\n"
5931                 "OpCapability Float16\n"
5932                 "OpMemoryModel Logical GLSL450\n"
5933                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5934                 "OpExecutionMode %main LocalSize 1 1 1\n"
5935                 "OpSource GLSL 430\n"
5936                 "OpName %main           \"main\"\n"
5937                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5938
5939                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5940
5941                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5942
5943                 "%id        = OpVariable %uvec3ptr Input\n"
5944                 "%zero      = OpConstant %i32 0\n"
5945                 "%f16       = OpTypeFloat 16\n"
5946                 "%c_f16_0   = OpConstant %f16 0.0\n"
5947                 "%c_f16_0_5 = OpConstant %f16 0.5\n"
5948                 "%c_f16_1   = OpConstant %f16 1.0\n"
5949                 "%v2f16     = OpTypeVector %f16 2\n"
5950                 "%v3f16     = OpTypeVector %f16 3\n"
5951                 "%v4f16     = OpTypeVector %f16 4\n"
5952
5953                 "${CONSTANT}\n"
5954
5955                 "%main      = OpFunction %void None %voidf\n"
5956                 "%label     = OpLabel\n"
5957                 "%idval     = OpLoad %uvec3 %id\n"
5958                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5959                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5960                 "%inval     = OpLoad %f32 %inloc\n"
5961                 "%neg       = OpFNegate %f32 %inval\n"
5962                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5963                 "             OpStore %outloc %neg\n"
5964                 "             OpReturn\n"
5965                 "             OpFunctionEnd\n");
5966
5967
5968         cases.push_back(CaseParameter("vector",                 "%const = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"));
5969         cases.push_back(CaseParameter("matrix",                 "%m3v3f16 = OpTypeMatrix %v3f16 3\n"
5970                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
5971                                                                                                         "%mat = OpConstantComposite %m3v3f16 %vec %vec %vec"));
5972         cases.push_back(CaseParameter("struct",                 "%m2v3f16 = OpTypeMatrix %v3f16 2\n"
5973                                                                                                         "%struct = OpTypeStruct %i32 %f16 %v3f16 %m2v3f16\n"
5974                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
5975                                                                                                         "%mat = OpConstantComposite %m2v3f16 %vec %vec\n"
5976                                                                                                         "%const = OpConstantComposite %struct %zero %c_f16_0_5 %vec %mat\n"));
5977         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %i32 %f16\n"
5978                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
5979                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
5980                                                                                                         "%st1val = OpConstantComposite %st1 %zero %c_f16_0_5\n"
5981                                                                                                         "%st2val = OpConstantComposite %st2 %zero %zero\n"
5982                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
5983
5984         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5985
5986         for (size_t ndx = 0; ndx < numElements; ++ndx)
5987                 negativeFloats[ndx] = -positiveFloats[ndx];
5988
5989         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5990         {
5991                 map<string, string>             specializations;
5992                 ComputeShaderSpec               spec;
5993
5994                 specializations["CONSTANT"] = cases[caseNdx].param;
5995                 spec.assembly = shaderTemplate.specialize(specializations);
5996                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5997                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5998                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5999
6000                 spec.extensions.push_back("VK_KHR_16bit_storage");
6001                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
6002
6003                 spec.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
6004                 spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
6005
6006                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
6007         }
6008
6009         return group.release();
6010 }
6011
6012 const vector<deFloat16> squarize(const vector<deFloat16>& inData, const deUint32 argNo)
6013 {
6014         const size_t            inDataLength    = inData.size();
6015         vector<deFloat16>       result;
6016
6017         result.reserve(inDataLength * inDataLength);
6018
6019         if (argNo == 0)
6020         {
6021                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6022                         result.insert(result.end(), inData.begin(), inData.end());
6023         }
6024
6025         if (argNo == 1)
6026         {
6027                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6028                 {
6029                         const vector<deFloat16> tmp(inDataLength, inData[numIdx]);
6030
6031                         result.insert(result.end(), tmp.begin(), tmp.end());
6032                 }
6033         }
6034
6035         return result;
6036 }
6037
6038 const vector<deFloat16> squarizeVector(const vector<deFloat16>& inData, const deUint32 argNo)
6039 {
6040         vector<deFloat16>       vec;
6041         vector<deFloat16>       result;
6042
6043         // Create vectors. vec will contain each possible pair from inData
6044         {
6045                 const size_t    inDataLength    = inData.size();
6046
6047                 DE_ASSERT(inDataLength <= 64);
6048
6049                 vec.reserve(2 * inDataLength * inDataLength);
6050
6051                 for (size_t numIdxX = 0; numIdxX < inDataLength; ++numIdxX)
6052                 for (size_t numIdxY = 0; numIdxY < inDataLength; ++numIdxY)
6053                 {
6054                         vec.push_back(inData[numIdxX]);
6055                         vec.push_back(inData[numIdxY]);
6056                 }
6057         }
6058
6059         // Create vector pairs. result will contain each possible pair from vec
6060         {
6061                 const size_t    coordsPerVector = 2;
6062                 const size_t    vectorsCount    = vec.size() / coordsPerVector;
6063
6064                 result.reserve(coordsPerVector * vectorsCount * vectorsCount);
6065
6066                 if (argNo == 0)
6067                 {
6068                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6069                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6070                         {
6071                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6072                                         result.push_back(vec[coordsPerVector * numIdxY + coordNdx]);
6073                         }
6074                 }
6075
6076                 if (argNo == 1)
6077                 {
6078                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6079                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6080                         {
6081                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6082                                         result.push_back(vec[coordsPerVector * numIdxX + coordNdx]);
6083                         }
6084                 }
6085         }
6086
6087         return result;
6088 }
6089
6090 struct fp16isNan                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isNaN(); } };
6091 struct fp16isInf                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isInf(); } };
6092 struct fp16isEqual                      { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() == in2.asFloat(); } };
6093 struct fp16isUnequal            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() != in2.asFloat(); } };
6094 struct fp16isLess                       { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <  in2.asFloat(); } };
6095 struct fp16isGreater            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >  in2.asFloat(); } };
6096 struct fp16isLessOrEqual        { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <= in2.asFloat(); } };
6097 struct fp16isGreaterOrEqual     { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >= in2.asFloat(); } };
6098
6099 template <class TestedLogicalFunction, bool onlyTestFunc, bool unationModeAnd, bool nanSupported>
6100 bool compareFP16Logical (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
6101 {
6102         if (inputs.size() != 2 || outputAllocs.size() != 1)
6103                 return false;
6104
6105         vector<deUint8> input1Bytes;
6106         vector<deUint8> input2Bytes;
6107
6108         inputs[0].getBytes(input1Bytes);
6109         inputs[1].getBytes(input2Bytes);
6110
6111         const deUint32                  denormModesCount                        = 2;
6112         const deFloat16                 float16one                                      = tcu::Float16(1.0f).bits();
6113         const deFloat16                 float16zero                                     = tcu::Float16(0.0f).bits();
6114         const tcu::Float16              zero                                            = tcu::Float16::zero(1);
6115         const deFloat16* const  outputAsFP16                            = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
6116         const deFloat16* const  input1AsFP16                            = reinterpret_cast<deFloat16* const>(&input1Bytes.front());
6117         const deFloat16* const  input2AsFP16                            = reinterpret_cast<deFloat16* const>(&input2Bytes.front());
6118         deUint32                                successfulRuns                          = denormModesCount;
6119         std::string                             results[denormModesCount];
6120         TestedLogicalFunction   testedLogicalFunction;
6121
6122         for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6123         {
6124                 const bool flushToZero = (denormMode == 1);
6125
6126                 for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deFloat16); ++idx)
6127                 {
6128                         const tcu::Float16      f1pre                   = tcu::Float16(input1AsFP16[idx]);
6129                         const tcu::Float16      f2pre                   = tcu::Float16(input2AsFP16[idx]);
6130                         const tcu::Float16      f1                              = (flushToZero && f1pre.isDenorm()) ? zero : f1pre;
6131                         const tcu::Float16      f2                              = (flushToZero && f2pre.isDenorm()) ? zero : f2pre;
6132                         deFloat16                       expectedOutput  = float16zero;
6133
6134                         if (onlyTestFunc)
6135                         {
6136                                 if (testedLogicalFunction(f1, f2))
6137                                         expectedOutput = float16one;
6138                         }
6139                         else
6140                         {
6141                                 const bool      f1nan   = f1.isNaN();
6142                                 const bool      f2nan   = f2.isNaN();
6143
6144                                 // Skip NaN floats if not supported by implementation
6145                                 if (!nanSupported && (f1nan || f2nan))
6146                                         continue;
6147
6148                                 if (unationModeAnd)
6149                                 {
6150                                         const bool      ordered         = !f1nan && !f2nan;
6151
6152                                         if (ordered && testedLogicalFunction(f1, f2))
6153                                                 expectedOutput = float16one;
6154                                 }
6155                                 else
6156                                 {
6157                                         const bool      unordered       = f1nan || f2nan;
6158
6159                                         if (unordered || testedLogicalFunction(f1, f2))
6160                                                 expectedOutput = float16one;
6161                                 }
6162                         }
6163
6164                         if (outputAsFP16[idx] != expectedOutput)
6165                         {
6166                                 std::ostringstream str;
6167
6168                                 str << "ERROR: Sub-case #" << idx
6169                                         << " flushToZero:" << flushToZero
6170                                         << std::hex
6171                                         << " failed, inputs: 0x" << f1.bits()
6172                                         << ";0x" << f2.bits()
6173                                         << " output: 0x" << outputAsFP16[idx]
6174                                         << " expected output: 0x" << expectedOutput;
6175
6176                                 results[denormMode] = str.str();
6177
6178                                 successfulRuns--;
6179
6180                                 break;
6181                         }
6182                 }
6183         }
6184
6185         if (successfulRuns == 0)
6186                 for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6187                         log << TestLog::Message << results[denormMode] << TestLog::EndMessage;
6188
6189         return successfulRuns > 0;
6190 }
6191
6192 } // anonymous
6193
6194 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
6195 {
6196         struct NameCodePair { string name, code; };
6197         RGBA                                                    defaultColors[4];
6198         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
6199         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
6200         map<string, string>                             fragments                               = passthruFragments();
6201         const NameCodePair                              tests[]                                 =
6202         {
6203                 {"unknown", "OpSource Unknown 321"},
6204                 {"essl", "OpSource ESSL 310"},
6205                 {"glsl", "OpSource GLSL 450"},
6206                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
6207                 {"opencl_c", "OpSource OpenCL_C 120"},
6208                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
6209                 {"file", opsourceGLSLWithFile},
6210                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
6211                 // Longest possible source string: SPIR-V limits instructions to 65535
6212                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
6213                 // contain 65530 UTF8 characters (one word each) plus one last word
6214                 // containing 3 ASCII characters and \0.
6215                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
6216         };
6217
6218         getDefaultColors(defaultColors);
6219         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6220         {
6221                 fragments["debug"] = tests[testNdx].code;
6222                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6223         }
6224
6225         return opSourceTests.release();
6226 }
6227
6228 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
6229 {
6230         struct NameCodePair { string name, code; };
6231         RGBA                                                            defaultColors[4];
6232         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
6233         map<string, string>                                     fragments                       = passthruFragments();
6234         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
6235         const NameCodePair                                      tests[]                         =
6236         {
6237                 {"empty", opsource + "OpSourceContinued \"\""},
6238                 {"short", opsource + "OpSourceContinued \"abcde\""},
6239                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
6240                 // Longest possible source string: SPIR-V limits instructions to 65535
6241                 // words, of which the first one is OpSourceContinued/length; the rest
6242                 // will contain 65533 UTF8 characters (one word each) plus one last word
6243                 // containing 3 ASCII characters and \0.
6244                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
6245         };
6246
6247         getDefaultColors(defaultColors);
6248         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6249         {
6250                 fragments["debug"] = tests[testNdx].code;
6251                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6252         }
6253
6254         return opSourceTests.release();
6255 }
6256 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
6257 {
6258         RGBA                                                             defaultColors[4];
6259         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
6260         map<string, string>                                      fragments;
6261         getDefaultColors(defaultColors);
6262         fragments["debug"]                      =
6263                 "%name = OpString \"name\"\n";
6264
6265         fragments["pre_main"]   =
6266                 "OpNoLine\n"
6267                 "OpNoLine\n"
6268                 "OpLine %name 1 1\n"
6269                 "OpNoLine\n"
6270                 "OpLine %name 1 1\n"
6271                 "OpLine %name 1 1\n"
6272                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6273                 "OpNoLine\n"
6274                 "OpLine %name 1 1\n"
6275                 "OpNoLine\n"
6276                 "OpLine %name 1 1\n"
6277                 "OpLine %name 1 1\n"
6278                 "%second_param1 = OpFunctionParameter %v4f32\n"
6279                 "OpNoLine\n"
6280                 "OpNoLine\n"
6281                 "%label_secondfunction = OpLabel\n"
6282                 "OpNoLine\n"
6283                 "OpReturnValue %second_param1\n"
6284                 "OpFunctionEnd\n"
6285                 "OpNoLine\n"
6286                 "OpNoLine\n";
6287
6288         fragments["testfun"]            =
6289                 // A %test_code function that returns its argument unchanged.
6290                 "OpNoLine\n"
6291                 "OpNoLine\n"
6292                 "OpLine %name 1 1\n"
6293                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6294                 "OpNoLine\n"
6295                 "%param1 = OpFunctionParameter %v4f32\n"
6296                 "OpNoLine\n"
6297                 "OpNoLine\n"
6298                 "%label_testfun = OpLabel\n"
6299                 "OpNoLine\n"
6300                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6301                 "OpReturnValue %val1\n"
6302                 "OpFunctionEnd\n"
6303                 "OpLine %name 1 1\n"
6304                 "OpNoLine\n";
6305
6306         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
6307
6308         return opLineTests.release();
6309 }
6310
6311 tcu::TestCaseGroup* createOpModuleProcessedTests(tcu::TestContext& testCtx)
6312 {
6313         RGBA                                                            defaultColors[4];
6314         de::MovePtr<tcu::TestCaseGroup>         opModuleProcessedTests                  (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "OpModuleProcessed instruction"));
6315         map<string, string>                                     fragments;
6316         std::vector<std::string>                        noExtensions;
6317         GraphicsResources                                       resources;
6318
6319         getDefaultColors(defaultColors);
6320         resources.verifyBinary = veryfiBinaryShader;
6321         resources.spirvVersion = SPIRV_VERSION_1_3;
6322
6323         fragments["moduleprocessed"]                                                    =
6324                 "OpModuleProcessed \"VULKAN CTS\"\n"
6325                 "OpModuleProcessed \"Negative values\"\n"
6326                 "OpModuleProcessed \"Date: 2017/09/21\"\n";
6327
6328         fragments["pre_main"]   =
6329                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6330                 "%second_param1 = OpFunctionParameter %v4f32\n"
6331                 "%label_secondfunction = OpLabel\n"
6332                 "OpReturnValue %second_param1\n"
6333                 "OpFunctionEnd\n";
6334
6335         fragments["testfun"]            =
6336                 // A %test_code function that returns its argument unchanged.
6337                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6338                 "%param1 = OpFunctionParameter %v4f32\n"
6339                 "%label_testfun = OpLabel\n"
6340                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6341                 "OpReturnValue %val1\n"
6342                 "OpFunctionEnd\n";
6343
6344         createTestsForAllStages ("opmoduleprocessed", defaultColors, defaultColors, fragments, resources, noExtensions, opModuleProcessedTests.get());
6345
6346         return opModuleProcessedTests.release();
6347 }
6348
6349
6350 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
6351 {
6352         RGBA                                                                                                    defaultColors[4];
6353         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
6354         map<string, string>                                                                             fragments;
6355         std::vector<std::pair<std::string, std::string> >               problemStrings;
6356
6357         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
6358         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
6359         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
6360         getDefaultColors(defaultColors);
6361
6362         fragments["debug"]                      =
6363                 "%other_name = OpString \"other_name\"\n";
6364
6365         fragments["pre_main"]   =
6366                 "OpLine %file_name 32 0\n"
6367                 "OpLine %file_name 32 32\n"
6368                 "OpLine %file_name 32 40\n"
6369                 "OpLine %other_name 32 40\n"
6370                 "OpLine %other_name 0 100\n"
6371                 "OpLine %other_name 0 4294967295\n"
6372                 "OpLine %other_name 4294967295 0\n"
6373                 "OpLine %other_name 32 40\n"
6374                 "OpLine %file_name 0 0\n"
6375                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6376                 "OpLine %file_name 1 0\n"
6377                 "%second_param1 = OpFunctionParameter %v4f32\n"
6378                 "OpLine %file_name 1 3\n"
6379                 "OpLine %file_name 1 2\n"
6380                 "%label_secondfunction = OpLabel\n"
6381                 "OpLine %file_name 0 2\n"
6382                 "OpReturnValue %second_param1\n"
6383                 "OpFunctionEnd\n"
6384                 "OpLine %file_name 0 2\n"
6385                 "OpLine %file_name 0 2\n";
6386
6387         fragments["testfun"]            =
6388                 // A %test_code function that returns its argument unchanged.
6389                 "OpLine %file_name 1 0\n"
6390                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6391                 "OpLine %file_name 16 330\n"
6392                 "%param1 = OpFunctionParameter %v4f32\n"
6393                 "OpLine %file_name 14 442\n"
6394                 "%label_testfun = OpLabel\n"
6395                 "OpLine %file_name 11 1024\n"
6396                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6397                 "OpLine %file_name 2 97\n"
6398                 "OpReturnValue %val1\n"
6399                 "OpFunctionEnd\n"
6400                 "OpLine %file_name 5 32\n";
6401
6402         for (size_t i = 0; i < problemStrings.size(); ++i)
6403         {
6404                 map<string, string> testFragments = fragments;
6405                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
6406                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
6407         }
6408
6409         return opLineTests.release();
6410 }
6411
6412 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
6413 {
6414         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
6415         RGBA                                                    colors[4];
6416
6417
6418         const char                                              functionStart[] =
6419                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6420                 "%param1 = OpFunctionParameter %v4f32\n"
6421                 "%lbl    = OpLabel\n";
6422
6423         const char                                              functionEnd[]   =
6424                 "OpReturnValue %transformed_param\n"
6425                 "OpFunctionEnd\n";
6426
6427         struct NameConstantsCode
6428         {
6429                 string name;
6430                 string constants;
6431                 string code;
6432         };
6433
6434         NameConstantsCode tests[] =
6435         {
6436                 {
6437                         "vec4",
6438                         "%cnull = OpConstantNull %v4f32\n",
6439                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
6440                 },
6441                 {
6442                         "float",
6443                         "%cnull = OpConstantNull %f32\n",
6444                         "%vp = OpVariable %fp_v4f32 Function\n"
6445                         "%v  = OpLoad %v4f32 %vp\n"
6446                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
6447                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
6448                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
6449                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
6450                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
6451                 },
6452                 {
6453                         "bool",
6454                         "%cnull             = OpConstantNull %bool\n",
6455                         "%v                 = OpVariable %fp_v4f32 Function\n"
6456                         "                     OpStore %v %param1\n"
6457                         "                     OpSelectionMerge %false_label None\n"
6458                         "                     OpBranchConditional %cnull %true_label %false_label\n"
6459                         "%true_label        = OpLabel\n"
6460                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
6461                         "                     OpBranch %false_label\n"
6462                         "%false_label       = OpLabel\n"
6463                         "%transformed_param = OpLoad %v4f32 %v\n"
6464                 },
6465                 {
6466                         "i32",
6467                         "%cnull             = OpConstantNull %i32\n",
6468                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
6469                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
6470                         "                     OpSelectionMerge %false_label None\n"
6471                         "                     OpBranchConditional %b %true_label %false_label\n"
6472                         "%true_label        = OpLabel\n"
6473                         "                     OpStore %v %param1\n"
6474                         "                     OpBranch %false_label\n"
6475                         "%false_label       = OpLabel\n"
6476                         "%transformed_param = OpLoad %v4f32 %v\n"
6477                 },
6478                 {
6479                         "struct",
6480                         "%stype             = OpTypeStruct %f32 %v4f32\n"
6481                         "%fp_stype          = OpTypePointer Function %stype\n"
6482                         "%cnull             = OpConstantNull %stype\n",
6483                         "%v                 = OpVariable %fp_stype Function %cnull\n"
6484                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
6485                         "%f_val             = OpLoad %v4f32 %f\n"
6486                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
6487                 },
6488                 {
6489                         "array",
6490                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
6491                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
6492                         "%cnull             = OpConstantNull %a4_v4f32\n",
6493                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
6494                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6495                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
6496                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
6497                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
6498                         "%f_val             = OpLoad %v4f32 %f\n"
6499                         "%f1_val            = OpLoad %v4f32 %f1\n"
6500                         "%f2_val            = OpLoad %v4f32 %f2\n"
6501                         "%f3_val            = OpLoad %v4f32 %f3\n"
6502                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
6503                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
6504                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
6505                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
6506                 },
6507                 {
6508                         "matrix",
6509                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
6510                         "%cnull             = OpConstantNull %mat4x4_f32\n",
6511                         // Our null matrix * any vector should result in a zero vector.
6512                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
6513                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
6514                 }
6515         };
6516
6517         getHalfColorsFullAlpha(colors);
6518
6519         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6520         {
6521                 map<string, string> fragments;
6522                 fragments["pre_main"] = tests[testNdx].constants;
6523                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6524                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
6525         }
6526         return opConstantNullTests.release();
6527 }
6528 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
6529 {
6530         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
6531         RGBA                                                    inputColors[4];
6532         RGBA                                                    outputColors[4];
6533
6534
6535         const char                                              functionStart[]  =
6536                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6537                 "%param1 = OpFunctionParameter %v4f32\n"
6538                 "%lbl    = OpLabel\n";
6539
6540         const char                                              functionEnd[]           =
6541                 "OpReturnValue %transformed_param\n"
6542                 "OpFunctionEnd\n";
6543
6544         struct NameConstantsCode
6545         {
6546                 string name;
6547                 string constants;
6548                 string code;
6549         };
6550
6551         NameConstantsCode tests[] =
6552         {
6553                 {
6554                         "vec4",
6555
6556                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
6557                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
6558                 },
6559                 {
6560                         "struct",
6561
6562                         "%stype             = OpTypeStruct %v4f32 %f32\n"
6563                         "%fp_stype          = OpTypePointer Function %stype\n"
6564                         "%f32_n_1           = OpConstant %f32 -1.0\n"
6565                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
6566                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
6567                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
6568
6569                         "%v                 = OpVariable %fp_stype Function %cval\n"
6570                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6571                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
6572                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
6573                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
6574                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
6575                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
6576                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
6577                 },
6578                 {
6579                         // [1|0|0|0.5] [x] = x + 0.5
6580                         // [0|1|0|0.5] [y] = y + 0.5
6581                         // [0|0|1|0.5] [z] = z + 0.5
6582                         // [0|0|0|1  ] [1] = 1
6583                         "matrix",
6584
6585                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
6586                         "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
6587                         "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
6588                         "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
6589                         "%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"
6590                         "%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",
6591
6592                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
6593                 },
6594                 {
6595                         "array",
6596
6597                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6598                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6599                         "%f32_n_1             = OpConstant %f32 -1.0\n"
6600                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
6601                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
6602
6603                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
6604                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
6605                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
6606                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
6607                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
6608                         "%f_val               = OpLoad %f32 %f\n"
6609                         "%f1_val              = OpLoad %f32 %f1\n"
6610                         "%f2_val              = OpLoad %f32 %f2\n"
6611                         "%f3_val              = OpLoad %f32 %f3\n"
6612                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
6613                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
6614                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
6615                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
6616                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6617                 },
6618                 {
6619                         //
6620                         // [
6621                         //   {
6622                         //      0.0,
6623                         //      [ 1.0, 1.0, 1.0, 1.0]
6624                         //   },
6625                         //   {
6626                         //      1.0,
6627                         //      [ 0.0, 0.5, 0.0, 0.0]
6628                         //   }, //     ^^^
6629                         //   {
6630                         //      0.0,
6631                         //      [ 1.0, 1.0, 1.0, 1.0]
6632                         //   }
6633                         // ]
6634                         "array_of_struct_of_array",
6635
6636                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6637                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6638                         "%stype               = OpTypeStruct %f32 %a4f32\n"
6639                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
6640                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
6641                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
6642                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6643                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
6644                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
6645                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
6646
6647                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
6648                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
6649                         "%f_l                 = OpLoad %f32 %f\n"
6650                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
6651                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6652                 }
6653         };
6654
6655         getHalfColorsFullAlpha(inputColors);
6656         outputColors[0] = RGBA(255, 255, 255, 255);
6657         outputColors[1] = RGBA(255, 127, 127, 255);
6658         outputColors[2] = RGBA(127, 255, 127, 255);
6659         outputColors[3] = RGBA(127, 127, 255, 255);
6660
6661         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6662         {
6663                 map<string, string> fragments;
6664                 fragments["pre_main"] = tests[testNdx].constants;
6665                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6666                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
6667         }
6668         return opConstantCompositeTests.release();
6669 }
6670
6671 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
6672 {
6673         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
6674         RGBA                                                    inputColors[4];
6675         RGBA                                                    outputColors[4];
6676         map<string, string>                             fragments;
6677
6678         // vec4 test_code(vec4 param) {
6679         //   vec4 result = param;
6680         //   for (int i = 0; i < 4; ++i) {
6681         //     if (i == 0) result[i] = 0.;
6682         //     else        result[i] = 1. - result[i];
6683         //   }
6684         //   return result;
6685         // }
6686         const char                                              function[]                      =
6687                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6688                 "%param1    = OpFunctionParameter %v4f32\n"
6689                 "%lbl       = OpLabel\n"
6690                 "%iptr      = OpVariable %fp_i32 Function\n"
6691                 "%result    = OpVariable %fp_v4f32 Function\n"
6692                 "             OpStore %iptr %c_i32_0\n"
6693                 "             OpStore %result %param1\n"
6694                 "             OpBranch %loop\n"
6695
6696                 // Loop entry block.
6697                 "%loop      = OpLabel\n"
6698                 "%ival      = OpLoad %i32 %iptr\n"
6699                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6700                 "             OpLoopMerge %exit %if_entry None\n"
6701                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
6702
6703                 // Merge block for loop.
6704                 "%exit      = OpLabel\n"
6705                 "%ret       = OpLoad %v4f32 %result\n"
6706                 "             OpReturnValue %ret\n"
6707
6708                 // If-statement entry block.
6709                 "%if_entry  = OpLabel\n"
6710                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6711                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
6712                 "             OpSelectionMerge %if_exit None\n"
6713                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
6714
6715                 // False branch for if-statement.
6716                 "%if_false  = OpLabel\n"
6717                 "%val       = OpLoad %f32 %loc\n"
6718                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
6719                 "             OpStore %loc %sub\n"
6720                 "             OpBranch %if_exit\n"
6721
6722                 // Merge block for if-statement.
6723                 "%if_exit   = OpLabel\n"
6724                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6725                 "             OpStore %iptr %ival_next\n"
6726                 "             OpBranch %loop\n"
6727
6728                 // True branch for if-statement.
6729                 "%if_true   = OpLabel\n"
6730                 "             OpStore %loc %c_f32_0\n"
6731                 "             OpBranch %if_exit\n"
6732
6733                 "             OpFunctionEnd\n";
6734
6735         fragments["testfun"]    = function;
6736
6737         inputColors[0]                  = RGBA(127, 127, 127, 0);
6738         inputColors[1]                  = RGBA(127, 0,   0,   0);
6739         inputColors[2]                  = RGBA(0,   127, 0,   0);
6740         inputColors[3]                  = RGBA(0,   0,   127, 0);
6741
6742         outputColors[0]                 = RGBA(0, 128, 128, 255);
6743         outputColors[1]                 = RGBA(0, 255, 255, 255);
6744         outputColors[2]                 = RGBA(0, 128, 255, 255);
6745         outputColors[3]                 = RGBA(0, 255, 128, 255);
6746
6747         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6748
6749         return group.release();
6750 }
6751
6752 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
6753 {
6754         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
6755         RGBA                                                    inputColors[4];
6756         RGBA                                                    outputColors[4];
6757         map<string, string>                             fragments;
6758
6759         const char                                              typesAndConstants[]     =
6760                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6761                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6762                 "%c_f32_p6  = OpConstant %f32 0.6\n"
6763                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6764
6765         // vec4 test_code(vec4 param) {
6766         //   vec4 result = param;
6767         //   for (int i = 0; i < 4; ++i) {
6768         //     switch (i) {
6769         //       case 0: result[i] += .2; break;
6770         //       case 1: result[i] += .6; break;
6771         //       case 2: result[i] += .4; break;
6772         //       case 3: result[i] += .8; break;
6773         //       default: break; // unreachable
6774         //     }
6775         //   }
6776         //   return result;
6777         // }
6778         const char                                              function[]                      =
6779                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6780                 "%param1    = OpFunctionParameter %v4f32\n"
6781                 "%lbl       = OpLabel\n"
6782                 "%iptr      = OpVariable %fp_i32 Function\n"
6783                 "%result    = OpVariable %fp_v4f32 Function\n"
6784                 "             OpStore %iptr %c_i32_0\n"
6785                 "             OpStore %result %param1\n"
6786                 "             OpBranch %loop\n"
6787
6788                 // Loop entry block.
6789                 "%loop      = OpLabel\n"
6790                 "%ival      = OpLoad %i32 %iptr\n"
6791                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6792                 "             OpLoopMerge %exit %switch_exit None\n"
6793                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
6794
6795                 // Merge block for loop.
6796                 "%exit      = OpLabel\n"
6797                 "%ret       = OpLoad %v4f32 %result\n"
6798                 "             OpReturnValue %ret\n"
6799
6800                 // Switch-statement entry block.
6801                 "%switch_entry   = OpLabel\n"
6802                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
6803                 "%val            = OpLoad %f32 %loc\n"
6804                 "                  OpSelectionMerge %switch_exit None\n"
6805                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6806
6807                 "%case2          = OpLabel\n"
6808                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
6809                 "                  OpStore %loc %addp4\n"
6810                 "                  OpBranch %switch_exit\n"
6811
6812                 "%switch_default = OpLabel\n"
6813                 "                  OpUnreachable\n"
6814
6815                 "%case3          = OpLabel\n"
6816                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
6817                 "                  OpStore %loc %addp8\n"
6818                 "                  OpBranch %switch_exit\n"
6819
6820                 "%case0          = OpLabel\n"
6821                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
6822                 "                  OpStore %loc %addp2\n"
6823                 "                  OpBranch %switch_exit\n"
6824
6825                 // Merge block for switch-statement.
6826                 "%switch_exit    = OpLabel\n"
6827                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
6828                 "                  OpStore %iptr %ival_next\n"
6829                 "                  OpBranch %loop\n"
6830
6831                 "%case1          = OpLabel\n"
6832                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
6833                 "                  OpStore %loc %addp6\n"
6834                 "                  OpBranch %switch_exit\n"
6835
6836                 "                  OpFunctionEnd\n";
6837
6838         fragments["pre_main"]   = typesAndConstants;
6839         fragments["testfun"]    = function;
6840
6841         inputColors[0]                  = RGBA(127, 27,  127, 51);
6842         inputColors[1]                  = RGBA(127, 0,   0,   51);
6843         inputColors[2]                  = RGBA(0,   27,  0,   51);
6844         inputColors[3]                  = RGBA(0,   0,   127, 51);
6845
6846         outputColors[0]                 = RGBA(178, 180, 229, 255);
6847         outputColors[1]                 = RGBA(178, 153, 102, 255);
6848         outputColors[2]                 = RGBA(51,  180, 102, 255);
6849         outputColors[3]                 = RGBA(51,  153, 229, 255);
6850
6851         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6852
6853         return group.release();
6854 }
6855
6856 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
6857 {
6858         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
6859         RGBA                                                    inputColors[4];
6860         RGBA                                                    outputColors[4];
6861         map<string, string>                             fragments;
6862
6863         const char                                              decorations[]           =
6864                 "OpDecorate %array_group         ArrayStride 4\n"
6865                 "OpDecorate %struct_member_group Offset 0\n"
6866                 "%array_group         = OpDecorationGroup\n"
6867                 "%struct_member_group = OpDecorationGroup\n"
6868
6869                 "OpDecorate %group1 RelaxedPrecision\n"
6870                 "OpDecorate %group3 RelaxedPrecision\n"
6871                 "OpDecorate %group3 Invariant\n"
6872                 "OpDecorate %group3 Restrict\n"
6873                 "%group0 = OpDecorationGroup\n"
6874                 "%group1 = OpDecorationGroup\n"
6875                 "%group3 = OpDecorationGroup\n";
6876
6877         const char                                              typesAndConstants[]     =
6878                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
6879                 "%struct1   = OpTypeStruct %a3f32\n"
6880                 "%struct2   = OpTypeStruct %a3f32\n"
6881                 "%fp_struct1 = OpTypePointer Function %struct1\n"
6882                 "%fp_struct2 = OpTypePointer Function %struct2\n"
6883                 "%c_f32_2    = OpConstant %f32 2.\n"
6884                 "%c_f32_n2   = OpConstant %f32 -2.\n"
6885
6886                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
6887                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
6888                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
6889                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
6890
6891         const char                                              function[]                      =
6892                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6893                 "%param     = OpFunctionParameter %v4f32\n"
6894                 "%entry     = OpLabel\n"
6895                 "%result    = OpVariable %fp_v4f32 Function\n"
6896                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
6897                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
6898                 "             OpStore %result %param\n"
6899                 "             OpStore %v_struct1 %c_struct1\n"
6900                 "             OpStore %v_struct2 %c_struct2\n"
6901                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
6902                 "%val1      = OpLoad %f32 %ptr1\n"
6903                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
6904                 "%val2      = OpLoad %f32 %ptr2\n"
6905                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
6906                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
6907                 "%val       = OpLoad %f32 %ptr\n"
6908                 "%addresult = OpFAdd %f32 %addvalues %val\n"
6909                 "             OpStore %ptr %addresult\n"
6910                 "%ret       = OpLoad %v4f32 %result\n"
6911                 "             OpReturnValue %ret\n"
6912                 "             OpFunctionEnd\n";
6913
6914         struct CaseNameDecoration
6915         {
6916                 string name;
6917                 string decoration;
6918         };
6919
6920         CaseNameDecoration tests[] =
6921         {
6922                 {
6923                         "same_decoration_group_on_multiple_types",
6924                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
6925                 },
6926                 {
6927                         "empty_decoration_group",
6928                         "OpGroupDecorate %group0      %a3f32\n"
6929                         "OpGroupDecorate %group0      %result\n"
6930                 },
6931                 {
6932                         "one_element_decoration_group",
6933                         "OpGroupDecorate %array_group %a3f32\n"
6934                 },
6935                 {
6936                         "multiple_elements_decoration_group",
6937                         "OpGroupDecorate %group3      %v_struct1\n"
6938                 },
6939                 {
6940                         "multiple_decoration_groups_on_same_variable",
6941                         "OpGroupDecorate %group0      %v_struct2\n"
6942                         "OpGroupDecorate %group1      %v_struct2\n"
6943                         "OpGroupDecorate %group3      %v_struct2\n"
6944                 },
6945                 {
6946                         "same_decoration_group_multiple_times",
6947                         "OpGroupDecorate %group1      %addvalues\n"
6948                         "OpGroupDecorate %group1      %addvalues\n"
6949                         "OpGroupDecorate %group1      %addvalues\n"
6950                 },
6951
6952         };
6953
6954         getHalfColorsFullAlpha(inputColors);
6955         getHalfColorsFullAlpha(outputColors);
6956
6957         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
6958         {
6959                 fragments["decoration"] = decorations + tests[idx].decoration;
6960                 fragments["pre_main"]   = typesAndConstants;
6961                 fragments["testfun"]    = function;
6962
6963                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
6964         }
6965
6966         return group.release();
6967 }
6968
6969 struct SpecConstantTwoIntGraphicsCase
6970 {
6971         const char*             caseName;
6972         const char*             scDefinition0;
6973         const char*             scDefinition1;
6974         const char*             scResultType;
6975         const char*             scOperation;
6976         deInt32                 scActualValue0;
6977         deInt32                 scActualValue1;
6978         const char*             resultOperation;
6979         RGBA                    expectedColors[4];
6980         deInt32                 scActualValueLength;
6981
6982                                         SpecConstantTwoIntGraphicsCase (const char*             name,
6983                                                                                                         const char*             definition0,
6984                                                                                                         const char*             definition1,
6985                                                                                                         const char*             resultType,
6986                                                                                                         const char*             operation,
6987                                                                                                         const deInt32   value0,
6988                                                                                                         const deInt32   value1,
6989                                                                                                         const char*             resultOp,
6990                                                                                                         const RGBA              (&output)[4],
6991                                                                                                         const deInt32   valueLength = sizeof(deInt32))
6992                                                 : caseName                              (name)
6993                                                 , scDefinition0                 (definition0)
6994                                                 , scDefinition1                 (definition1)
6995                                                 , scResultType                  (resultType)
6996                                                 , scOperation                   (operation)
6997                                                 , scActualValue0                (value0)
6998                                                 , scActualValue1                (value1)
6999                                                 , resultOperation               (resultOp)
7000                                                 , scActualValueLength   (valueLength)
7001         {
7002                 expectedColors[0] = output[0];
7003                 expectedColors[1] = output[1];
7004                 expectedColors[2] = output[2];
7005                 expectedColors[3] = output[3];
7006         }
7007 };
7008
7009 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
7010 {
7011         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
7012         vector<SpecConstantTwoIntGraphicsCase>  cases;
7013         RGBA                                                    inputColors[4];
7014         RGBA                                                    outputColors0[4];
7015         RGBA                                                    outputColors1[4];
7016         RGBA                                                    outputColors2[4];
7017
7018         const deInt32                                   m1AsFloat16                     = 0xbc00; // -1(fp16) == 1 01111 0000000000 == 1011 1100 0000 0000
7019
7020         const char      decorations1[]                  =
7021                 "OpDecorate %sc_0  SpecId 0\n"
7022                 "OpDecorate %sc_1  SpecId 1\n";
7023
7024         const char      typesAndConstants1[]    =
7025                 "${OPTYPE_DEFINITIONS:opt}"
7026                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
7027                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
7028                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
7029
7030         const char      function1[]                             =
7031                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7032                 "%param     = OpFunctionParameter %v4f32\n"
7033                 "%label     = OpLabel\n"
7034                 "%result    = OpVariable %fp_v4f32 Function\n"
7035                 "${TYPE_CONVERT:opt}"
7036                 "             OpStore %result %param\n"
7037                 "%gen       = ${GEN_RESULT}\n"
7038                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
7039                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
7040                 "%val       = OpLoad %f32 %loc\n"
7041                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7042                 "             OpStore %loc %add\n"
7043                 "%ret       = OpLoad %v4f32 %result\n"
7044                 "             OpReturnValue %ret\n"
7045                 "             OpFunctionEnd\n";
7046
7047         inputColors[0] = RGBA(127, 127, 127, 255);
7048         inputColors[1] = RGBA(127, 0,   0,   255);
7049         inputColors[2] = RGBA(0,   127, 0,   255);
7050         inputColors[3] = RGBA(0,   0,   127, 255);
7051
7052         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
7053         outputColors0[0] = RGBA(255, 127, 127, 255);
7054         outputColors0[1] = RGBA(255, 0,   0,   255);
7055         outputColors0[2] = RGBA(128, 127, 0,   255);
7056         outputColors0[3] = RGBA(128, 0,   127, 255);
7057
7058         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
7059         outputColors1[0] = RGBA(127, 255, 127, 255);
7060         outputColors1[1] = RGBA(127, 128, 0,   255);
7061         outputColors1[2] = RGBA(0,   255, 0,   255);
7062         outputColors1[3] = RGBA(0,   128, 127, 255);
7063
7064         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
7065         outputColors2[0] = RGBA(127, 127, 255, 255);
7066         outputColors2[1] = RGBA(127, 0,   128, 255);
7067         outputColors2[2] = RGBA(0,   127, 128, 255);
7068         outputColors2[3] = RGBA(0,   0,   255, 255);
7069
7070         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
7071         const char addZeroToSc32[]              = "OpIAdd %i32 %c_i32_0 %sc_op32";
7072         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
7073         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
7074
7075         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
7076         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
7077         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
7078         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
7079         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
7080         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7081         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7082         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
7083         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
7084         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
7085         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
7086         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
7087         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
7088         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
7089         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
7090         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
7091         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7092         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
7093         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
7094         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
7095         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7096         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
7097         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
7098         cases.push_back(SpecConstantTwoIntGraphicsCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                             42,             24,             selectTrueUsingSc,      outputColors2));
7099         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7100         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7101         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7102         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7103         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
7104         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
7105         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
7106         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
7107         cases.push_back(SpecConstantTwoIntGraphicsCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                                   -1,             0,              addZeroToSc32,          outputColors0));
7108         // -1082130432 stored as 32-bit two's complement is the binary representation of -1 as IEEE-754 Float
7109         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                                   -1082130432, 0, addZeroToSc32,          outputColors0));
7110         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                                   m1AsFloat16, 0, addZeroToSc32,          outputColors0, sizeof(deFloat16)));
7111         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
7112
7113         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
7114         {
7115                 map<string, string>                     specializations;
7116                 map<string, string>                     fragments;
7117                 SpecConstants                           specConstants;
7118                 PushConstants                           noPushConstants;
7119                 GraphicsResources                       noResources;
7120                 GraphicsInterfaces                      noInterfaces;
7121                 vector<string>                          extensions;
7122                 VulkanFeatures                          requiredFeatures;
7123
7124                 // Special SPIR-V code for SConvert-case
7125                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
7126                 {
7127                         requiredFeatures.coreFeatures.shaderInt16 = VK_TRUE;
7128                         fragments["capability"]                                 = "OpCapability Int16\n";                                       // Adds 16-bit integer capability
7129                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                            // Adds 16-bit integer type
7130                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpSConvert %i32 %sc_op\n";        // Converts 16-bit integer to 32-bit integer
7131                 }
7132
7133                 // Special SPIR-V code for FConvert-case
7134                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
7135                 {
7136                         requiredFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
7137                         fragments["capability"]                                 = "OpCapability Float64\n";                                     // Adds 64-bit float capability
7138                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                            // Adds 64-bit float type
7139                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 64-bit float to 32-bit integer
7140                 }
7141
7142                 // Special SPIR-V code for FConvert-case for 16-bit floats
7143                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
7144                 {
7145                         extensions.push_back("VK_KHR_shader_float16_int8");
7146                         requiredFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
7147                         fragments["capability"]                                 = "OpCapability Float16\n";                                     // Adds 16-bit float capability
7148                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                            // Adds 16-bit float type
7149                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 16-bit float to 32-bit integer
7150                 }
7151
7152                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
7153                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
7154                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
7155                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
7156                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
7157
7158                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
7159                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
7160                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
7161
7162                 specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
7163                 specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
7164
7165                 createTestsForAllStages(
7166                         cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants,
7167                         noPushConstants, noResources, noInterfaces, extensions, requiredFeatures, group.get());
7168         }
7169
7170         const char      decorations2[]                  =
7171                 "OpDecorate %sc_0  SpecId 0\n"
7172                 "OpDecorate %sc_1  SpecId 1\n"
7173                 "OpDecorate %sc_2  SpecId 2\n";
7174
7175         const char      typesAndConstants2[]    =
7176                 "%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
7177                 "%vec3_undef  = OpUndef %v3i32\n"
7178
7179                 "%sc_0        = OpSpecConstant %i32 0\n"
7180                 "%sc_1        = OpSpecConstant %i32 0\n"
7181                 "%sc_2        = OpSpecConstant %i32 0\n"
7182                 "%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0      0\n"                                                 // (sc_0, 0,    0)
7183                 "%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0      1\n"                                                 // (0,    sc_1, 0)
7184                 "%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0      2\n"                                                 // (0,    0,    sc_2)
7185                 "%sc_vec3_0_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
7186                 "%sc_vec3_1_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
7187                 "%sc_vec3_2_s = OpSpecConstantOp %v3i32 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
7188                 "%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
7189                 "%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
7190                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
7191                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
7192                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
7193                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
7194                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";                                                             // (sc_2 - sc_0) * sc_1
7195
7196         const char      function2[]                             =
7197                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7198                 "%param     = OpFunctionParameter %v4f32\n"
7199                 "%label     = OpLabel\n"
7200                 "%result    = OpVariable %fp_v4f32 Function\n"
7201                 "             OpStore %result %param\n"
7202                 "%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
7203                 "%val       = OpLoad %f32 %loc\n"
7204                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7205                 "             OpStore %loc %add\n"
7206                 "%ret       = OpLoad %v4f32 %result\n"
7207                 "             OpReturnValue %ret\n"
7208                 "             OpFunctionEnd\n";
7209
7210         map<string, string>     fragments;
7211         SpecConstants           specConstants;
7212
7213         fragments["decoration"] = decorations2;
7214         fragments["pre_main"]   = typesAndConstants2;
7215         fragments["testfun"]    = function2;
7216
7217         specConstants.append<deInt32>(56789);
7218         specConstants.append<deInt32>(-2);
7219         specConstants.append<deInt32>(56788);
7220
7221         createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
7222
7223         return group.release();
7224 }
7225
7226 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
7227 {
7228         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
7229         RGBA                                                    inputColors[4];
7230         RGBA                                                    outputColors1[4];
7231         RGBA                                                    outputColors2[4];
7232         RGBA                                                    outputColors3[4];
7233         RGBA                                                    outputColors4[4];
7234         map<string, string>                             fragments1;
7235         map<string, string>                             fragments2;
7236         map<string, string>                             fragments3;
7237         map<string, string>                             fragments4;
7238         std::vector<std::string>                extensions4;
7239         GraphicsResources                               resources4;
7240         VulkanFeatures                                  vulkanFeatures4;
7241
7242         const char      typesAndConstants1[]    =
7243                 "%c_f32_p2  = OpConstant %f32 0.2\n"
7244                 "%c_f32_p4  = OpConstant %f32 0.4\n"
7245                 "%c_f32_p5  = OpConstant %f32 0.5\n"
7246                 "%c_f32_p8  = OpConstant %f32 0.8\n";
7247
7248         // vec4 test_code(vec4 param) {
7249         //   vec4 result = param;
7250         //   for (int i = 0; i < 4; ++i) {
7251         //     float operand;
7252         //     switch (i) {
7253         //       case 0: operand = .2; break;
7254         //       case 1: operand = .5; break;
7255         //       case 2: operand = .4; break;
7256         //       case 3: operand = .0; break;
7257         //       default: break; // unreachable
7258         //     }
7259         //     result[i] += operand;
7260         //   }
7261         //   return result;
7262         // }
7263         const char      function1[]                             =
7264                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7265                 "%param1    = OpFunctionParameter %v4f32\n"
7266                 "%lbl       = OpLabel\n"
7267                 "%iptr      = OpVariable %fp_i32 Function\n"
7268                 "%result    = OpVariable %fp_v4f32 Function\n"
7269                 "             OpStore %iptr %c_i32_0\n"
7270                 "             OpStore %result %param1\n"
7271                 "             OpBranch %loop\n"
7272
7273                 "%loop      = OpLabel\n"
7274                 "%ival      = OpLoad %i32 %iptr\n"
7275                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
7276                 "             OpLoopMerge %exit %phi None\n"
7277                 "             OpBranchConditional %lt_4 %entry %exit\n"
7278
7279                 "%entry     = OpLabel\n"
7280                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
7281                 "%val       = OpLoad %f32 %loc\n"
7282                 "             OpSelectionMerge %phi None\n"
7283                 "             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
7284
7285                 "%case0     = OpLabel\n"
7286                 "             OpBranch %phi\n"
7287                 "%case1     = OpLabel\n"
7288                 "             OpBranch %phi\n"
7289                 "%case2     = OpLabel\n"
7290                 "             OpBranch %phi\n"
7291                 "%case3     = OpLabel\n"
7292                 "             OpBranch %phi\n"
7293
7294                 "%default   = OpLabel\n"
7295                 "             OpUnreachable\n"
7296
7297                 "%phi       = OpLabel\n"
7298                 "%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
7299                 "%add       = OpFAdd %f32 %val %operand\n"
7300                 "             OpStore %loc %add\n"
7301                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
7302                 "             OpStore %iptr %ival_next\n"
7303                 "             OpBranch %loop\n"
7304
7305                 "%exit      = OpLabel\n"
7306                 "%ret       = OpLoad %v4f32 %result\n"
7307                 "             OpReturnValue %ret\n"
7308
7309                 "             OpFunctionEnd\n";
7310
7311         fragments1["pre_main"]  = typesAndConstants1;
7312         fragments1["testfun"]   = function1;
7313
7314         getHalfColorsFullAlpha(inputColors);
7315
7316         outputColors1[0]                = RGBA(178, 255, 229, 255);
7317         outputColors1[1]                = RGBA(178, 127, 102, 255);
7318         outputColors1[2]                = RGBA(51,  255, 102, 255);
7319         outputColors1[3]                = RGBA(51,  127, 229, 255);
7320
7321         createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
7322
7323         const char      typesAndConstants2[]    =
7324                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7325
7326         // Add .4 to the second element of the given parameter.
7327         const char      function2[]                             =
7328                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7329                 "%param     = OpFunctionParameter %v4f32\n"
7330                 "%entry     = OpLabel\n"
7331                 "%result    = OpVariable %fp_v4f32 Function\n"
7332                 "             OpStore %result %param\n"
7333                 "%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7334                 "%val       = OpLoad %f32 %loc\n"
7335                 "             OpBranch %phi\n"
7336
7337                 "%phi        = OpLabel\n"
7338                 "%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
7339                 "%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
7340                 "%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
7341                 "%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
7342                 "%still_loop = OpSLessThan %bool %step %c_i32_2\n"
7343                 "              OpLoopMerge %exit %phi None\n"
7344                 "              OpBranchConditional %still_loop %phi %exit\n"
7345
7346                 "%exit       = OpLabel\n"
7347                 "              OpStore %loc %accum\n"
7348                 "%ret        = OpLoad %v4f32 %result\n"
7349                 "              OpReturnValue %ret\n"
7350
7351                 "              OpFunctionEnd\n";
7352
7353         fragments2["pre_main"]  = typesAndConstants2;
7354         fragments2["testfun"]   = function2;
7355
7356         outputColors2[0]                        = RGBA(127, 229, 127, 255);
7357         outputColors2[1]                        = RGBA(127, 102, 0,   255);
7358         outputColors2[2]                        = RGBA(0,   229, 0,   255);
7359         outputColors2[3]                        = RGBA(0,   102, 127, 255);
7360
7361         createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
7362
7363         const char      typesAndConstants3[]    =
7364                 "%true      = OpConstantTrue %bool\n"
7365                 "%false     = OpConstantFalse %bool\n"
7366                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7367
7368         // Swap the second and the third element of the given parameter.
7369         const char      function3[]                             =
7370                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7371                 "%param     = OpFunctionParameter %v4f32\n"
7372                 "%entry     = OpLabel\n"
7373                 "%result    = OpVariable %fp_v4f32 Function\n"
7374                 "             OpStore %result %param\n"
7375                 "%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
7376                 "%a_init    = OpLoad %f32 %a_loc\n"
7377                 "%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
7378                 "%b_init    = OpLoad %f32 %b_loc\n"
7379                 "             OpBranch %phi\n"
7380
7381                 "%phi        = OpLabel\n"
7382                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7383                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
7384                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
7385                 "              OpLoopMerge %exit %phi None\n"
7386                 "              OpBranchConditional %still_loop %phi %exit\n"
7387
7388                 "%exit       = OpLabel\n"
7389                 "              OpStore %a_loc %a_next\n"
7390                 "              OpStore %b_loc %b_next\n"
7391                 "%ret        = OpLoad %v4f32 %result\n"
7392                 "              OpReturnValue %ret\n"
7393
7394                 "              OpFunctionEnd\n";
7395
7396         fragments3["pre_main"]  = typesAndConstants3;
7397         fragments3["testfun"]   = function3;
7398
7399         outputColors3[0]                        = RGBA(127, 127, 127, 255);
7400         outputColors3[1]                        = RGBA(127, 0,   0,   255);
7401         outputColors3[2]                        = RGBA(0,   0,   127, 255);
7402         outputColors3[3]                        = RGBA(0,   127, 0,   255);
7403
7404         createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
7405
7406         const char      typesAndConstants4[]    =
7407                 "%f16        = OpTypeFloat 16\n"
7408                 "%v4f16      = OpTypeVector %f16 4\n"
7409                 "%fp_f16     = OpTypePointer Function %f16\n"
7410                 "%fp_v4f16   = OpTypePointer Function %v4f16\n"
7411                 "%true       = OpConstantTrue %bool\n"
7412                 "%false      = OpConstantFalse %bool\n"
7413                 "%c_f32_p2   = OpConstant %f32 0.2\n";
7414
7415         // Swap the second and the third element of the given parameter.
7416         const char      function4[]                             =
7417                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7418                 "%param      = OpFunctionParameter %v4f32\n"
7419                 "%entry      = OpLabel\n"
7420                 "%result     = OpVariable %fp_v4f16 Function\n"
7421                 "%param16    = OpFConvert %v4f16 %param\n"
7422                 "              OpStore %result %param16\n"
7423                 "%a_loc      = OpAccessChain %fp_f16 %result %c_i32_1\n"
7424                 "%a_init     = OpLoad %f16 %a_loc\n"
7425                 "%b_loc      = OpAccessChain %fp_f16 %result %c_i32_2\n"
7426                 "%b_init     = OpLoad %f16 %b_loc\n"
7427                 "              OpBranch %phi\n"
7428
7429                 "%phi        = OpLabel\n"
7430                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7431                 "%a_next     = OpPhi %f16  %a_init %entry %b_next %phi\n"
7432                 "%b_next     = OpPhi %f16  %b_init %entry %a_next %phi\n"
7433                 "              OpLoopMerge %exit %phi None\n"
7434                 "              OpBranchConditional %still_loop %phi %exit\n"
7435
7436                 "%exit       = OpLabel\n"
7437                 "              OpStore %a_loc %a_next\n"
7438                 "              OpStore %b_loc %b_next\n"
7439                 "%ret16      = OpLoad %v4f16 %result\n"
7440                 "%ret        = OpFConvert %v4f32 %ret16\n"
7441                 "              OpReturnValue %ret\n"
7442
7443                 "              OpFunctionEnd\n";
7444
7445         fragments4["pre_main"]          = typesAndConstants4;
7446         fragments4["testfun"]           = function4;
7447         fragments4["capability"]        = "OpCapability StorageUniformBufferBlock16\n";
7448         fragments4["extension"]         = "OpExtension \"SPV_KHR_16bit_storage\"";
7449
7450         extensions4.push_back("VK_KHR_16bit_storage");
7451         extensions4.push_back("VK_KHR_shader_float16_int8");
7452
7453         vulkanFeatures4.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
7454         vulkanFeatures4.extFloat16Int8  = EXTFLOAT16INT8FEATURES_FLOAT16;
7455
7456         outputColors4[0]                        = RGBA(127, 127, 127, 255);
7457         outputColors4[1]                        = RGBA(127, 0,   0,   255);
7458         outputColors4[2]                        = RGBA(0,   0,   127, 255);
7459         outputColors4[3]                        = RGBA(0,   127, 0,   255);
7460
7461         createTestsForAllStages("swap16", inputColors, outputColors4, fragments4, resources4, extensions4, group.get(), vulkanFeatures4);
7462
7463         return group.release();
7464 }
7465
7466 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
7467 {
7468         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
7469         RGBA                                                    inputColors[4];
7470         RGBA                                                    outputColors[4];
7471
7472         // With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
7473         // For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
7474         // only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
7475         // On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
7476         const char                                              constantsAndTypes[]      =
7477                 "%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
7478                 "%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
7479                 "%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
7480                 "%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
7481                 "%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n";
7482
7483         const char                                              function[]       =
7484                 "%test_code      = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7485                 "%param          = OpFunctionParameter %v4f32\n"
7486                 "%label          = OpLabel\n"
7487                 "%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
7488                 "%var2           = OpVariable %fp_f32 Function\n"
7489                 "%red            = OpCompositeExtract %f32 %param 0\n"
7490                 "%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
7491                 "                  OpStore %var2 %plus_red\n"
7492                 "%val1           = OpLoad %f32 %var1\n"
7493                 "%val2           = OpLoad %f32 %var2\n"
7494                 "%mul            = OpFMul %f32 %val1 %val2\n"
7495                 "%add            = OpFAdd %f32 %mul %c_f32_n1\n"
7496                 "%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
7497                 "%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
7498                 "%success        = OpLogicalOr %bool %is0 %isn1n24\n"
7499                 "%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
7500                 "%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
7501                 "                  OpReturnValue %ret\n"
7502                 "                  OpFunctionEnd\n";
7503
7504         struct CaseNameDecoration
7505         {
7506                 string name;
7507                 string decoration;
7508         };
7509
7510
7511         CaseNameDecoration tests[] = {
7512                 {"multiplication",      "OpDecorate %mul NoContraction"},
7513                 {"addition",            "OpDecorate %add NoContraction"},
7514                 {"both",                        "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
7515         };
7516
7517         getHalfColorsFullAlpha(inputColors);
7518
7519         for (deUint8 idx = 0; idx < 4; ++idx)
7520         {
7521                 inputColors[idx].setRed(0);
7522                 outputColors[idx] = RGBA(0, 0, 0, 255);
7523         }
7524
7525         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
7526         {
7527                 map<string, string> fragments;
7528
7529                 fragments["decoration"] = tests[testNdx].decoration;
7530                 fragments["pre_main"] = constantsAndTypes;
7531                 fragments["testfun"] = function;
7532
7533                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
7534         }
7535
7536         return group.release();
7537 }
7538
7539 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
7540 {
7541         de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
7542         RGBA                                                    colors[4];
7543
7544         const char                                              constantsAndTypes[]      =
7545                 "%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
7546                 "%fp_a2f32          = OpTypePointer Function %a2f32\n"
7547                 "%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
7548                 "%fp_stype          = OpTypePointer Function %stype\n";
7549
7550         const char                                              function[]       =
7551                 "%test_code         = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7552                 "%param1            = OpFunctionParameter %v4f32\n"
7553                 "%lbl               = OpLabel\n"
7554                 "%v1                = OpVariable %fp_v4f32 Function\n"
7555                 "%v2                = OpVariable %fp_a2f32 Function\n"
7556                 "%v3                = OpVariable %fp_f32 Function\n"
7557                 "%v                 = OpVariable %fp_stype Function\n"
7558                 "%vv                = OpVariable %fp_stype Function\n"
7559                 "%vvv               = OpVariable %fp_f32 Function\n"
7560
7561                 "                     OpStore %v1 %c_v4f32_1_1_1_1\n"
7562                 "                     OpStore %v2 %c_a2f32_1\n"
7563                 "                     OpStore %v3 %c_f32_1\n"
7564
7565                 "%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
7566                 "%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
7567                 "%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
7568                 "%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
7569                 "%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
7570                 "%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
7571
7572                 "                    OpStore %p_v4f32 %v1_v ${access_type}\n"
7573                 "                    OpStore %p_a2f32 %v2_v ${access_type}\n"
7574                 "                    OpStore %p_f32 %v3_v ${access_type}\n"
7575
7576                 "                    OpCopyMemory %vv %v ${access_type}\n"
7577                 "                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
7578
7579                 "%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
7580                 "%v_f32_2          = OpLoad %f32 %p_f32_2\n"
7581                 "%v_f32_3          = OpLoad %f32 %vvv\n"
7582
7583                 "%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
7584                 "%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
7585                 "                    OpReturnValue %ret2\n"
7586                 "                    OpFunctionEnd\n";
7587
7588         struct NameMemoryAccess
7589         {
7590                 string name;
7591                 string accessType;
7592         };
7593
7594
7595         NameMemoryAccess tests[] =
7596         {
7597                 { "none", "" },
7598                 { "volatile", "Volatile" },
7599                 { "aligned",  "Aligned 1" },
7600                 { "volatile_aligned",  "Volatile|Aligned 1" },
7601                 { "nontemporal_aligned",  "Nontemporal|Aligned 1" },
7602                 { "volatile_nontemporal",  "Volatile|Nontemporal" },
7603                 { "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
7604         };
7605
7606         getHalfColorsFullAlpha(colors);
7607
7608         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
7609         {
7610                 map<string, string> fragments;
7611                 map<string, string> memoryAccess;
7612                 memoryAccess["access_type"] = tests[testNdx].accessType;
7613
7614                 fragments["pre_main"] = constantsAndTypes;
7615                 fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
7616                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
7617         }
7618         return memoryAccessTests.release();
7619 }
7620 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
7621 {
7622         de::MovePtr<tcu::TestCaseGroup>         opUndefTests             (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
7623         RGBA                                                            defaultColors[4];
7624         map<string, string>                                     fragments;
7625         getDefaultColors(defaultColors);
7626
7627         // First, simple cases that don't do anything with the OpUndef result.
7628         struct NameCodePair { string name, decl, type; };
7629         const NameCodePair tests[] =
7630         {
7631                 {"bool", "", "%bool"},
7632                 {"vec2uint32", "", "%v2u32"},
7633                 {"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown", "%type"},
7634                 {"sampler", "%type = OpTypeSampler", "%type"},
7635                 {"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img", "%type"},
7636                 {"pointer", "", "%fp_i32"},
7637                 {"runtimearray", "%type = OpTypeRuntimeArray %f32", "%type"},
7638                 {"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100", "%type"},
7639                 {"struct", "%type = OpTypeStruct %f32 %i32 %u32", "%type"}};
7640         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
7641         {
7642                 fragments["undef_type"] = tests[testNdx].type;
7643                 fragments["testfun"] = StringTemplate(
7644                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7645                         "%param1 = OpFunctionParameter %v4f32\n"
7646                         "%label_testfun = OpLabel\n"
7647                         "%undef = OpUndef ${undef_type}\n"
7648                         "OpReturnValue %param1\n"
7649                         "OpFunctionEnd\n").specialize(fragments);
7650                 fragments["pre_main"] = tests[testNdx].decl;
7651                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
7652         }
7653         fragments.clear();
7654
7655         fragments["testfun"] =
7656                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7657                 "%param1 = OpFunctionParameter %v4f32\n"
7658                 "%label_testfun = OpLabel\n"
7659                 "%undef = OpUndef %f32\n"
7660                 "%zero = OpFMul %f32 %undef %c_f32_0\n"
7661                 "%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
7662                 "%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
7663                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7664                 "%b = OpFAdd %f32 %a %actually_zero\n"
7665                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
7666                 "OpReturnValue %ret\n"
7667                 "OpFunctionEnd\n";
7668
7669         createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7670
7671         fragments["testfun"] =
7672                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7673                 "%param1 = OpFunctionParameter %v4f32\n"
7674                 "%label_testfun = OpLabel\n"
7675                 "%undef = OpUndef %i32\n"
7676                 "%zero = OpIMul %i32 %undef %c_i32_0\n"
7677                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7678                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7679                 "OpReturnValue %ret\n"
7680                 "OpFunctionEnd\n";
7681
7682         createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7683
7684         fragments["testfun"] =
7685                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7686                 "%param1 = OpFunctionParameter %v4f32\n"
7687                 "%label_testfun = OpLabel\n"
7688                 "%undef = OpUndef %u32\n"
7689                 "%zero = OpIMul %u32 %undef %c_i32_0\n"
7690                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7691                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7692                 "OpReturnValue %ret\n"
7693                 "OpFunctionEnd\n";
7694
7695         createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7696
7697         fragments["testfun"] =
7698                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7699                 "%param1 = OpFunctionParameter %v4f32\n"
7700                 "%label_testfun = OpLabel\n"
7701                 "%undef = OpUndef %v4f32\n"
7702                 "%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
7703                 "%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
7704                 "%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
7705                 "%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
7706                 "%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
7707                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7708                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7709                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7710                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7711                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7712                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7713                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7714                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7715                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7716                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7717                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7718                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7719                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7720                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7721                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7722                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7723                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7724                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7725                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7726                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7727                 "OpReturnValue %ret\n"
7728                 "OpFunctionEnd\n";
7729
7730         createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7731
7732         fragments["pre_main"] =
7733                 "%m2x2f32 = OpTypeMatrix %v2f32 2\n";
7734         fragments["testfun"] =
7735                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7736                 "%param1 = OpFunctionParameter %v4f32\n"
7737                 "%label_testfun = OpLabel\n"
7738                 "%undef = OpUndef %m2x2f32\n"
7739                 "%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
7740                 "%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
7741                 "%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
7742                 "%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
7743                 "%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
7744                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7745                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7746                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7747                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7748                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7749                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7750                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7751                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7752                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7753                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7754                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7755                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7756                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7757                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7758                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7759                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7760                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7761                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7762                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7763                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7764                 "OpReturnValue %ret\n"
7765                 "OpFunctionEnd\n";
7766
7767         createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
7768
7769         return opUndefTests.release();
7770 }
7771
7772 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
7773 {
7774         const RGBA              inputColors[4]          =
7775         {
7776                 RGBA(0,         0,              0,              255),
7777                 RGBA(0,         0,              255,    255),
7778                 RGBA(0,         255,    0,              255),
7779                 RGBA(0,         255,    255,    255)
7780         };
7781
7782         const RGBA              expectedColors[4]       =
7783         {
7784                 RGBA(255,        0,              0,              255),
7785                 RGBA(255,        0,              0,              255),
7786                 RGBA(255,        0,              0,              255),
7787                 RGBA(255,        0,              0,              255)
7788         };
7789
7790         const struct SingleFP16Possibility
7791         {
7792                 const char* name;
7793                 const char* constant;  // Value to assign to %test_constant.
7794                 float           valueAsFloat;
7795                 const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
7796         }                               tests[]                         =
7797         {
7798                 {
7799                         "negative",
7800                         "-0x1.3p1\n",
7801                         -constructNormalizedFloat(1, 0x300000),
7802                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7803                 }, // -19
7804                 {
7805                         "positive",
7806                         "0x1.0p7\n",
7807                         constructNormalizedFloat(7, 0x000000),
7808                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7809                 },  // +128
7810                 // SPIR-V requires that OpQuantizeToF16 flushes
7811                 // any numbers that would end up denormalized in F16 to zero.
7812                 {
7813                         "denorm",
7814                         "0x0.0006p-126\n",
7815                         std::ldexp(1.5f, -140),
7816                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7817                 },  // denorm
7818                 {
7819                         "negative_denorm",
7820                         "-0x0.0006p-126\n",
7821                         -std::ldexp(1.5f, -140),
7822                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7823                 }, // -denorm
7824                 {
7825                         "too_small",
7826                         "0x1.0p-16\n",
7827                         std::ldexp(1.0f, -16),
7828                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7829                 },     // too small positive
7830                 {
7831                         "negative_too_small",
7832                         "-0x1.0p-32\n",
7833                         -std::ldexp(1.0f, -32),
7834                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7835                 },      // too small negative
7836                 {
7837                         "negative_inf",
7838                         "-0x1.0p128\n",
7839                         -std::ldexp(1.0f, 128),
7840
7841                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7842                         "%inf = OpIsInf %bool %c\n"
7843                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7844                 },     // -inf to -inf
7845                 {
7846                         "inf",
7847                         "0x1.0p128\n",
7848                         std::ldexp(1.0f, 128),
7849
7850                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7851                         "%inf = OpIsInf %bool %c\n"
7852                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7853                 },     // +inf to +inf
7854                 {
7855                         "round_to_negative_inf",
7856                         "-0x1.0p32\n",
7857                         -std::ldexp(1.0f, 32),
7858
7859                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7860                         "%inf = OpIsInf %bool %c\n"
7861                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7862                 },     // round to -inf
7863                 {
7864                         "round_to_inf",
7865                         "0x1.0p16\n",
7866                         std::ldexp(1.0f, 16),
7867
7868                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7869                         "%inf = OpIsInf %bool %c\n"
7870                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7871                 },     // round to +inf
7872                 {
7873                         "nan",
7874                         "0x1.1p128\n",
7875                         std::numeric_limits<float>::quiet_NaN(),
7876
7877                         // Test for any NaN value, as NaNs are not preserved
7878                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7879                         "%cond = OpIsNan %bool %direct_quant\n"
7880                 }, // nan
7881                 {
7882                         "negative_nan",
7883                         "-0x1.0001p128\n",
7884                         std::numeric_limits<float>::quiet_NaN(),
7885
7886                         // Test for any NaN value, as NaNs are not preserved
7887                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
7888                         "%cond = OpIsNan %bool %direct_quant\n"
7889                 } // -nan
7890         };
7891         const char*             constants                       =
7892                 "%test_constant = OpConstant %f32 ";  // The value will be test.constant.
7893
7894         StringTemplate  function                        (
7895                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7896                 "%param1        = OpFunctionParameter %v4f32\n"
7897                 "%label_testfun = OpLabel\n"
7898                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7899                 "%b             = OpFAdd %f32 %test_constant %a\n"
7900                 "%c             = OpQuantizeToF16 %f32 %b\n"
7901                 "${condition}\n"
7902                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7903                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7904                 "                 OpReturnValue %retval\n"
7905                 "OpFunctionEnd\n"
7906         );
7907
7908         const char*             specDecorations         = "OpDecorate %test_constant SpecId 0\n";
7909         const char*             specConstants           =
7910                         "%test_constant = OpSpecConstant %f32 0.\n"
7911                         "%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
7912
7913         StringTemplate  specConstantFunction(
7914                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7915                 "%param1        = OpFunctionParameter %v4f32\n"
7916                 "%label_testfun = OpLabel\n"
7917                 "${condition}\n"
7918                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
7919                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
7920                 "                 OpReturnValue %retval\n"
7921                 "OpFunctionEnd\n"
7922         );
7923
7924         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7925         {
7926                 map<string, string>                                                             codeSpecialization;
7927                 map<string, string>                                                             fragments;
7928                 codeSpecialization["condition"]                                 = tests[idx].condition;
7929                 fragments["testfun"]                                                    = function.specialize(codeSpecialization);
7930                 fragments["pre_main"]                                                   = string(constants) + tests[idx].constant + "\n";
7931                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
7932         }
7933
7934         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
7935         {
7936                 map<string, string>                                                             codeSpecialization;
7937                 map<string, string>                                                             fragments;
7938                 SpecConstants                                                                   passConstants;
7939
7940                 codeSpecialization["condition"]                                 = tests[idx].condition;
7941                 fragments["testfun"]                                                    = specConstantFunction.specialize(codeSpecialization);
7942                 fragments["decoration"]                                                 = specDecorations;
7943                 fragments["pre_main"]                                                   = specConstants;
7944
7945                 passConstants.append<float>(tests[idx].valueAsFloat);
7946
7947                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
7948         }
7949 }
7950
7951 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
7952 {
7953         RGBA inputColors[4] =  {
7954                 RGBA(0,         0,              0,              255),
7955                 RGBA(0,         0,              255,    255),
7956                 RGBA(0,         255,    0,              255),
7957                 RGBA(0,         255,    255,    255)
7958         };
7959
7960         RGBA expectedColors[4] =
7961         {
7962                 RGBA(255,        0,              0,              255),
7963                 RGBA(255,        0,              0,              255),
7964                 RGBA(255,        0,              0,              255),
7965                 RGBA(255,        0,              0,              255)
7966         };
7967
7968         struct DualFP16Possibility
7969         {
7970                 const char* name;
7971                 const char* input;
7972                 float           inputAsFloat;
7973                 const char* possibleOutput1;
7974                 const char* possibleOutput2;
7975         } tests[] = {
7976                 {
7977                         "positive_round_up_or_round_down",
7978                         "0x1.3003p8",
7979                         constructNormalizedFloat(8, 0x300300),
7980                         "0x1.304p8",
7981                         "0x1.3p8"
7982                 },
7983                 {
7984                         "negative_round_up_or_round_down",
7985                         "-0x1.6008p-7",
7986                         -constructNormalizedFloat(-7, 0x600800),
7987                         "-0x1.6p-7",
7988                         "-0x1.604p-7"
7989                 },
7990                 {
7991                         "carry_bit",
7992                         "0x1.01ep2",
7993                         constructNormalizedFloat(2, 0x01e000),
7994                         "0x1.01cp2",
7995                         "0x1.02p2"
7996                 },
7997                 {
7998                         "carry_to_exponent",
7999                         "0x1.ffep1",
8000                         constructNormalizedFloat(1, 0xffe000),
8001                         "0x1.ffcp1",
8002                         "0x1.0p2"
8003                 },
8004         };
8005         StringTemplate constants (
8006                 "%input_const = OpConstant %f32 ${input}\n"
8007                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8008                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8009                 );
8010
8011         StringTemplate specConstants (
8012                 "%input_const = OpSpecConstant %f32 0.\n"
8013                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8014                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8015         );
8016
8017         const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
8018
8019         const char* function  =
8020                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8021                 "%param1        = OpFunctionParameter %v4f32\n"
8022                 "%label_testfun = OpLabel\n"
8023                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8024                 // For the purposes of this test we assume that 0.f will always get
8025                 // faithfully passed through the pipeline stages.
8026                 "%b             = OpFAdd %f32 %input_const %a\n"
8027                 "%c             = OpQuantizeToF16 %f32 %b\n"
8028                 "%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
8029                 "%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
8030                 "%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
8031                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8032                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
8033                 "                 OpReturnValue %retval\n"
8034                 "OpFunctionEnd\n";
8035
8036         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8037                 map<string, string>                                                                     fragments;
8038                 map<string, string>                                                                     constantSpecialization;
8039
8040                 constantSpecialization["input"]                                         = tests[idx].input;
8041                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8042                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8043                 fragments["testfun"]                                                            = function;
8044                 fragments["pre_main"]                                                           = constants.specialize(constantSpecialization);
8045                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
8046         }
8047
8048         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8049                 map<string, string>                                                                     fragments;
8050                 map<string, string>                                                                     constantSpecialization;
8051                 SpecConstants                                                                           passConstants;
8052
8053                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8054                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8055                 fragments["testfun"]                                                            = function;
8056                 fragments["decoration"]                                                         = specDecorations;
8057                 fragments["pre_main"]                                                           = specConstants.specialize(constantSpecialization);
8058
8059                 passConstants.append<float>(tests[idx].inputAsFloat);
8060
8061                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
8062         }
8063 }
8064
8065 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
8066 {
8067         de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
8068         createOpQuantizeSingleOptionTests(opQuantizeTests.get());
8069         createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
8070         return opQuantizeTests.release();
8071 }
8072
8073 struct ShaderPermutation
8074 {
8075         deUint8 vertexPermutation;
8076         deUint8 geometryPermutation;
8077         deUint8 tesscPermutation;
8078         deUint8 tessePermutation;
8079         deUint8 fragmentPermutation;
8080 };
8081
8082 ShaderPermutation getShaderPermutation(deUint8 inputValue)
8083 {
8084         ShaderPermutation       permutation =
8085         {
8086                 static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
8087                 static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
8088                 static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
8089                 static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
8090                 static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
8091         };
8092         return permutation;
8093 }
8094
8095 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
8096 {
8097         RGBA                                                            defaultColors[4];
8098         RGBA                                                            invertedColors[4];
8099         de::MovePtr<tcu::TestCaseGroup>         moduleTests                     (new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
8100
8101         getDefaultColors(defaultColors);
8102         getInvertedDefaultColors(invertedColors);
8103
8104         // Combined module tests
8105         {
8106                 // Shader stages: vertex and fragment
8107                 {
8108                         const ShaderElement combinedPipeline[]  =
8109                         {
8110                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8111                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8112                         };
8113
8114                         addFunctionCaseWithPrograms<InstanceContext>(
8115                                 moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline,
8116                                 createInstanceContext(combinedPipeline, map<string, string>()));
8117                 }
8118
8119                 // Shader stages: vertex, geometry and fragment
8120                 {
8121                         const ShaderElement combinedPipeline[]  =
8122                         {
8123                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8124                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8125                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8126                         };
8127
8128                         addFunctionCaseWithPrograms<InstanceContext>(
8129                                 moduleTests.get(), "same_module_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8130                                 createInstanceContext(combinedPipeline, map<string, string>()));
8131                 }
8132
8133                 // Shader stages: vertex, tessellation control, tessellation evaluation and fragment
8134                 {
8135                         const ShaderElement combinedPipeline[]  =
8136                         {
8137                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8138                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8139                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8140                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8141                         };
8142
8143                         addFunctionCaseWithPrograms<InstanceContext>(
8144                                 moduleTests.get(), "same_module_tessc_tesse", "", createCombinedModule, runAndVerifyDefaultPipeline,
8145                                 createInstanceContext(combinedPipeline, map<string, string>()));
8146                 }
8147
8148                 // Shader stages: vertex, tessellation control, tessellation evaluation, geometry and fragment
8149                 {
8150                         const ShaderElement combinedPipeline[]  =
8151                         {
8152                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8153                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8154                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8155                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8156                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8157                         };
8158
8159                         addFunctionCaseWithPrograms<InstanceContext>(
8160                                 moduleTests.get(), "same_module_tessc_tesse_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8161                                 createInstanceContext(combinedPipeline, map<string, string>()));
8162                 }
8163         }
8164
8165         const char* numbers[] =
8166         {
8167                 "1", "2"
8168         };
8169
8170         for (deInt8 idx = 0; idx < 32; ++idx)
8171         {
8172                 ShaderPermutation                       permutation             = getShaderPermutation(idx);
8173                 string                                          name                    = string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
8174                 const ShaderElement                     pipeline[]              =
8175                 {
8176                         ShaderElement("vert",   string("vert") +        numbers[permutation.vertexPermutation],         VK_SHADER_STAGE_VERTEX_BIT),
8177                         ShaderElement("geom",   string("geom") +        numbers[permutation.geometryPermutation],       VK_SHADER_STAGE_GEOMETRY_BIT),
8178                         ShaderElement("tessc",  string("tessc") +       numbers[permutation.tesscPermutation],          VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8179                         ShaderElement("tesse",  string("tesse") +       numbers[permutation.tessePermutation],          VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8180                         ShaderElement("frag",   string("frag") +        numbers[permutation.fragmentPermutation],       VK_SHADER_STAGE_FRAGMENT_BIT)
8181                 };
8182
8183                 // If there are an even number of swaps, then it should be no-op.
8184                 // If there are an odd number, the color should be flipped.
8185                 if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
8186                 {
8187                         addFunctionCaseWithPrograms<InstanceContext>(
8188                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8189                                         createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
8190                 }
8191                 else
8192                 {
8193                         addFunctionCaseWithPrograms<InstanceContext>(
8194                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8195                                         createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
8196                 }
8197         }
8198         return moduleTests.release();
8199 }
8200
8201 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
8202 {
8203         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
8204         RGBA defaultColors[4];
8205         getDefaultColors(defaultColors);
8206         map<string, string> fragments;
8207         fragments["pre_main"] =
8208                 "%c_f32_5 = OpConstant %f32 5.\n";
8209
8210         // A loop with a single block. The Continue Target is the loop block
8211         // itself. In SPIR-V terms, the "loop construct" contains no blocks at all
8212         // -- the "continue construct" forms the entire loop.
8213         fragments["testfun"] =
8214                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8215                 "%param1 = OpFunctionParameter %v4f32\n"
8216
8217                 "%entry = OpLabel\n"
8218                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8219                 "OpBranch %loop\n"
8220
8221                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8222                 "%loop = OpLabel\n"
8223                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8224                 "%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
8225                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8226                 "%val = OpFAdd %f32 %val1 %delta\n"
8227                 "%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
8228                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8229                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8230                 "OpLoopMerge %exit %loop None\n"
8231                 "OpBranchConditional %again %loop %exit\n"
8232
8233                 "%exit = OpLabel\n"
8234                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8235                 "OpReturnValue %result\n"
8236
8237                 "OpFunctionEnd\n";
8238
8239         createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
8240
8241         // Body comprised of multiple basic blocks.
8242         const StringTemplate multiBlock(
8243                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8244                 "%param1 = OpFunctionParameter %v4f32\n"
8245
8246                 "%entry = OpLabel\n"
8247                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8248                 "OpBranch %loop\n"
8249
8250                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8251                 "%loop = OpLabel\n"
8252                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
8253                 "%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
8254                 "%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
8255                 // There are several possibilities for the Continue Target below.  Each
8256                 // will be specialized into a separate test case.
8257                 "OpLoopMerge %exit ${continue_target} None\n"
8258                 "OpBranch %if\n"
8259
8260                 "%if = OpLabel\n"
8261                 ";delta_next = (delta > 0) ? -1 : 1;\n"
8262                 "%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
8263                 "OpSelectionMerge %gather DontFlatten\n"
8264                 "OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
8265
8266                 "%odd = OpLabel\n"
8267                 "OpBranch %gather\n"
8268
8269                 "%even = OpLabel\n"
8270                 "OpBranch %gather\n"
8271
8272                 "%gather = OpLabel\n"
8273                 "%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
8274                 "%val = OpFAdd %f32 %val1 %delta\n"
8275                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8276                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8277                 "OpBranchConditional %again %loop %exit\n"
8278
8279                 "%exit = OpLabel\n"
8280                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8281                 "OpReturnValue %result\n"
8282
8283                 "OpFunctionEnd\n");
8284
8285         map<string, string> continue_target;
8286
8287         // The Continue Target is the loop block itself.
8288         continue_target["continue_target"] = "%loop";
8289         fragments["testfun"] = multiBlock.specialize(continue_target);
8290         createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
8291
8292         // The Continue Target is at the end of the loop.
8293         continue_target["continue_target"] = "%gather";
8294         fragments["testfun"] = multiBlock.specialize(continue_target);
8295         createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
8296
8297         // A loop with continue statement.
8298         fragments["testfun"] =
8299                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8300                 "%param1 = OpFunctionParameter %v4f32\n"
8301
8302                 "%entry = OpLabel\n"
8303                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8304                 "OpBranch %loop\n"
8305
8306                 ";adds 4, 3, and 1 to %val0 (skips 2)\n"
8307                 "%loop = OpLabel\n"
8308                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8309                 "%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
8310                 "OpLoopMerge %exit %continue None\n"
8311                 "OpBranch %if\n"
8312
8313                 "%if = OpLabel\n"
8314                 ";skip if %count==2\n"
8315                 "%eq2 = OpIEqual %bool %count %c_i32_2\n"
8316                 "OpSelectionMerge %continue DontFlatten\n"
8317                 "OpBranchConditional %eq2 %continue %body\n"
8318
8319                 "%body = OpLabel\n"
8320                 "%fcount = OpConvertSToF %f32 %count\n"
8321                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8322                 "OpBranch %continue\n"
8323
8324                 "%continue = OpLabel\n"
8325                 "%val = OpPhi %f32 %val2 %body %val1 %if\n"
8326                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8327                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8328                 "OpBranchConditional %again %loop %exit\n"
8329
8330                 "%exit = OpLabel\n"
8331                 "%same = OpFSub %f32 %val %c_f32_8\n"
8332                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8333                 "OpReturnValue %result\n"
8334                 "OpFunctionEnd\n";
8335         createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
8336
8337         // A loop with break.
8338         fragments["testfun"] =
8339                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8340                 "%param1 = OpFunctionParameter %v4f32\n"
8341
8342                 "%entry = OpLabel\n"
8343                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8344                 "%dot = OpDot %f32 %param1 %param1\n"
8345                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8346                 "%zero = OpConvertFToU %u32 %div\n"
8347                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8348                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8349                 "OpBranch %loop\n"
8350
8351                 ";adds 4 and 3 to %val0 (exits early)\n"
8352                 "%loop = OpLabel\n"
8353                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8354                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8355                 "OpLoopMerge %exit %continue None\n"
8356                 "OpBranch %if\n"
8357
8358                 "%if = OpLabel\n"
8359                 ";end loop if %count==%two\n"
8360                 "%above2 = OpSGreaterThan %bool %count %two\n"
8361                 "OpSelectionMerge %continue DontFlatten\n"
8362                 "OpBranchConditional %above2 %body %exit\n"
8363
8364                 "%body = OpLabel\n"
8365                 "%fcount = OpConvertSToF %f32 %count\n"
8366                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8367                 "OpBranch %continue\n"
8368
8369                 "%continue = OpLabel\n"
8370                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8371                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8372                 "OpBranchConditional %again %loop %exit\n"
8373
8374                 "%exit = OpLabel\n"
8375                 "%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
8376                 "%same = OpFSub %f32 %val_post %c_f32_7\n"
8377                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8378                 "OpReturnValue %result\n"
8379                 "OpFunctionEnd\n";
8380         createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
8381
8382         // A loop with return.
8383         fragments["testfun"] =
8384                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8385                 "%param1 = OpFunctionParameter %v4f32\n"
8386
8387                 "%entry = OpLabel\n"
8388                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8389                 "%dot = OpDot %f32 %param1 %param1\n"
8390                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8391                 "%zero = OpConvertFToU %u32 %div\n"
8392                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8393                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8394                 "OpBranch %loop\n"
8395
8396                 ";returns early without modifying %param1\n"
8397                 "%loop = OpLabel\n"
8398                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8399                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8400                 "OpLoopMerge %exit %continue None\n"
8401                 "OpBranch %if\n"
8402
8403                 "%if = OpLabel\n"
8404                 ";return if %count==%two\n"
8405                 "%above2 = OpSGreaterThan %bool %count %two\n"
8406                 "OpSelectionMerge %continue DontFlatten\n"
8407                 "OpBranchConditional %above2 %body %early_exit\n"
8408
8409                 "%early_exit = OpLabel\n"
8410                 "OpReturnValue %param1\n"
8411
8412                 "%body = OpLabel\n"
8413                 "%fcount = OpConvertSToF %f32 %count\n"
8414                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8415                 "OpBranch %continue\n"
8416
8417                 "%continue = OpLabel\n"
8418                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8419                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8420                 "OpBranchConditional %again %loop %exit\n"
8421
8422                 "%exit = OpLabel\n"
8423                 ";should never get here, so return an incorrect result\n"
8424                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
8425                 "OpReturnValue %result\n"
8426                 "OpFunctionEnd\n";
8427         createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
8428
8429         // Continue inside a switch block to break to enclosing loop's merge block.
8430         // Matches roughly the following GLSL code:
8431         // for (; keep_going; keep_going = false)
8432         // {
8433         //     switch (int(param1.x))
8434         //     {
8435         //         case 0: continue;
8436         //         case 1: continue;
8437         //         default: continue;
8438         //     }
8439         //     dead code: modify return value to invalid result.
8440         // }
8441         fragments["pre_main"] =
8442                 "%fp_bool = OpTypePointer Function %bool\n"
8443                 "%true = OpConstantTrue %bool\n"
8444                 "%false = OpConstantFalse %bool\n";
8445
8446         fragments["testfun"] =
8447                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8448                 "%param1 = OpFunctionParameter %v4f32\n"
8449
8450                 "%entry = OpLabel\n"
8451                 "%keep_going = OpVariable %fp_bool Function\n"
8452                 "%val_ptr = OpVariable %fp_f32 Function\n"
8453                 "%param1_x = OpCompositeExtract %f32 %param1 0\n"
8454                 "OpStore %keep_going %true\n"
8455                 "OpBranch %forloop_begin\n"
8456
8457                 "%forloop_begin = OpLabel\n"
8458                 "OpLoopMerge %forloop_merge %forloop_continue None\n"
8459                 "OpBranch %forloop\n"
8460
8461                 "%forloop = OpLabel\n"
8462                 "%for_condition = OpLoad %bool %keep_going\n"
8463                 "OpBranchConditional %for_condition %forloop_body %forloop_merge\n"
8464
8465                 "%forloop_body = OpLabel\n"
8466                 "OpStore %val_ptr %param1_x\n"
8467                 "%param1_x_int = OpConvertFToS %i32 %param1_x\n"
8468
8469                 "OpSelectionMerge %switch_merge None\n"
8470                 "OpSwitch %param1_x_int %default 0 %case_0 1 %case_1\n"
8471                 "%case_0 = OpLabel\n"
8472                 "OpBranch %forloop_continue\n"
8473                 "%case_1 = OpLabel\n"
8474                 "OpBranch %forloop_continue\n"
8475                 "%default = OpLabel\n"
8476                 "OpBranch %forloop_continue\n"
8477                 "%switch_merge = OpLabel\n"
8478                 ";should never get here, so change the return value to invalid result\n"
8479                 "OpStore %val_ptr %c_f32_1\n"
8480                 "OpBranch %forloop_continue\n"
8481
8482                 "%forloop_continue = OpLabel\n"
8483                 "OpStore %keep_going %false\n"
8484                 "OpBranch %forloop_begin\n"
8485                 "%forloop_merge = OpLabel\n"
8486
8487                 "%val = OpLoad %f32 %val_ptr\n"
8488                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8489                 "OpReturnValue %result\n"
8490                 "OpFunctionEnd\n";
8491         createTestsForAllStages("switch_continue", defaultColors, defaultColors, fragments, testGroup.get());
8492
8493         return testGroup.release();
8494 }
8495
8496 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
8497 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
8498 {
8499         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
8500         map<string, string> fragments;
8501
8502         // A barrier inside a function body.
8503         fragments["pre_main"] =
8504                 "%Workgroup = OpConstant %i32 2\n"
8505                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n";
8506         fragments["testfun"] =
8507                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8508                 "%param1 = OpFunctionParameter %v4f32\n"
8509                 "%label_testfun = OpLabel\n"
8510                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8511                 "OpReturnValue %param1\n"
8512                 "OpFunctionEnd\n";
8513         addTessCtrlTest(testGroup.get(), "in_function", fragments);
8514
8515         // Common setup code for the following tests.
8516         fragments["pre_main"] =
8517                 "%Workgroup = OpConstant %i32 2\n"
8518                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8519                 "%c_f32_5 = OpConstant %f32 5.\n";
8520         const string setupPercentZero =  // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
8521                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8522                 "%param1 = OpFunctionParameter %v4f32\n"
8523                 "%entry = OpLabel\n"
8524                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8525                 "%dot = OpDot %f32 %param1 %param1\n"
8526                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8527                 "%zero = OpConvertFToU %u32 %div\n";
8528
8529         // Barriers inside OpSwitch branches.
8530         fragments["testfun"] =
8531                 setupPercentZero +
8532                 "OpSelectionMerge %switch_exit None\n"
8533                 "OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
8534
8535                 "%case1 = OpLabel\n"
8536                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8537                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8538                 "%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8539                 "OpBranch %switch_exit\n"
8540
8541                 "%switch_default = OpLabel\n"
8542                 "%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8543                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8544                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8545                 "OpBranch %switch_exit\n"
8546
8547                 "%case0 = OpLabel\n"
8548                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8549                 "OpBranch %switch_exit\n"
8550
8551                 "%switch_exit = OpLabel\n"
8552                 "%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
8553                 "OpReturnValue %ret\n"
8554                 "OpFunctionEnd\n";
8555         addTessCtrlTest(testGroup.get(), "in_switch", fragments);
8556
8557         // Barriers inside if-then-else.
8558         fragments["testfun"] =
8559                 setupPercentZero +
8560                 "%eq0 = OpIEqual %bool %zero %c_u32_0\n"
8561                 "OpSelectionMerge %exit DontFlatten\n"
8562                 "OpBranchConditional %eq0 %then %else\n"
8563
8564                 "%else = OpLabel\n"
8565                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8566                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8567                 "%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8568                 "OpBranch %exit\n"
8569
8570                 "%then = OpLabel\n"
8571                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8572                 "OpBranch %exit\n"
8573                 "%exit = OpLabel\n"
8574                 "%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
8575                 "OpReturnValue %ret\n"
8576                 "OpFunctionEnd\n";
8577         addTessCtrlTest(testGroup.get(), "in_if", fragments);
8578
8579         // A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
8580         // http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
8581         fragments["testfun"] =
8582                 setupPercentZero +
8583                 "%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
8584                 "%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
8585                 "OpSelectionMerge %exit DontFlatten\n"
8586                 "OpBranchConditional %thread0 %then %else\n"
8587
8588                 "%else = OpLabel\n"
8589                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8590                 "OpBranch %exit\n"
8591
8592                 "%then = OpLabel\n"
8593                 "%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
8594                 "OpBranch %exit\n"
8595
8596                 "%exit = OpLabel\n"
8597                 "%val = OpPhi %f32 %val0 %else %val1 %then\n"
8598                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8599                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
8600                 "OpReturnValue %ret\n"
8601                 "OpFunctionEnd\n";
8602         addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
8603
8604         // A barrier inside a loop.
8605         fragments["pre_main"] =
8606                 "%Workgroup = OpConstant %i32 2\n"
8607                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8608                 "%c_f32_10 = OpConstant %f32 10.\n";
8609         fragments["testfun"] =
8610                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8611                 "%param1 = OpFunctionParameter %v4f32\n"
8612                 "%entry = OpLabel\n"
8613                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8614                 "OpBranch %loop\n"
8615
8616                 ";adds 4, 3, 2, and 1 to %val0\n"
8617                 "%loop = OpLabel\n"
8618                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8619                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8620                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8621                 "%fcount = OpConvertSToF %f32 %count\n"
8622                 "%val = OpFAdd %f32 %val1 %fcount\n"
8623                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8624                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8625                 "OpLoopMerge %exit %loop None\n"
8626                 "OpBranchConditional %again %loop %exit\n"
8627
8628                 "%exit = OpLabel\n"
8629                 "%same = OpFSub %f32 %val %c_f32_10\n"
8630                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8631                 "OpReturnValue %ret\n"
8632                 "OpFunctionEnd\n";
8633         addTessCtrlTest(testGroup.get(), "in_loop", fragments);
8634
8635         return testGroup.release();
8636 }
8637
8638 // Test for the OpFRem instruction.
8639 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
8640 {
8641         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
8642         map<string, string>                                     fragments;
8643         RGBA                                                            inputColors[4];
8644         RGBA                                                            outputColors[4];
8645
8646         fragments["pre_main"]                            =
8647                 "%c_f32_3 = OpConstant %f32 3.0\n"
8648                 "%c_f32_n3 = OpConstant %f32 -3.0\n"
8649                 "%c_f32_4 = OpConstant %f32 4.0\n"
8650                 "%c_f32_p75 = OpConstant %f32 0.75\n"
8651                 "%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
8652                 "%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
8653                 "%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
8654
8655         // The test does the following.
8656         // vec4 result = (param1 * 8.0) - 4.0;
8657         // return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
8658         fragments["testfun"]                             =
8659                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8660                 "%param1 = OpFunctionParameter %v4f32\n"
8661                 "%label_testfun = OpLabel\n"
8662                 "%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
8663                 "%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
8664                 "%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
8665                 "%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
8666                 "%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
8667                 "%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
8668                 "OpReturnValue %xy_0_1\n"
8669                 "OpFunctionEnd\n";
8670
8671
8672         inputColors[0]          = RGBA(16,      16,             0, 255);
8673         inputColors[1]          = RGBA(232, 232,        0, 255);
8674         inputColors[2]          = RGBA(232, 16,         0, 255);
8675         inputColors[3]          = RGBA(16,      232,    0, 255);
8676
8677         outputColors[0]         = RGBA(64,      64,             0, 255);
8678         outputColors[1]         = RGBA(255, 255,        0, 255);
8679         outputColors[2]         = RGBA(255, 64,         0, 255);
8680         outputColors[3]         = RGBA(64,      255,    0, 255);
8681
8682         createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
8683         return testGroup.release();
8684 }
8685
8686 // Test for the OpSRem instruction.
8687 tcu::TestCaseGroup* createOpSRemGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8688 {
8689         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "srem", "OpSRem"));
8690         map<string, string>                                     fragments;
8691
8692         fragments["pre_main"]                            =
8693                 "%c_f32_255 = OpConstant %f32 255.0\n"
8694                 "%c_i32_128 = OpConstant %i32 128\n"
8695                 "%c_i32_255 = OpConstant %i32 255\n"
8696                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8697                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8698                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8699
8700         // The test does the following.
8701         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8702         // ivec4 result = ivec4(srem(ints.x, ints.y), srem(ints.y, ints.z), srem(ints.z, ints.x), 255);
8703         // return float(result + 128) / 255.0;
8704         fragments["testfun"]                             =
8705                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8706                 "%param1 = OpFunctionParameter %v4f32\n"
8707                 "%label_testfun = OpLabel\n"
8708                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8709                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8710                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8711                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8712                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8713                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8714                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8715                 "%x_out = OpSRem %i32 %x_in %y_in\n"
8716                 "%y_out = OpSRem %i32 %y_in %z_in\n"
8717                 "%z_out = OpSRem %i32 %z_in %x_in\n"
8718                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8719                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8720                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8721                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8722                 "OpReturnValue %float_out\n"
8723                 "OpFunctionEnd\n";
8724
8725         const struct CaseParams
8726         {
8727                 const char*             name;
8728                 const char*             failMessageTemplate;    // customized status message
8729                 qpTestResult    failResult;                             // override status on failure
8730                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8731                 int                             results[4][3];                  // four (x, y, z) vectors of results
8732         } cases[] =
8733         {
8734                 {
8735                         "positive",
8736                         "${reason}",
8737                         QP_TEST_RESULT_FAIL,
8738                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                 // operands
8739                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                 // results
8740                 },
8741                 {
8742                         "all",
8743                         "Inconsistent results, but within specification: ${reason}",
8744                         negFailResult,                                                                                                                  // negative operands, not required by the spec
8745                         { { 5, 12, -17 }, { -5, -5, 7 }, { 75, 8, -81 }, { 25, -60, 100 } },    // operands
8746                         { { 5, 12,  -2 }, {  0, -5, 2 }, {  3, 8,  -6 }, { 25, -60,   0 } },    // results
8747                 },
8748         };
8749         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8750
8751         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8752         {
8753                 const CaseParams&       params                  = cases[caseNdx];
8754                 RGBA                            inputColors[4];
8755                 RGBA                            outputColors[4];
8756
8757                 for (int i = 0; i < 4; ++i)
8758                 {
8759                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8760                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8761                 }
8762
8763                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8764         }
8765
8766         return testGroup.release();
8767 }
8768
8769 // Test for the OpSMod instruction.
8770 tcu::TestCaseGroup* createOpSModGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8771 {
8772         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "smod", "OpSMod"));
8773         map<string, string>                                     fragments;
8774
8775         fragments["pre_main"]                            =
8776                 "%c_f32_255 = OpConstant %f32 255.0\n"
8777                 "%c_i32_128 = OpConstant %i32 128\n"
8778                 "%c_i32_255 = OpConstant %i32 255\n"
8779                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8780                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8781                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8782
8783         // The test does the following.
8784         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8785         // ivec4 result = ivec4(smod(ints.x, ints.y), smod(ints.y, ints.z), smod(ints.z, ints.x), 255);
8786         // return float(result + 128) / 255.0;
8787         fragments["testfun"]                             =
8788                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8789                 "%param1 = OpFunctionParameter %v4f32\n"
8790                 "%label_testfun = OpLabel\n"
8791                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8792                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8793                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8794                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8795                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8796                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8797                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8798                 "%x_out = OpSMod %i32 %x_in %y_in\n"
8799                 "%y_out = OpSMod %i32 %y_in %z_in\n"
8800                 "%z_out = OpSMod %i32 %z_in %x_in\n"
8801                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8802                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8803                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8804                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8805                 "OpReturnValue %float_out\n"
8806                 "OpFunctionEnd\n";
8807
8808         const struct CaseParams
8809         {
8810                 const char*             name;
8811                 const char*             failMessageTemplate;    // customized status message
8812                 qpTestResult    failResult;                             // override status on failure
8813                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8814                 int                             results[4][3];                  // four (x, y, z) vectors of results
8815         } cases[] =
8816         {
8817                 {
8818                         "positive",
8819                         "${reason}",
8820                         QP_TEST_RESULT_FAIL,
8821                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                         // operands
8822                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                         // results
8823                 },
8824                 {
8825                         "all",
8826                         "Inconsistent results, but within specification: ${reason}",
8827                         negFailResult,                                                                                                                          // negative operands, not required by the spec
8828                         { { 5, 12, -17 }, { -5, -5,  7 }, { 75,   8, -81 }, {  25, -60, 100 } },        // operands
8829                         { { 5, -5,   3 }, {  0,  2, -3 }, {  3, -73,  69 }, { -35,  40,   0 } },        // results
8830                 },
8831         };
8832         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8833
8834         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8835         {
8836                 const CaseParams&       params                  = cases[caseNdx];
8837                 RGBA                            inputColors[4];
8838                 RGBA                            outputColors[4];
8839
8840                 for (int i = 0; i < 4; ++i)
8841                 {
8842                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8843                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8844                 }
8845
8846                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8847         }
8848         return testGroup.release();
8849 }
8850
8851 enum ConversionDataType
8852 {
8853         DATA_TYPE_SIGNED_8,
8854         DATA_TYPE_SIGNED_16,
8855         DATA_TYPE_SIGNED_32,
8856         DATA_TYPE_SIGNED_64,
8857         DATA_TYPE_UNSIGNED_8,
8858         DATA_TYPE_UNSIGNED_16,
8859         DATA_TYPE_UNSIGNED_32,
8860         DATA_TYPE_UNSIGNED_64,
8861         DATA_TYPE_FLOAT_16,
8862         DATA_TYPE_FLOAT_32,
8863         DATA_TYPE_FLOAT_64,
8864         DATA_TYPE_VEC2_SIGNED_16,
8865         DATA_TYPE_VEC2_SIGNED_32
8866 };
8867
8868 const string getBitWidthStr (ConversionDataType type)
8869 {
8870         switch (type)
8871         {
8872                 case DATA_TYPE_SIGNED_8:
8873                 case DATA_TYPE_UNSIGNED_8:
8874                         return "8";
8875
8876                 case DATA_TYPE_SIGNED_16:
8877                 case DATA_TYPE_UNSIGNED_16:
8878                 case DATA_TYPE_FLOAT_16:
8879                         return "16";
8880
8881                 case DATA_TYPE_SIGNED_32:
8882                 case DATA_TYPE_UNSIGNED_32:
8883                 case DATA_TYPE_FLOAT_32:
8884                 case DATA_TYPE_VEC2_SIGNED_16:
8885                         return "32";
8886
8887                 case DATA_TYPE_SIGNED_64:
8888                 case DATA_TYPE_UNSIGNED_64:
8889                 case DATA_TYPE_FLOAT_64:
8890                 case DATA_TYPE_VEC2_SIGNED_32:
8891                         return "64";
8892
8893                 default:
8894                         DE_ASSERT(false);
8895         }
8896         return "";
8897 }
8898
8899 const string getByteWidthStr (ConversionDataType type)
8900 {
8901         switch (type)
8902         {
8903                 case DATA_TYPE_SIGNED_8:
8904                 case DATA_TYPE_UNSIGNED_8:
8905                         return "1";
8906
8907                 case DATA_TYPE_SIGNED_16:
8908                 case DATA_TYPE_UNSIGNED_16:
8909                 case DATA_TYPE_FLOAT_16:
8910                         return "2";
8911
8912                 case DATA_TYPE_SIGNED_32:
8913                 case DATA_TYPE_UNSIGNED_32:
8914                 case DATA_TYPE_FLOAT_32:
8915                 case DATA_TYPE_VEC2_SIGNED_16:
8916                         return "4";
8917
8918                 case DATA_TYPE_SIGNED_64:
8919                 case DATA_TYPE_UNSIGNED_64:
8920                 case DATA_TYPE_FLOAT_64:
8921                 case DATA_TYPE_VEC2_SIGNED_32:
8922                         return "8";
8923
8924                 default:
8925                         DE_ASSERT(false);
8926         }
8927         return "";
8928 }
8929
8930 bool isSigned (ConversionDataType type)
8931 {
8932         switch (type)
8933         {
8934                 case DATA_TYPE_SIGNED_8:
8935                 case DATA_TYPE_SIGNED_16:
8936                 case DATA_TYPE_SIGNED_32:
8937                 case DATA_TYPE_SIGNED_64:
8938                 case DATA_TYPE_FLOAT_16:
8939                 case DATA_TYPE_FLOAT_32:
8940                 case DATA_TYPE_FLOAT_64:
8941                 case DATA_TYPE_VEC2_SIGNED_16:
8942                 case DATA_TYPE_VEC2_SIGNED_32:
8943                         return true;
8944
8945                 case DATA_TYPE_UNSIGNED_8:
8946                 case DATA_TYPE_UNSIGNED_16:
8947                 case DATA_TYPE_UNSIGNED_32:
8948                 case DATA_TYPE_UNSIGNED_64:
8949                         return false;
8950
8951                 default:
8952                         DE_ASSERT(false);
8953         }
8954         return false;
8955 }
8956
8957 bool isInt (ConversionDataType type)
8958 {
8959         switch (type)
8960         {
8961                 case DATA_TYPE_SIGNED_8:
8962                 case DATA_TYPE_SIGNED_16:
8963                 case DATA_TYPE_SIGNED_32:
8964                 case DATA_TYPE_SIGNED_64:
8965                 case DATA_TYPE_UNSIGNED_8:
8966                 case DATA_TYPE_UNSIGNED_16:
8967                 case DATA_TYPE_UNSIGNED_32:
8968                 case DATA_TYPE_UNSIGNED_64:
8969                         return true;
8970
8971                 case DATA_TYPE_FLOAT_16:
8972                 case DATA_TYPE_FLOAT_32:
8973                 case DATA_TYPE_FLOAT_64:
8974                 case DATA_TYPE_VEC2_SIGNED_16:
8975                 case DATA_TYPE_VEC2_SIGNED_32:
8976                         return false;
8977
8978                 default:
8979                         DE_ASSERT(false);
8980         }
8981         return false;
8982 }
8983
8984 bool isFloat (ConversionDataType type)
8985 {
8986         switch (type)
8987         {
8988                 case DATA_TYPE_SIGNED_8:
8989                 case DATA_TYPE_SIGNED_16:
8990                 case DATA_TYPE_SIGNED_32:
8991                 case DATA_TYPE_SIGNED_64:
8992                 case DATA_TYPE_UNSIGNED_8:
8993                 case DATA_TYPE_UNSIGNED_16:
8994                 case DATA_TYPE_UNSIGNED_32:
8995                 case DATA_TYPE_UNSIGNED_64:
8996                 case DATA_TYPE_VEC2_SIGNED_16:
8997                 case DATA_TYPE_VEC2_SIGNED_32:
8998                         return false;
8999
9000                 case DATA_TYPE_FLOAT_16:
9001                 case DATA_TYPE_FLOAT_32:
9002                 case DATA_TYPE_FLOAT_64:
9003                         return true;
9004
9005                 default:
9006                         DE_ASSERT(false);
9007         }
9008         return false;
9009 }
9010
9011 const string getTypeName (ConversionDataType type)
9012 {
9013         string prefix = isSigned(type) ? "" : "u";
9014
9015         if              (isInt(type))                                           return prefix + "int"   + getBitWidthStr(type);
9016         else if (isFloat(type))                                         return prefix + "float" + getBitWidthStr(type);
9017         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9018         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "i32vec2";
9019         else                                                                            DE_ASSERT(false);
9020
9021         return "";
9022 }
9023
9024 const string getTestName (ConversionDataType from, ConversionDataType to, const char* suffix)
9025 {
9026         const string fullSuffix(suffix == DE_NULL ? "" : string("_") + string(suffix));
9027
9028         return getTypeName(from) + "_to_" + getTypeName(to) + fullSuffix;
9029 }
9030
9031 const string getAsmTypeName (ConversionDataType type)
9032 {
9033         string prefix;
9034
9035         if              (isInt(type))                                           prefix = isSigned(type) ? "i" : "u";
9036         else if (isFloat(type))                                         prefix = "f";
9037         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9038         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "v2i32";
9039         else                                                                            DE_ASSERT(false);
9040
9041         return prefix + getBitWidthStr(type);
9042 }
9043
9044 template<typename T>
9045 BufferSp getSpecializedBuffer (deInt64 number)
9046 {
9047         return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
9048 }
9049
9050 BufferSp getBuffer (ConversionDataType type, deInt64 number)
9051 {
9052         switch (type)
9053         {
9054                 case DATA_TYPE_SIGNED_8:                return getSpecializedBuffer<deInt8>(number);
9055                 case DATA_TYPE_SIGNED_16:               return getSpecializedBuffer<deInt16>(number);
9056                 case DATA_TYPE_SIGNED_32:               return getSpecializedBuffer<deInt32>(number);
9057                 case DATA_TYPE_SIGNED_64:               return getSpecializedBuffer<deInt64>(number);
9058                 case DATA_TYPE_UNSIGNED_8:              return getSpecializedBuffer<deUint8>(number);
9059                 case DATA_TYPE_UNSIGNED_16:             return getSpecializedBuffer<deUint16>(number);
9060                 case DATA_TYPE_UNSIGNED_32:             return getSpecializedBuffer<deUint32>(number);
9061                 case DATA_TYPE_UNSIGNED_64:             return getSpecializedBuffer<deUint64>(number);
9062                 case DATA_TYPE_FLOAT_16:                return getSpecializedBuffer<deUint16>(number);
9063                 case DATA_TYPE_FLOAT_32:                return getSpecializedBuffer<deUint32>(number);
9064                 case DATA_TYPE_FLOAT_64:                return getSpecializedBuffer<deUint64>(number);
9065                 case DATA_TYPE_VEC2_SIGNED_16:  return getSpecializedBuffer<deUint32>(number);
9066                 case DATA_TYPE_VEC2_SIGNED_32:  return getSpecializedBuffer<deUint64>(number);
9067
9068                 default:                                                TCU_THROW(InternalError, "Unimplemented type passed");
9069         }
9070 }
9071
9072 bool usesInt8 (ConversionDataType from, ConversionDataType to)
9073 {
9074         return (from == DATA_TYPE_SIGNED_8 || to == DATA_TYPE_SIGNED_8 ||
9075                         from == DATA_TYPE_UNSIGNED_8 || to == DATA_TYPE_UNSIGNED_8);
9076 }
9077
9078 bool usesInt16 (ConversionDataType from, ConversionDataType to)
9079 {
9080         return (from == DATA_TYPE_SIGNED_16 || to == DATA_TYPE_SIGNED_16 ||
9081                         from == DATA_TYPE_UNSIGNED_16 || to == DATA_TYPE_UNSIGNED_16 ||
9082                         from == DATA_TYPE_VEC2_SIGNED_16 || to == DATA_TYPE_VEC2_SIGNED_16);
9083 }
9084
9085 bool usesInt32 (ConversionDataType from, ConversionDataType to)
9086 {
9087         return (from == DATA_TYPE_SIGNED_32 || to == DATA_TYPE_SIGNED_32 ||
9088                         from == DATA_TYPE_UNSIGNED_32 || to == DATA_TYPE_UNSIGNED_32 ||
9089                         from == DATA_TYPE_VEC2_SIGNED_32|| to == DATA_TYPE_VEC2_SIGNED_32);
9090 }
9091
9092 bool usesInt64 (ConversionDataType from, ConversionDataType to)
9093 {
9094         return (from == DATA_TYPE_SIGNED_64 || to == DATA_TYPE_SIGNED_64 ||
9095                         from == DATA_TYPE_UNSIGNED_64 || to == DATA_TYPE_UNSIGNED_64);
9096 }
9097
9098 bool usesFloat16 (ConversionDataType from, ConversionDataType to)
9099 {
9100         return (from == DATA_TYPE_FLOAT_16 || to == DATA_TYPE_FLOAT_16);
9101 }
9102
9103 bool usesFloat32 (ConversionDataType from, ConversionDataType to)
9104 {
9105         return (from == DATA_TYPE_FLOAT_32 || to == DATA_TYPE_FLOAT_32);
9106 }
9107
9108 bool usesFloat64 (ConversionDataType from, ConversionDataType to)
9109 {
9110         return (from == DATA_TYPE_FLOAT_64 || to == DATA_TYPE_FLOAT_64);
9111 }
9112
9113 void getVulkanFeaturesAndExtensions (ConversionDataType from, ConversionDataType to, VulkanFeatures& vulkanFeatures, vector<string>& extensions)
9114 {
9115         if (usesInt16(from, to) && !usesInt32(from, to))
9116                 vulkanFeatures.coreFeatures.shaderInt16 = DE_TRUE;
9117
9118         if (usesInt64(from, to))
9119                 vulkanFeatures.coreFeatures.shaderInt64 = DE_TRUE;
9120
9121         if (usesFloat64(from, to))
9122                 vulkanFeatures.coreFeatures.shaderFloat64 = DE_TRUE;
9123
9124         if (usesInt16(from, to) || usesFloat16(from, to))
9125         {
9126                 extensions.push_back("VK_KHR_16bit_storage");
9127                 vulkanFeatures.ext16BitStorage |= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
9128         }
9129
9130         if (usesFloat16(from, to) || usesInt8(from, to))
9131         {
9132                 extensions.push_back("VK_KHR_shader_float16_int8");
9133
9134                 if (usesFloat16(from, to))
9135                 {
9136                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
9137                 }
9138
9139                 if (usesInt8(from, to))
9140                 {
9141                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
9142
9143                         extensions.push_back("VK_KHR_8bit_storage");
9144                         vulkanFeatures.ext8BitStorage |= EXT8BITSTORAGEFEATURES_STORAGE_BUFFER;
9145                 }
9146         }
9147 }
9148
9149 struct ConvertCase
9150 {
9151         ConvertCase (const string& instruction, ConversionDataType from, ConversionDataType to, deInt64 number, bool separateOutput = false, deInt64 outputNumber = 0, const char* suffix = DE_NULL)
9152         : m_fromType            (from)
9153         , m_toType                      (to)
9154         , m_name                        (getTestName(from, to, suffix))
9155         , m_inputBuffer         (getBuffer(from, number))
9156         {
9157                 string caps;
9158                 string decl;
9159                 string exts;
9160
9161                 m_asmTypes["inputType"]         = getAsmTypeName(from);
9162                 m_asmTypes["outputType"]        = getAsmTypeName(to);
9163
9164                 if (separateOutput)
9165                         m_outputBuffer = getBuffer(to, outputNumber);
9166                 else
9167                         m_outputBuffer = getBuffer(to, number);
9168
9169                 if (usesInt8(from, to))
9170                 {
9171                         bool requiresInt8Capability = true;
9172                         if (instruction == "OpUConvert" || instruction == "OpSConvert")
9173                         {
9174                                 // Conversions between 8 and 32 bit are provided by SPV_KHR_8bit_storage. The rest requires explicit Int8
9175                                 if (usesInt32(from, to))
9176                                         requiresInt8Capability = false;
9177                         }
9178
9179                         caps += "OpCapability StorageBuffer8BitAccess\n";
9180                         if (requiresInt8Capability)
9181                                 caps += "OpCapability Int8\n";
9182
9183                         decl += "%i8         = OpTypeInt 8 1\n"
9184                                         "%u8         = OpTypeInt 8 0\n";
9185                         exts += "OpExtension \"SPV_KHR_8bit_storage\"\n";
9186                 }
9187
9188                 if (usesInt16(from, to))
9189                 {
9190                         bool requiresInt16Capability = true;
9191
9192                         if (instruction == "OpUConvert" || instruction == "OpSConvert" || instruction == "OpFConvert")
9193                         {
9194                                 // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9195                                 if (usesInt32(from, to) || usesFloat32(from, to))
9196                                         requiresInt16Capability = false;
9197                         }
9198
9199                         decl += "%i16        = OpTypeInt 16 1\n"
9200                                         "%u16        = OpTypeInt 16 0\n"
9201                                         "%i16vec2    = OpTypeVector %i16 2\n";
9202
9203                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9204                         if (requiresInt16Capability)
9205                                 caps += "OpCapability Int16\n";
9206                 }
9207
9208                 if (usesFloat16(from, to))
9209                 {
9210                         decl += "%f16        = OpTypeFloat 16\n";
9211
9212                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Float16
9213                         if (!(usesInt32(from, to) || usesFloat32(from, to)))
9214                                 caps += "OpCapability Float16\n";
9215                 }
9216
9217                 if (usesInt16(from, to) || usesFloat16(from, to))
9218                 {
9219                         caps += "OpCapability StorageUniformBufferBlock16\n";
9220                         exts += "OpExtension \"SPV_KHR_16bit_storage\"\n";
9221                 }
9222
9223                 if (usesInt64(from, to))
9224                 {
9225                         caps += "OpCapability Int64\n";
9226                         decl += "%i64        = OpTypeInt 64 1\n"
9227                                         "%u64        = OpTypeInt 64 0\n";
9228                 }
9229
9230                 if (usesFloat64(from, to))
9231                 {
9232                         caps += "OpCapability Float64\n";
9233                         decl += "%f64        = OpTypeFloat 64\n";
9234                 }
9235
9236                 m_asmTypes["datatype_capabilities"]             = caps;
9237                 m_asmTypes["datatype_additional_decl"]  = decl;
9238                 m_asmTypes["datatype_extensions"]               = exts;
9239         }
9240
9241         ConversionDataType              m_fromType;
9242         ConversionDataType              m_toType;
9243         string                                  m_name;
9244         map<string, string>             m_asmTypes;
9245         BufferSp                                m_inputBuffer;
9246         BufferSp                                m_outputBuffer;
9247 };
9248
9249 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
9250 {
9251         map<string, string> params = convertCase.m_asmTypes;
9252
9253         params["instruction"]   = instruction;
9254         params["inDecorator"]   = getByteWidthStr(convertCase.m_fromType);
9255         params["outDecorator"]  = getByteWidthStr(convertCase.m_toType);
9256
9257         const StringTemplate shader (
9258                 "OpCapability Shader\n"
9259                 "${datatype_capabilities}"
9260                 "${datatype_extensions:opt}"
9261                 "OpMemoryModel Logical GLSL450\n"
9262                 "OpEntryPoint GLCompute %main \"main\"\n"
9263                 "OpExecutionMode %main LocalSize 1 1 1\n"
9264                 "OpSource GLSL 430\n"
9265                 "OpName %main           \"main\"\n"
9266                 // Decorators
9267                 "OpDecorate %indata DescriptorSet 0\n"
9268                 "OpDecorate %indata Binding 0\n"
9269                 "OpDecorate %outdata DescriptorSet 0\n"
9270                 "OpDecorate %outdata Binding 1\n"
9271                 "OpDecorate %in_buf BufferBlock\n"
9272                 "OpDecorate %out_buf BufferBlock\n"
9273                 "OpMemberDecorate %in_buf 0 Offset 0\n"
9274                 "OpMemberDecorate %out_buf 0 Offset 0\n"
9275                 // Base types
9276                 "%void       = OpTypeVoid\n"
9277                 "%voidf      = OpTypeFunction %void\n"
9278                 "%u32        = OpTypeInt 32 0\n"
9279                 "%i32        = OpTypeInt 32 1\n"
9280                 "%f32        = OpTypeFloat 32\n"
9281                 "%v2i32      = OpTypeVector %i32 2\n"
9282                 "${datatype_additional_decl}"
9283                 "%uvec3      = OpTypeVector %u32 3\n"
9284                 // Derived types
9285                 "%in_ptr     = OpTypePointer Uniform %${inputType}\n"
9286                 "%out_ptr    = OpTypePointer Uniform %${outputType}\n"
9287                 "%in_buf     = OpTypeStruct %${inputType}\n"
9288                 "%out_buf    = OpTypeStruct %${outputType}\n"
9289                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
9290                 "%out_bufptr = OpTypePointer Uniform %out_buf\n"
9291                 "%indata     = OpVariable %in_bufptr Uniform\n"
9292                 "%outdata    = OpVariable %out_bufptr Uniform\n"
9293                 // Constants
9294                 "%zero       = OpConstant %i32 0\n"
9295                 // Main function
9296                 "%main       = OpFunction %void None %voidf\n"
9297                 "%label      = OpLabel\n"
9298                 "%inloc      = OpAccessChain %in_ptr %indata %zero\n"
9299                 "%outloc     = OpAccessChain %out_ptr %outdata %zero\n"
9300                 "%inval      = OpLoad %${inputType} %inloc\n"
9301                 "%conv       = ${instruction} %${outputType} %inval\n"
9302                 "              OpStore %outloc %conv\n"
9303                 "              OpReturn\n"
9304                 "              OpFunctionEnd\n"
9305         );
9306
9307         return shader.specialize(params);
9308 }
9309
9310 void createConvertCases (vector<ConvertCase>& testCases, const string& instruction)
9311 {
9312         if (instruction == "OpUConvert")
9313         {
9314                 // Convert unsigned int to unsigned int
9315                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_16,          42));
9316                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_32,          73));
9317                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_64,          121));
9318
9319                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_8,           33));
9320                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_32,          60653));
9321                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_64,          17991));
9322
9323                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_64,          904256275));
9324                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_16,          6275));
9325                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_8,           17));
9326
9327                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_32,          701256243));
9328                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_16,          4741));
9329                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_8,           65));
9330         }
9331         else if (instruction == "OpSConvert")
9332         {
9333                 // Sign extension int->int
9334                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_16,            -30));
9335                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_32,            55));
9336                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_64,            -3));
9337                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_32,            14669));
9338                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_64,            -3341));
9339                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_64,            973610259));
9340
9341                 // Truncate for int->int
9342                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_8,                     81));
9343                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_8,                     -93));
9344                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_8,                     3182748172687672ll,                                     true,   56));
9345                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_16,            12382));
9346                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_32,            -972812359));
9347                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_16,            -1067742499291926803ll,                         true,   -4371));
9348
9349                 // Sign extension for int->uint
9350                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_16,          56));
9351                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_32,          -47,                                                            true,   4294967249u));
9352                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_64,          -5,                                                                     true,   18446744073709551611ull));
9353                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_32,          14669));
9354                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_64,          -3341,                                                          true,   18446744073709548275ull));
9355                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_64,          973610259));
9356
9357                 // Truncate for int->uint
9358                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_8,           -25711,                                                         true,   145));
9359                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_8,           103));
9360                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_8,           -1067742499291926803ll,                         true,   61165));
9361                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_16,          12382));
9362                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_32,          -972812359,                                                     true,   3322154937u));
9363                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_16,          -1067742499291926803ll,                         true,   61165));
9364
9365                 // Sign extension for uint->int
9366                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_16,            71));
9367                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_32,            201,                                                            true,   -55));
9368                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_64,            188,                                                            true,   -68));
9369                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_32,            14669));
9370                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_64,            62195,                                                          true,   -3341));
9371                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_64,            973610259));
9372
9373                 // Truncate for uint->int
9374                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_8,                     67));
9375                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_8,                     133,                                                            true,   -123));
9376                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_8,                     836927654193256494ull,                          true,   46));
9377                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_16,            12382));
9378                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_32,            18446744072736739257ull,                        true,   -972812359));
9379                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_16,            17379001574417624813ull,                        true,   -4371));
9380
9381                 // Convert i16vec2 to i32vec2 and vice versa
9382                 // Unsigned values are used here to represent negative signed values and to allow defined shifting behaviour.
9383                 // The actual signed value -32123 is used here as uint16 value 33413 and uint32 value 4294935173
9384                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_16,       DATA_TYPE_VEC2_SIGNED_32,       (33413u << 16)                  | 27593,        true,   (4294935173ull << 32)   | 27593));
9385                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_32,       DATA_TYPE_VEC2_SIGNED_16,       (4294935173ull << 32)   | 27593,        true,   (33413u << 16)                  | 27593));
9386         }
9387         else if (instruction == "OpFConvert")
9388         {
9389                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9390                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_64,                     0x449a4000,                                                     true,   0x4093480000000000));
9391                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_32,                     0x4093480000000000,                                     true,   0x449a4000));
9392
9393                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_16,                     0x449a4000,                                                     true,   0x64D2));
9394                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_32,                     0x64D2,                                                         true,   0x449a4000));
9395
9396                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_64,                     0x64D2,                                                         true,   0x4093480000000000));
9397                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_16,                     0x4093480000000000,                                     true,   0x64D2));
9398         }
9399         else if (instruction == "OpConvertFToU")
9400         {
9401                 // Normal numbers from uint8 range
9402                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5020,                                                         true,   33,                                                                     "33"));
9403                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x42280000,                                                     true,   42,                                                                     "42"));
9404                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x4067800000000000ull,                          true,   188,                                                            "188"));
9405
9406                 // Maximum uint8 value
9407                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5BF8,                                                         true,   255,                                                            "max"));
9408                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x437F0000,                                                     true,   255,                                                            "max"));
9409                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x406FE00000000000ull,                          true,   255,                                                            "max"));
9410
9411                 // +0
9412                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x0000,                                                         true,   0,                                                                      "p0"));
9413                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x00000000,                                                     true,   0,                                                                      "p0"));
9414                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9415
9416                 // -0
9417                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x8000,                                                         true,   0,                                                                      "m0"));
9418                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x80000000,                                                     true,   0,                                                                      "m0"));
9419                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9420
9421                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9422                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x64D2,                                                         true,   1234,                                                           "1234"));
9423                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x64D2,                                                         true,   1234,                                                           "1234"));
9424                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x64D2,                                                         true,   1234,                                                           "1234"));
9425
9426                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9427                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x7BFF,                                                         true,   65504,                                                          "max"));
9428                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x7BFF,                                                         true,   65504,                                                          "max"));
9429                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x7BFF,                                                         true,   65504,                                                          "max"));
9430
9431                 // +0
9432                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x0000,                                                         true,   0,                                                                      "p0"));
9433                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x0000,                                                         true,   0,                                                                      "p0"));
9434                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x0000,                                                         true,   0,                                                                      "p0"));
9435
9436                 // -0
9437                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x8000,                                                         true,   0,                                                                      "m0"));
9438                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x8000,                                                         true,   0,                                                                      "m0"));
9439                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x8000,                                                         true,   0,                                                                      "m0"));
9440
9441                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_16,          0x449a4000,                                                     true,   1234));
9442                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_32,          0x449a4000,                                                     true,   1234));
9443                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_64,          0x449a4000,                                                     true,   1234));
9444                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_16,          0x4093480000000000,                                     true,   1234));
9445                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_32,          0x4093480000000000,                                     true,   1234));
9446                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_64,          0x4093480000000000,                                     true,   1234));
9447         }
9448         else if (instruction == "OpConvertUToF")
9449         {
9450                 // Normal numbers from uint8 range
9451                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     116,                                                            true,   0x5740,                                                         "116"));
9452                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     232,                                                            true,   0x43680000,                                                     "232"));
9453                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     164,                                                            true,   0x4064800000000000ull,                          "164"));
9454
9455                 // Maximum uint8 value
9456                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     255,                                                            true,   0x5BF8,                                                         "max"));
9457                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     255,                                                            true,   0x437F0000,                                                     "max"));
9458                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     255,                                                            true,   0x406FE00000000000ull,                          "max"));
9459
9460                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9461                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9462                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9463                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9464
9465                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9466                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9467                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9468                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9469
9470                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9471                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9472                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9473                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9474                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9475                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9476         }
9477         else if (instruction == "OpConvertFToS")
9478         {
9479                 // Normal numbers from int8 range
9480                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xC980,                                                         true,   -11,                                                            "m11"));
9481                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC2140000,                                                     true,   -37,                                                            "m37"));
9482                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC050800000000000ull,                          true,   -66,                                                            "m66"));
9483
9484                 // Minimum int8 value
9485                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xD800,                                                         true,   -128,                                                           "min"));
9486                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC3000000,                                                     true,   -128,                                                           "min"));
9487                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC060000000000000ull,                          true,   -128,                                                           "min"));
9488
9489                 // Maximum int8 value
9490                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x57F0,                                                         true,   127,                                                            "max"));
9491                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x42FE0000,                                                     true,   127,                                                            "max"));
9492                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x405FC00000000000ull,                          true,   127,                                                            "max"));
9493
9494                 // +0
9495                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x0000,                                                         true,   0,                                                                      "p0"));
9496                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x00000000,                                                     true,   0,                                                                      "p0"));
9497                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9498
9499                 // -0
9500                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x8000,                                                         true,   0,                                                                      "m0"));
9501                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x80000000,                                                     true,   0,                                                                      "m0"));
9502                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9503
9504                 // All hexadecimal values below represent -1234.0 as 32/64-bit IEEE 754 float
9505                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9506                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9507                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9508
9509                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9510                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xF800,                                                         true,   -32768,                                                         "min"));
9511                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xF800,                                                         true,   -32768,                                                         "min"));
9512                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xF800,                                                         true,   -32768,                                                         "min"));
9513
9514                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9515                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x77FF,                                                         true,   32752,                                                          "max"));
9516                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x77FF,                                                         true,   32752,                                                          "max"));
9517                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x77FF,                                                         true,   32752,                                                          "max"));
9518
9519                 // +0
9520                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x0000,                                                         true,   0,                                                                      "p0"));
9521                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x0000,                                                         true,   0,                                                                      "p0"));
9522                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x0000,                                                         true,   0,                                                                      "p0"));
9523
9524                 // -0
9525                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x8000,                                                         true,   0,                                                                      "m0"));
9526                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x8000,                                                         true,   0,                                                                      "m0"));
9527                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x8000,                                                         true,   0,                                                                      "m0"));
9528
9529                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc49a4000,                                                     true,   -1234));
9530                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_32,            0xc49a4000,                                                     true,   -1234));
9531                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_64,            0xc49a4000,                                                     true,   -1234));
9532                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_16,            0xc093480000000000,                                     true,   -1234));
9533                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_32,            0xc093480000000000,                                     true,   -1234));
9534                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_64,            0xc093480000000000,                                     true,   -1234));
9535                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0x453b9000,                                                     true,    3001,                                                          "p3001"));
9536                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc53b9000,                                                     true,   -3001,                                                          "m3001"));
9537         }
9538         else if (instruction == "OpConvertSToF")
9539         {
9540                 // Normal numbers from int8 range
9541                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -12,                                                            true,   0xCA00,                                                         "m21"));
9542                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -21,                                                            true,   0xC1A80000,                                                     "m21"));
9543                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -99,                                                            true,   0xC058C00000000000ull,                          "m99"));
9544
9545                 // Minimum int8 value
9546                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -128,                                                           true,   0xD800,                                                         "min"));
9547                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -128,                                                           true,   0xC3000000,                                                     "min"));
9548                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -128,                                                           true,   0xC060000000000000ull,                          "min"));
9549
9550                 // Maximum int8 value
9551                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     127,                                                            true,   0x57F0,                                                         "max"));
9552                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     127,                                                            true,   0x42FE0000,                                                     "max"));
9553                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     127,                                                            true,   0x405FC00000000000ull,                          "max"));
9554
9555                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9556                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9557                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9558                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9559
9560                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9561                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9562                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9563                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9564
9565                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9566                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9567                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9568                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9569
9570                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9571                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9572                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9573                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9574                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9575                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9576         }
9577         else
9578                 DE_FATAL("Unknown instruction");
9579 }
9580
9581 const map<string, string> getConvertCaseFragments (string instruction, const ConvertCase& convertCase)
9582 {
9583         map<string, string> params = convertCase.m_asmTypes;
9584         map<string, string> fragments;
9585
9586         params["instruction"] = instruction;
9587         params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
9588
9589         const StringTemplate decoration (
9590                 "      OpDecorate %SSBOi DescriptorSet 0\n"
9591                 "      OpDecorate %SSBOo DescriptorSet 0\n"
9592                 "      OpDecorate %SSBOi Binding 0\n"
9593                 "      OpDecorate %SSBOo Binding 1\n"
9594                 "      OpDecorate %s_SSBOi Block\n"
9595                 "      OpDecorate %s_SSBOo Block\n"
9596                 "OpMemberDecorate %s_SSBOi 0 Offset 0\n"
9597                 "OpMemberDecorate %s_SSBOo 0 Offset 0\n");
9598
9599         const StringTemplate pre_main (
9600                 "${datatype_additional_decl:opt}"
9601                 "    %ptr_in = OpTypePointer StorageBuffer %${inputType}\n"
9602                 "   %ptr_out = OpTypePointer StorageBuffer %${outputType}\n"
9603                 "   %s_SSBOi = OpTypeStruct %${inputType}\n"
9604                 "   %s_SSBOo = OpTypeStruct %${outputType}\n"
9605                 " %ptr_SSBOi = OpTypePointer StorageBuffer %s_SSBOi\n"
9606                 " %ptr_SSBOo = OpTypePointer StorageBuffer %s_SSBOo\n"
9607                 "     %SSBOi = OpVariable %ptr_SSBOi StorageBuffer\n"
9608                 "     %SSBOo = OpVariable %ptr_SSBOo StorageBuffer\n");
9609
9610         const StringTemplate testfun (
9611                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9612                 "%param     = OpFunctionParameter %v4f32\n"
9613                 "%label     = OpLabel\n"
9614                 "%iLoc      = OpAccessChain %ptr_in %SSBOi %c_u32_0\n"
9615                 "%oLoc      = OpAccessChain %ptr_out %SSBOo %c_u32_0\n"
9616                 "%valIn     = OpLoad %${inputType} %iLoc\n"
9617                 "%valOut    = ${instruction} %${outputType} %valIn\n"
9618                 "             OpStore %oLoc %valOut\n"
9619                 "             OpReturnValue %param\n"
9620                 "             OpFunctionEnd\n");
9621
9622         params["datatype_extensions"] =
9623                 params["datatype_extensions"] +
9624                 "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n";
9625
9626         fragments["capability"] = params["datatype_capabilities"];
9627         fragments["extension"]  = params["datatype_extensions"];
9628         fragments["decoration"] = decoration.specialize(params);
9629         fragments["pre_main"]   = pre_main.specialize(params);
9630         fragments["testfun"]    = testfun.specialize(params);
9631
9632         return fragments;
9633 }
9634
9635 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in compute shaders
9636 tcu::TestCaseGroup* createConvertComputeTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9637 {
9638         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9639         vector<ConvertCase>                                     testCases;
9640         createConvertCases(testCases, instruction);
9641
9642         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9643         {
9644                 ComputeShaderSpec spec;
9645                 spec.assembly                   = getConvertCaseShaderStr(instruction, *test);
9646                 spec.numWorkGroups              = IVec3(1, 1, 1);
9647                 spec.inputs.push_back   (test->m_inputBuffer);
9648                 spec.outputs.push_back  (test->m_outputBuffer);
9649
9650                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, spec.requestedVulkanFeatures, spec.extensions);
9651
9652                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "", spec));
9653         }
9654         return group.release();
9655 }
9656
9657 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in graphics shaders
9658 tcu::TestCaseGroup* createConvertGraphicsTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9659 {
9660         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9661         vector<ConvertCase>                                     testCases;
9662         createConvertCases(testCases, instruction);
9663
9664         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9665         {
9666                 map<string, string>     fragments               = getConvertCaseFragments(instruction, *test);
9667                 VulkanFeatures          vulkanFeatures;
9668                 GraphicsResources       resources;
9669                 vector<string>          extensions;
9670                 SpecConstants           noSpecConstants;
9671                 PushConstants           noPushConstants;
9672                 GraphicsInterfaces      noInterfaces;
9673                 tcu::RGBA                       defaultColors[4];
9674
9675                 getDefaultColors                        (defaultColors);
9676                 resources.inputs.push_back      (Resource(test->m_inputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9677                 resources.outputs.push_back     (Resource(test->m_outputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9678                 extensions.push_back            ("VK_KHR_storage_buffer_storage_class");
9679
9680                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, vulkanFeatures, extensions);
9681
9682                 vulkanFeatures.coreFeatures.vertexPipelineStoresAndAtomics      = true;
9683                 vulkanFeatures.coreFeatures.fragmentStoresAndAtomics            = true;
9684
9685                 createTestsForAllStages(
9686                         test->m_name, defaultColors, defaultColors, fragments, noSpecConstants,
9687                         noPushConstants, resources, noInterfaces, extensions, vulkanFeatures, group.get());
9688         }
9689         return group.release();
9690 }
9691
9692 // Constant-Creation Instructions: OpConstant, OpConstantComposite
9693 tcu::TestCaseGroup* createOpConstantFloat16Tests(tcu::TestContext& testCtx)
9694 {
9695         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstant", "OpConstant and OpConstantComposite instruction"));
9696         RGBA                                                    inputColors[4];
9697         RGBA                                                    outputColors[4];
9698         vector<string>                                  extensions;
9699         GraphicsResources                               resources;
9700         VulkanFeatures                                  features;
9701
9702         const char                                              functionStart[]  =
9703                 "%test_code             = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9704                 "%param1                = OpFunctionParameter %v4f32\n"
9705                 "%lbl                   = OpLabel\n";
9706
9707         const char                                              functionEnd[]           =
9708                 "%transformed_param_32  = OpFConvert %v4f32 %transformed_param\n"
9709                 "                         OpReturnValue %transformed_param_32\n"
9710                 "                         OpFunctionEnd\n";
9711
9712         struct NameConstantsCode
9713         {
9714                 string name;
9715                 string constants;
9716                 string code;
9717         };
9718
9719 #define FLOAT_16_COMMON_TYPES_AND_CONSTS \
9720                         "%f16                  = OpTypeFloat 16\n"                                                 \
9721                         "%c_f16_0              = OpConstant %f16 0.0\n"                                            \
9722                         "%c_f16_0_5            = OpConstant %f16 0.5\n"                                            \
9723                         "%c_f16_1              = OpConstant %f16 1.0\n"                                            \
9724                         "%v4f16                = OpTypeVector %f16 4\n"                                            \
9725                         "%fp_f16               = OpTypePointer Function %f16\n"                                    \
9726                         "%fp_v4f16             = OpTypePointer Function %v4f16\n"                                  \
9727                         "%c_v4f16_1_1_1_1      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n" \
9728                         "%a4f16                = OpTypeArray %f16 %c_u32_4\n"                                      \
9729
9730         NameConstantsCode                               tests[] =
9731         {
9732                 {
9733                         "vec4",
9734
9735                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9736                         "%cval                 = OpConstantComposite %v4f16 %c_f16_0_5 %c_f16_0_5 %c_f16_0_5 %c_f16_0\n",
9737                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9738                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %cval\n"
9739                 },
9740                 {
9741                         "struct",
9742
9743                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9744                         "%stype                = OpTypeStruct %v4f16 %f16\n"
9745                         "%fp_stype             = OpTypePointer Function %stype\n"
9746                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9747                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9748                         "%cvec                 = OpConstantComposite %v4f16 %f16_1_5 %f16_1_5 %f16_1_5 %c_f16_1\n"
9749                         "%cval                 = OpConstantComposite %stype %cvec %f16_n_1\n",
9750
9751                         "%v                    = OpVariable %fp_stype Function %cval\n"
9752                         "%vec_ptr              = OpAccessChain %fp_v4f16 %v %c_u32_0\n"
9753                         "%f16_ptr              = OpAccessChain %fp_f16 %v %c_u32_1\n"
9754                         "%vec_val              = OpLoad %v4f16 %vec_ptr\n"
9755                         "%f16_val              = OpLoad %f16 %f16_ptr\n"
9756                         "%tmp1                 = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_1 %f16_val\n" // vec4(-1)
9757                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9758                         "%tmp2                 = OpFAdd %v4f16 %tmp1 %param1_16\n" // param1 + vec4(-1)
9759                         "%transformed_param    = OpFAdd %v4f16 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
9760                 },
9761                 {
9762                         // [1|0|0|0.5] [x] = x + 0.5
9763                         // [0|1|0|0.5] [y] = y + 0.5
9764                         // [0|0|1|0.5] [z] = z + 0.5
9765                         // [0|0|0|1  ] [1] = 1
9766                         "matrix",
9767
9768                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9769                         "%mat4x4_f16           = OpTypeMatrix %v4f16 4\n"
9770                         "%v4f16_1_0_0_0        = OpConstantComposite %v4f16 %c_f16_1 %c_f16_0 %c_f16_0 %c_f16_0\n"
9771                         "%v4f16_0_1_0_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_1 %c_f16_0 %c_f16_0\n"
9772                         "%v4f16_0_0_1_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_1 %c_f16_0\n"
9773                         "%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"
9774                         "%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",
9775
9776                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9777                         "%transformed_param    = OpMatrixTimesVector %v4f16 %cval %param1_16\n"
9778                 },
9779                 {
9780                         "array",
9781
9782                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9783                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9784                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9785                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9786                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9787                         "%carr                 = OpConstantComposite %a4f16 %c_f16_0 %f16_n_1 %f16_1_5 %c_f16_0\n",
9788
9789                         "%v                    = OpVariable %fp_a4f16 Function %carr\n"
9790                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_0\n"
9791                         "%f1                   = OpAccessChain %fp_f16 %v %c_u32_1\n"
9792                         "%f2                   = OpAccessChain %fp_f16 %v %c_u32_2\n"
9793                         "%f3                   = OpAccessChain %fp_f16 %v %c_u32_3\n"
9794                         "%f_val                = OpLoad %f16 %f\n"
9795                         "%f1_val               = OpLoad %f16 %f1\n"
9796                         "%f2_val               = OpLoad %f16 %f2\n"
9797                         "%f3_val               = OpLoad %f16 %f3\n"
9798                         "%ftot1                = OpFAdd %f16 %f_val %f1_val\n"
9799                         "%ftot2                = OpFAdd %f16 %ftot1 %f2_val\n"
9800                         "%ftot3                = OpFAdd %f16 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
9801                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %ftot3\n"
9802                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9803                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
9804                 },
9805                 {
9806                         //
9807                         // [
9808                         //   {
9809                         //      0.0,
9810                         //      [ 1.0, 1.0, 1.0, 1.0]
9811                         //   },
9812                         //   {
9813                         //      1.0,
9814                         //      [ 0.0, 0.5, 0.0, 0.0]
9815                         //   }, //     ^^^
9816                         //   {
9817                         //      0.0,
9818                         //      [ 1.0, 1.0, 1.0, 1.0]
9819                         //   }
9820                         // ]
9821                         "array_of_struct_of_array",
9822
9823                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9824                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9825                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9826                         "%stype                = OpTypeStruct %f16 %a4f16\n"
9827                         "%a3stype              = OpTypeArray %stype %c_u32_3\n"
9828                         "%fp_a3stype           = OpTypePointer Function %a3stype\n"
9829                         "%ca4f16_0             = OpConstantComposite %a4f16 %c_f16_0 %c_f16_0_5 %c_f16_0 %c_f16_0\n"
9830                         "%ca4f16_1             = OpConstantComposite %a4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n"
9831                         "%cstype1              = OpConstantComposite %stype %c_f16_0 %ca4f16_1\n"
9832                         "%cstype2              = OpConstantComposite %stype %c_f16_1 %ca4f16_0\n"
9833                         "%carr                 = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
9834
9835                         "%v                    = OpVariable %fp_a3stype Function %carr\n"
9836                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
9837                         "%f_l                  = OpLoad %f16 %f\n"
9838                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %f_l\n"
9839                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9840                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
9841                 }
9842         };
9843
9844         getHalfColorsFullAlpha(inputColors);
9845         outputColors[0] = RGBA(255, 255, 255, 255);
9846         outputColors[1] = RGBA(255, 127, 127, 255);
9847         outputColors[2] = RGBA(127, 255, 127, 255);
9848         outputColors[3] = RGBA(127, 127, 255, 255);
9849
9850         extensions.push_back("VK_KHR_16bit_storage");
9851         extensions.push_back("VK_KHR_shader_float16_int8");
9852         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
9853
9854         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
9855         {
9856                 map<string, string> fragments;
9857
9858                 fragments["extension"]  = "OpExtension \"SPV_KHR_16bit_storage\"";
9859                 fragments["capability"] = "OpCapability Float16\n";
9860                 fragments["pre_main"]   = tests[testNdx].constants;
9861                 fragments["testfun"]    = string(functionStart) + tests[testNdx].code + functionEnd;
9862
9863                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, resources, extensions, opConstantCompositeTests.get(), features);
9864         }
9865         return opConstantCompositeTests.release();
9866 }
9867
9868 template<typename T>
9869 void finalizeTestsCreation (T&                                                  specResource,
9870                                                         const map<string, string>&      fragments,
9871                                                         tcu::TestContext&                       testCtx,
9872                                                         tcu::TestCaseGroup&                     testGroup,
9873                                                         const std::string&                      testName,
9874                                                         const VulkanFeatures&           vulkanFeatures,
9875                                                         const vector<string>&           extensions,
9876                                                         const IVec3&                            numWorkGroups);
9877
9878 template<>
9879 void finalizeTestsCreation (GraphicsResources&                  specResource,
9880                                                         const map<string, string>&      fragments,
9881                                                         tcu::TestContext&                       ,
9882                                                         tcu::TestCaseGroup&                     testGroup,
9883                                                         const std::string&                      testName,
9884                                                         const VulkanFeatures&           vulkanFeatures,
9885                                                         const vector<string>&           extensions,
9886                                                         const IVec3&                            )
9887 {
9888         RGBA defaultColors[4];
9889         getDefaultColors(defaultColors);
9890
9891         createTestsForAllStages(testName, defaultColors, defaultColors, fragments, specResource, extensions, &testGroup, vulkanFeatures);
9892 }
9893
9894 template<>
9895 void finalizeTestsCreation (ComputeShaderSpec&                  specResource,
9896                                                         const map<string, string>&      fragments,
9897                                                         tcu::TestContext&                       testCtx,
9898                                                         tcu::TestCaseGroup&                     testGroup,
9899                                                         const std::string&                      testName,
9900                                                         const VulkanFeatures&           vulkanFeatures,
9901                                                         const vector<string>&           extensions,
9902                                                         const IVec3&                            numWorkGroups)
9903 {
9904         specResource.numWorkGroups = numWorkGroups;
9905         specResource.requestedVulkanFeatures = vulkanFeatures;
9906         specResource.extensions = extensions;
9907
9908         specResource.assembly = makeComputeShaderAssembly(fragments);
9909
9910         testGroup.addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", specResource));
9911 }
9912
9913 template<class SpecResource>
9914 tcu::TestCaseGroup* createFloat16LogicalSet (tcu::TestContext& testCtx, const bool nanSupported)
9915 {
9916         const string                                            nan                                     = nanSupported ? "_nan" : "";
9917         const string                                            groupName                       = "logical" + nan;
9918         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Float 16 logical tests"));
9919
9920         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
9921         const string                                            spvCapabilities         = string("OpCapability StorageUniformBufferBlock16\n") + (nanSupported ? "OpCapability SignedZeroInfNanPreserve\n" : "");
9922         const string                                            spvExtensions           = string("OpExtension \"SPV_KHR_16bit_storage\"\n") + (nanSupported ? "OpExtension \"SPV_KHR_float_controls\"\n" : "");
9923         const string                                            spvExecutionMode        = nanSupported ? "OpExecutionMode %BP_main SignedZeroInfNanPreserve 16\n" : "";
9924         const deUint32                                          numDataPoints           = 16;
9925         const vector<deFloat16>                         float16Data                     = getFloat16s(rnd, numDataPoints);
9926         const vector<deFloat16>                         float16Data1            = squarize(float16Data, 0);
9927         const vector<deFloat16>                         float16Data2            = squarize(float16Data, 1);
9928         const vector<deFloat16>                         float16DataVec1         = squarizeVector(float16Data, 0);
9929         const vector<deFloat16>                         float16DataVec2         = squarizeVector(float16Data, 1);
9930         const vector<deFloat16>                         float16OutDummy         (float16Data1.size(), 0);
9931         const vector<deFloat16>                         float16OutVecDummy      (float16DataVec1.size(), 0);
9932
9933         struct TestOp
9934         {
9935                 const char*             opCode;
9936                 VerifyIOFunc    verifyFuncNan;
9937                 VerifyIOFunc    verifyFuncNonNan;
9938                 const deUint32  argCount;
9939         };
9940
9941         const TestOp    testOps[]       =
9942         {
9943                 { "OpIsNan"                                             ,       compareFP16Logical<fp16isNan,                           true,  false, true>,    compareFP16Logical<fp16isNan,                           true,  false, false>,   1       },
9944                 { "OpIsInf"                                             ,       compareFP16Logical<fp16isInf,                           true,  false, true>,    compareFP16Logical<fp16isInf,                           true,  false, false>,   1       },
9945                 { "OpFOrdEqual"                                 ,       compareFP16Logical<fp16isEqual,                         false, true,  true>,    compareFP16Logical<fp16isEqual,                         false, true,  false>,   2       },
9946                 { "OpFUnordEqual"                               ,       compareFP16Logical<fp16isEqual,                         false, false, true>,    compareFP16Logical<fp16isEqual,                         false, false, false>,   2       },
9947                 { "OpFOrdNotEqual"                              ,       compareFP16Logical<fp16isUnequal,                       false, true,  true>,    compareFP16Logical<fp16isUnequal,                       false, true,  false>,   2       },
9948                 { "OpFUnordNotEqual"                    ,       compareFP16Logical<fp16isUnequal,                       false, false, true>,    compareFP16Logical<fp16isUnequal,                       false, false, false>,   2       },
9949                 { "OpFOrdLessThan"                              ,       compareFP16Logical<fp16isLess,                          false, true,  true>,    compareFP16Logical<fp16isLess,                          false, true,  false>,   2       },
9950                 { "OpFUnordLessThan"                    ,       compareFP16Logical<fp16isLess,                          false, false, true>,    compareFP16Logical<fp16isLess,                          false, false, false>,   2       },
9951                 { "OpFOrdGreaterThan"                   ,       compareFP16Logical<fp16isGreater,                       false, true,  true>,    compareFP16Logical<fp16isGreater,                       false, true,  false>,   2       },
9952                 { "OpFUnordGreaterThan"                 ,       compareFP16Logical<fp16isGreater,                       false, false, true>,    compareFP16Logical<fp16isGreater,                       false, false, false>,   2       },
9953                 { "OpFOrdLessThanEqual"                 ,       compareFP16Logical<fp16isLessOrEqual,           false, true,  true>,    compareFP16Logical<fp16isLessOrEqual,           false, true,  false>,   2       },
9954                 { "OpFUnordLessThanEqual"               ,       compareFP16Logical<fp16isLessOrEqual,           false, false, true>,    compareFP16Logical<fp16isLessOrEqual,           false, false, false>,   2       },
9955                 { "OpFOrdGreaterThanEqual"              ,       compareFP16Logical<fp16isGreaterOrEqual,        false, true,  true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, true,  false>,   2       },
9956                 { "OpFUnordGreaterThanEqual"    ,       compareFP16Logical<fp16isGreaterOrEqual,        false, false, true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, false, false>,   2       },
9957         };
9958
9959         { // scalar cases
9960                 const StringTemplate preMain
9961                 (
9962                         "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
9963                         "      %f16 = OpTypeFloat 16\n"
9964                         "  %c_f16_0 = OpConstant %f16 0.0\n"
9965                         "  %c_f16_1 = OpConstant %f16 1.0\n"
9966                         "   %up_f16 = OpTypePointer Uniform %f16\n"
9967                         "   %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
9968                         "   %SSBO16 = OpTypeStruct %ra_f16\n"
9969                         "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
9970                         "%ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
9971                         "%ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
9972                         " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
9973                 );
9974
9975                 const StringTemplate decoration
9976                 (
9977                         "OpDecorate %ra_f16 ArrayStride 2\n"
9978                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
9979                         "OpDecorate %SSBO16 BufferBlock\n"
9980                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
9981                         "OpDecorate %ssbo_src0 Binding 0\n"
9982                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
9983                         "OpDecorate %ssbo_src1 Binding 1\n"
9984                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
9985                         "OpDecorate %ssbo_dst Binding 2\n"
9986                 );
9987
9988                 const StringTemplate testFun
9989                 (
9990                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9991                         "    %param = OpFunctionParameter %v4f32\n"
9992
9993                         "    %entry = OpLabel\n"
9994                         "        %i = OpVariable %fp_i32 Function\n"
9995                         "             OpStore %i %c_i32_0\n"
9996                         "             OpBranch %loop\n"
9997
9998                         "     %loop = OpLabel\n"
9999                         "    %i_cmp = OpLoad %i32 %i\n"
10000                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10001                         "             OpLoopMerge %merge %next None\n"
10002                         "             OpBranchConditional %lt %write %merge\n"
10003
10004                         "    %write = OpLabel\n"
10005                         "      %ndx = OpLoad %i32 %i\n"
10006
10007                         "     %src0 = OpAccessChain %up_f16 %ssbo_src0 %c_i32_0 %ndx\n"
10008                         " %val_src0 = OpLoad %f16 %src0\n"
10009
10010                         "${op_arg1_calc}"
10011
10012                         " %val_bdst = ${op_code} %bool %val_src0 ${op_arg1}\n"
10013                         "  %val_dst = OpSelect %f16 %val_bdst %c_f16_1 %c_f16_0\n"
10014                         "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10015                         "             OpStore %dst %val_dst\n"
10016                         "             OpBranch %next\n"
10017
10018                         "     %next = OpLabel\n"
10019                         "    %i_cur = OpLoad %i32 %i\n"
10020                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10021                         "             OpStore %i %i_new\n"
10022                         "             OpBranch %loop\n"
10023
10024                         "    %merge = OpLabel\n"
10025                         "             OpReturnValue %param\n"
10026
10027                         "             OpFunctionEnd\n"
10028                 );
10029
10030                 const StringTemplate arg1Calc
10031                 (
10032                         "     %src1 = OpAccessChain %up_f16 %ssbo_src1 %c_i32_0 %ndx\n"
10033                         " %val_src1 = OpLoad %f16 %src1\n"
10034                 );
10035
10036                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10037                 {
10038                         const size_t            iterations              = float16Data1.size();
10039                         const TestOp&           testOp                  = testOps[testOpsIdx];
10040                         const string            testName                = de::toLower(string(testOp.opCode)) + "_scalar";
10041                         SpecResource            specResource;
10042                         map<string, string>     specs;
10043                         VulkanFeatures          features;
10044                         map<string, string>     fragments;
10045                         vector<string>          extensions;
10046
10047                         specs["num_data_points"]        = de::toString(iterations);
10048                         specs["op_code"]                        = testOp.opCode;
10049                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10050                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10051
10052                         fragments["extension"]          = spvExtensions;
10053                         fragments["capability"]         = spvCapabilities;
10054                         fragments["execution_mode"]     = spvExecutionMode;
10055                         fragments["decoration"]         = decoration.specialize(specs);
10056                         fragments["pre_main"]           = preMain.specialize(specs);
10057                         fragments["testfun"]            = testFun.specialize(specs);
10058
10059                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10060                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10061                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10062                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10063
10064                         extensions.push_back("VK_KHR_16bit_storage");
10065                         extensions.push_back("VK_KHR_shader_float16_int8");
10066
10067                         if (nanSupported)
10068                         {
10069                                 extensions.push_back("VK_KHR_shader_float_controls");
10070
10071                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10072                         }
10073
10074                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10075                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10076
10077                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10078                 }
10079         }
10080         { // vector cases
10081                 const StringTemplate preMain
10082                 (
10083                         "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10084                         "     %v2bool = OpTypeVector %bool 2\n"
10085                         "        %f16 = OpTypeFloat 16\n"
10086                         "    %c_f16_0 = OpConstant %f16 0.0\n"
10087                         "    %c_f16_1 = OpConstant %f16 1.0\n"
10088                         "      %v2f16 = OpTypeVector %f16 2\n"
10089                         "%c_v2f16_0_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10090                         "%c_v2f16_1_1 = OpConstantComposite %v2f16 %c_f16_1 %c_f16_1\n"
10091                         "   %up_v2f16 = OpTypePointer Uniform %v2f16\n"
10092                         "   %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
10093                         "     %SSBO16 = OpTypeStruct %ra_v2f16\n"
10094                         "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10095                         "  %ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
10096                         "  %ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
10097                         "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10098                 );
10099
10100                 const StringTemplate decoration
10101                 (
10102                         "OpDecorate %ra_v2f16 ArrayStride 4\n"
10103                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
10104                         "OpDecorate %SSBO16 BufferBlock\n"
10105                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
10106                         "OpDecorate %ssbo_src0 Binding 0\n"
10107                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
10108                         "OpDecorate %ssbo_src1 Binding 1\n"
10109                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
10110                         "OpDecorate %ssbo_dst Binding 2\n"
10111                 );
10112
10113                 const StringTemplate testFun
10114                 (
10115                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10116                         "    %param = OpFunctionParameter %v4f32\n"
10117
10118                         "    %entry = OpLabel\n"
10119                         "        %i = OpVariable %fp_i32 Function\n"
10120                         "             OpStore %i %c_i32_0\n"
10121                         "             OpBranch %loop\n"
10122
10123                         "     %loop = OpLabel\n"
10124                         "    %i_cmp = OpLoad %i32 %i\n"
10125                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10126                         "             OpLoopMerge %merge %next None\n"
10127                         "             OpBranchConditional %lt %write %merge\n"
10128
10129                         "    %write = OpLabel\n"
10130                         "      %ndx = OpLoad %i32 %i\n"
10131
10132                         "     %src0 = OpAccessChain %up_v2f16 %ssbo_src0 %c_i32_0 %ndx\n"
10133                         " %val_src0 = OpLoad %v2f16 %src0\n"
10134
10135                         "${op_arg1_calc}"
10136
10137                         " %val_bdst = ${op_code} %v2bool %val_src0 ${op_arg1}\n"
10138                         "  %val_dst = OpSelect %v2f16 %val_bdst %c_v2f16_1_1 %c_v2f16_0_0\n"
10139                         "      %dst = OpAccessChain %up_v2f16 %ssbo_dst %c_i32_0 %ndx\n"
10140                         "             OpStore %dst %val_dst\n"
10141                         "             OpBranch %next\n"
10142
10143                         "     %next = OpLabel\n"
10144                         "    %i_cur = OpLoad %i32 %i\n"
10145                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10146                         "             OpStore %i %i_new\n"
10147                         "             OpBranch %loop\n"
10148
10149                         "    %merge = OpLabel\n"
10150                         "             OpReturnValue %param\n"
10151
10152                         "             OpFunctionEnd\n"
10153                 );
10154
10155                 const StringTemplate arg1Calc
10156                 (
10157                         "     %src1 = OpAccessChain %up_v2f16 %ssbo_src1 %c_i32_0 %ndx\n"
10158                         " %val_src1 = OpLoad %v2f16 %src1\n"
10159                 );
10160
10161                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10162                 {
10163                         const deUint32          itemsPerVec     = 2;
10164                         const size_t            iterations      = float16DataVec1.size() / itemsPerVec;
10165                         const TestOp&           testOp          = testOps[testOpsIdx];
10166                         const string            testName        = de::toLower(string(testOp.opCode)) + "_vector";
10167                         SpecResource            specResource;
10168                         map<string, string>     specs;
10169                         vector<string>          extensions;
10170                         VulkanFeatures          features;
10171                         map<string, string>     fragments;
10172
10173                         specs["num_data_points"]        = de::toString(iterations);
10174                         specs["op_code"]                        = testOp.opCode;
10175                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10176                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10177
10178                         fragments["extension"]          = spvExtensions;
10179                         fragments["capability"]         = spvCapabilities;
10180                         fragments["execution_mode"]     = spvExecutionMode;
10181                         fragments["decoration"]         = decoration.specialize(specs);
10182                         fragments["pre_main"]           = preMain.specialize(specs);
10183                         fragments["testfun"]            = testFun.specialize(specs);
10184
10185                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10186                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10187                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutVecDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10188                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10189
10190                         extensions.push_back("VK_KHR_16bit_storage");
10191                         extensions.push_back("VK_KHR_shader_float16_int8");
10192
10193                         if (nanSupported)
10194                         {
10195                                 extensions.push_back("VK_KHR_shader_float_controls");
10196
10197                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10198                         }
10199
10200                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10201                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10202
10203                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10204                 }
10205         }
10206
10207         return testGroup.release();
10208 }
10209
10210 bool compareFP16FunctionSetFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10211 {
10212         if (inputs.size() != 1 || outputAllocs.size() != 1)
10213                 return false;
10214
10215         vector<deUint8> input1Bytes;
10216
10217         inputs[0].getBytes(input1Bytes);
10218
10219         const deUint16* const   input1AsFP16    = (const deUint16*)&input1Bytes[0];
10220         const deUint16* const   outputAsFP16    = (const deUint16*)outputAllocs[0]->getHostPtr();
10221         std::string                             error;
10222
10223         for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deUint16); ++idx)
10224         {
10225                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
10226                 {
10227                         log << TestLog::Message << error << TestLog::EndMessage;
10228
10229                         return false;
10230                 }
10231         }
10232
10233         return true;
10234 }
10235
10236 template<class SpecResource>
10237 tcu::TestCaseGroup* createFloat16FuncSet (tcu::TestContext& testCtx)
10238 {
10239         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "function", "Float 16 function call related tests"));
10240
10241         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10242         const StringTemplate                            capabilities            ("OpCapability ${cap}\n");
10243         const deUint32                                          numDataPoints           = 256;
10244         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10245         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10246         map<string, string>                                     fragments;
10247
10248         struct TestType
10249         {
10250                 const deUint32  typeComponents;
10251                 const char*             typeName;
10252                 const char*             typeDecls;
10253         };
10254
10255         const TestType  testTypes[]     =
10256         {
10257                 {
10258                         1,
10259                         "f16",
10260                         ""
10261                 },
10262                 {
10263                         2,
10264                         "v2f16",
10265                         "      %v2f16 = OpTypeVector %f16 2\n"
10266                         "  %c_v2f16_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10267                 },
10268                 {
10269                         4,
10270                         "v4f16",
10271                         "      %v4f16 = OpTypeVector %f16 4\n"
10272                         "  %c_v4f16_0 = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_0 %c_f16_0\n"
10273                 },
10274         };
10275
10276         const StringTemplate preMain
10277         (
10278                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10279                 "     %v2bool = OpTypeVector %bool 2\n"
10280                 "        %f16 = OpTypeFloat 16\n"
10281                 "    %c_f16_0 = OpConstant %f16 0.0\n"
10282
10283                 "${type_decls}"
10284
10285                 "  %${tt}_fun = OpTypeFunction %${tt} %${tt}\n"
10286                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10287                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10288                 "     %SSBO16 = OpTypeStruct %ra_${tt}\n"
10289                 "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10290                 "   %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10291                 "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10292         );
10293
10294         const StringTemplate decoration
10295         (
10296                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10297                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10298                 "OpDecorate %SSBO16 BufferBlock\n"
10299                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10300                 "OpDecorate %ssbo_src Binding 0\n"
10301                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10302                 "OpDecorate %ssbo_dst Binding 1\n"
10303         );
10304
10305         const StringTemplate testFun
10306         (
10307                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10308                 "    %param = OpFunctionParameter %v4f32\n"
10309                 "    %entry = OpLabel\n"
10310
10311                 "        %i = OpVariable %fp_i32 Function\n"
10312                 "             OpStore %i %c_i32_0\n"
10313                 "             OpBranch %loop\n"
10314
10315                 "     %loop = OpLabel\n"
10316                 "    %i_cmp = OpLoad %i32 %i\n"
10317                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10318                 "             OpLoopMerge %merge %next None\n"
10319                 "             OpBranchConditional %lt %write %merge\n"
10320
10321                 "    %write = OpLabel\n"
10322                 "      %ndx = OpLoad %i32 %i\n"
10323
10324                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10325                 "  %val_src = OpLoad %${tt} %src\n"
10326
10327                 "  %val_dst = OpFunctionCall %${tt} %pass_fun %val_src\n"
10328                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10329                 "             OpStore %dst %val_dst\n"
10330                 "             OpBranch %next\n"
10331
10332                 "     %next = OpLabel\n"
10333                 "    %i_cur = OpLoad %i32 %i\n"
10334                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10335                 "             OpStore %i %i_new\n"
10336                 "             OpBranch %loop\n"
10337
10338                 "    %merge = OpLabel\n"
10339                 "             OpReturnValue %param\n"
10340
10341                 "             OpFunctionEnd\n"
10342
10343                 " %pass_fun = OpFunction %${tt} None %${tt}_fun\n"
10344                 "   %param0 = OpFunctionParameter %${tt}\n"
10345                 " %entry_pf = OpLabel\n"
10346                 "     %res0 = OpFAdd %${tt} %param0 %c_${tt}_0\n"
10347                 "             OpReturnValue %res0\n"
10348                 "             OpFunctionEnd\n"
10349         );
10350
10351         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10352         {
10353                 const TestType&         testType                = testTypes[testTypeIdx];
10354                 const string            testName                = testType.typeName;
10355                 const deUint32          itemsPerType    = testType.typeComponents;
10356                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10357                 const size_t            typeStride              = itemsPerType * sizeof(deFloat16);
10358                 SpecResource            specResource;
10359                 map<string, string>     specs;
10360                 VulkanFeatures          features;
10361                 vector<string>          extensions;
10362
10363                 specs["cap"]                            = "StorageUniformBufferBlock16";
10364                 specs["num_data_points"]        = de::toString(iterations);
10365                 specs["tt"]                                     = testType.typeName;
10366                 specs["tt_stride"]                      = de::toString(typeStride);
10367                 specs["type_decls"]                     = testType.typeDecls;
10368
10369                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10370                 fragments["capability"]         = capabilities.specialize(specs);
10371                 fragments["decoration"]         = decoration.specialize(specs);
10372                 fragments["pre_main"]           = preMain.specialize(specs);
10373                 fragments["testfun"]            = testFun.specialize(specs);
10374
10375                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10376                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10377                 specResource.verifyIO = compareFP16FunctionSetFunc;
10378
10379                 extensions.push_back("VK_KHR_16bit_storage");
10380                 extensions.push_back("VK_KHR_shader_float16_int8");
10381
10382                 features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10383                 features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10384
10385                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10386         }
10387
10388         return testGroup.release();
10389 }
10390
10391 struct getV_    { deUint32 inline operator()(deUint32 v) const  { return v;        } getV_(){} };
10392 struct getV0    { deUint32 inline operator()(deUint32 v) const  { return v & (~1); } getV0(){} };
10393 struct getV1    { deUint32 inline operator()(deUint32 v) const  { return v | ( 1); } getV1(){} };
10394
10395 template<deUint32 R, deUint32 N>
10396 inline static deUint32 getOffset(deUint32 x, deUint32 y, deUint32 n)
10397 {
10398         return N * ((R * y) + x) + n;
10399 }
10400
10401 template<deUint32 R, deUint32 N, class X0, class X1, class Y0, class Y1>
10402 struct getFDelta
10403 {
10404         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10405         {
10406                 DE_STATIC_ASSERT(R%2 == 0);
10407                 DE_ASSERT(flavor == 0);
10408                 DE_UNREF(flavor);
10409
10410                 const X0                        x0;
10411                 const X1                        x1;
10412                 const Y0                        y0;
10413                 const Y1                        y1;
10414                 const deFloat16         v0      = data[getOffset<R, N>(x0(x), y0(y), n)];
10415                 const deFloat16         v1      = data[getOffset<R, N>(x1(x), y1(y), n)];
10416                 const tcu::Float16      f0      = tcu::Float16(v0);
10417                 const tcu::Float16      f1      = tcu::Float16(v1);
10418                 const float                     d0      = f0.asFloat();
10419                 const float                     d1      = f1.asFloat();
10420                 const float                     d       = d1 - d0;
10421
10422                 return d;
10423         }
10424
10425         getFDelta(){}
10426 };
10427
10428 template<deUint32 F, class Class0, class Class1>
10429 struct getFOneOf
10430 {
10431         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10432         {
10433                 DE_ASSERT(flavor < F);
10434
10435                 if (flavor == 0)
10436                 {
10437                         Class0 c;
10438
10439                         return c(data, x, y, n, flavor);
10440                 }
10441                 else
10442                 {
10443                         Class1 c;
10444
10445                         return c(data, x, y, n, flavor - 1);
10446                 }
10447         }
10448
10449         getFOneOf(){}
10450 };
10451
10452 template<class FineX0, class FineX1, class FineY0, class FineY1>
10453 struct calcWidthOf4
10454 {
10455         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10456         {
10457                 DE_ASSERT(flavor < 4);
10458
10459                 const deUint32                                          flavorX = (flavor & 1) == 0 ? 0 : 1;
10460                 const deUint32                                          flavorY = (flavor & 2) == 0 ? 0 : 1;
10461                 const getFOneOf<2, FineX0, FineX1>      cx;
10462                 const getFOneOf<2, FineY0, FineY1>      cy;
10463                 float                                                           v               = 0;
10464
10465                 v += fabsf(cx(data, x, y, n, flavorX));
10466                 v += fabsf(cy(data, x, y, n, flavorY));
10467
10468                 return v;
10469         }
10470
10471         calcWidthOf4(){}
10472 };
10473
10474 template<deUint32 R, deUint32 N, class Derivative>
10475 bool compareDerivativeWithFlavor (const deFloat16* inputAsFP16, const deFloat16* outputAsFP16, deUint32 flavor, std::string& error)
10476 {
10477         const deUint32          numDataPointsByAxis     = R;
10478         const Derivative        derivativeFunc;
10479
10480         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10481         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10482         for (deUint32 n = 0; n < N; ++n)
10483         {
10484                 const float             expectedFloat   = derivativeFunc(inputAsFP16, x, y, n, flavor);
10485                 deFloat16               expected                = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_NEAREST_EVEN);
10486                 const deFloat16 output                  = outputAsFP16[getOffset<R, N>(x, y, n)];
10487
10488                 bool                    reportError             = !compare16BitFloat(expected, output, error);
10489
10490                 if (reportError)
10491                 {
10492                         expected        = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_ZERO);
10493                         reportError     = !compare16BitFloat(expected, output, error);
10494                 }
10495
10496                 if (reportError)
10497                 {
10498                         error = "subcase at " + de::toString(x) + "," + de::toString(y) + "," + de::toString(n) + ": " + error;
10499
10500                         return false;
10501                 }
10502         }
10503
10504         return true;
10505 }
10506
10507 template<deUint32 R, deUint32 N, deUint32 FLAVOUR_COUNT, class Derivative>
10508 bool compareDerivative (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10509 {
10510         if (inputs.size() != 1 || outputAllocs.size() != 1)
10511                 return false;
10512
10513         deUint32                        successfulRuns                  = FLAVOUR_COUNT;
10514         std::string                     results[FLAVOUR_COUNT];
10515         vector<deUint8>         inputBytes;
10516
10517         inputs[0].getBytes(inputBytes);
10518
10519         const deFloat16*        inputAsFP16             = reinterpret_cast<deFloat16* const>(&inputBytes.front());
10520         const deFloat16*        outputAsFP16    = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
10521
10522         DE_ASSERT(inputBytes.size() ==  R * R * N * sizeof(deFloat16));
10523
10524         for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; ++flavor)
10525                 if (compareDerivativeWithFlavor<R, N, Derivative> (inputAsFP16, outputAsFP16, flavor, results[flavor]))
10526                 {
10527                         break;
10528                 }
10529                 else
10530                 {
10531                         successfulRuns--;
10532                 }
10533
10534         if (successfulRuns == 0)
10535                 for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; flavor++)
10536                         log << TestLog::Message << "At flavor #" << flavor << " " << results[flavor] << TestLog::EndMessage;
10537
10538         return successfulRuns > 0;
10539 }
10540
10541 template<deUint32 R, deUint32 N>
10542 tcu::TestCaseGroup* createDerivativeTests (tcu::TestContext& testCtx)
10543 {
10544         typedef getFDelta<R, N, getV0, getV1, getV_, getV_> getFDxFine;
10545         typedef getFDelta<R, N, getV_, getV_, getV0, getV1> getFDyFine;
10546
10547         typedef getFDelta<R, N, getV0, getV1, getV0, getV0> getFdxCoarse0;
10548         typedef getFDelta<R, N, getV0, getV1, getV1, getV1> getFdxCoarse1;
10549         typedef getFDelta<R, N, getV0, getV0, getV0, getV1> getFdyCoarse0;
10550         typedef getFDelta<R, N, getV1, getV1, getV0, getV1> getFdyCoarse1;
10551         typedef getFOneOf<2, getFdxCoarse0, getFdxCoarse1> getFDxCoarse;
10552         typedef getFOneOf<2, getFdyCoarse0, getFdyCoarse1> getFDyCoarse;
10553
10554         typedef calcWidthOf4<getFDxFine, getFDxFine, getFDyFine, getFDyFine> getFWidthFine;
10555         typedef calcWidthOf4<getFdxCoarse0, getFdxCoarse1, getFdyCoarse0, getFdyCoarse1> getFWidthCoarse;
10556
10557         typedef getFOneOf<3, getFDxFine, getFDxCoarse> getFDx;
10558         typedef getFOneOf<3, getFDyFine, getFDyCoarse> getFDy;
10559         typedef getFOneOf<5, getFWidthFine, getFWidthCoarse> getFWidth;
10560
10561         const std::string                                       testGroupName           (std::string("derivative_") + de::toString(N));
10562         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Derivative instruction tests"));
10563
10564         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10565         const deUint32                                          numDataPointsByAxis     = R;
10566         const deUint32                                          numDataPoints           = N * numDataPointsByAxis * numDataPointsByAxis;
10567         vector<deFloat16>                                       float16InputX;
10568         vector<deFloat16>                                       float16InputY;
10569         vector<deFloat16>                                       float16InputW;
10570         vector<deFloat16>                                       float16OutputDummy      (numDataPoints, 0);
10571         RGBA                                                            defaultColors[4];
10572
10573         getDefaultColors(defaultColors);
10574
10575         float16InputX.reserve(numDataPoints);
10576         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10577         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10578         for (deUint32 n = 0; n < N; ++n)
10579         {
10580                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(x * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10581
10582                 if (y%2 == 0)
10583                         float16InputX.push_back(tcu::Float16(sin(arg)).bits());
10584                 else
10585                         float16InputX.push_back(tcu::Float16(cos(arg)).bits());
10586         }
10587
10588         float16InputY.reserve(numDataPoints);
10589         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10590         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10591         for (deUint32 n = 0; n < N; ++n)
10592         {
10593                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(y * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10594
10595                 if (x%2 == 0)
10596                         float16InputY.push_back(tcu::Float16(sin(arg)).bits());
10597                 else
10598                         float16InputY.push_back(tcu::Float16(cos(arg)).bits());
10599         }
10600
10601         const deFloat16 testNumbers[]   =
10602         {
10603                 tcu::Float16( 2.0  ).bits(),
10604                 tcu::Float16( 4.0  ).bits(),
10605                 tcu::Float16( 8.0  ).bits(),
10606                 tcu::Float16( 16.0 ).bits(),
10607                 tcu::Float16( 32.0 ).bits(),
10608                 tcu::Float16( 64.0 ).bits(),
10609                 tcu::Float16( 128.0).bits(),
10610                 tcu::Float16( 256.0).bits(),
10611                 tcu::Float16( 512.0).bits(),
10612                 tcu::Float16(-2.0  ).bits(),
10613                 tcu::Float16(-4.0  ).bits(),
10614                 tcu::Float16(-8.0  ).bits(),
10615                 tcu::Float16(-16.0 ).bits(),
10616                 tcu::Float16(-32.0 ).bits(),
10617                 tcu::Float16(-64.0 ).bits(),
10618                 tcu::Float16(-128.0).bits(),
10619                 tcu::Float16(-256.0).bits(),
10620                 tcu::Float16(-512.0).bits(),
10621         };
10622
10623         float16InputW.reserve(numDataPoints);
10624         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10625         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10626         for (deUint32 n = 0; n < N; ++n)
10627                 float16InputW.push_back(testNumbers[rnd.getInt(0, DE_LENGTH_OF_ARRAY(testNumbers) - 1)]);
10628
10629         struct TestOp
10630         {
10631                 const char*                     opCode;
10632                 vector<deFloat16>&      inputData;
10633                 VerifyIOFunc            verifyFunc;
10634         };
10635
10636         const TestOp    testOps[]       =
10637         {
10638                 { "OpDPdxFine"          ,       float16InputX   ,       compareDerivative<R, N, 1, getFDxFine           >       },
10639                 { "OpDPdyFine"          ,       float16InputY   ,       compareDerivative<R, N, 1, getFDyFine           >       },
10640                 { "OpFwidthFine"        ,       float16InputW   ,       compareDerivative<R, N, 1, getFWidthFine        >       },
10641                 { "OpDPdxCoarse"        ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10642                 { "OpDPdyCoarse"        ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10643                 { "OpFwidthCoarse"      ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10644                 { "OpDPdx"                      ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10645                 { "OpDPdy"                      ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10646                 { "OpFwidth"            ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10647         };
10648
10649         struct TestType
10650         {
10651                 const deUint32  typeComponents;
10652                 const char*             typeName;
10653                 const char*             typeDecls;
10654         };
10655
10656         const TestType  testTypes[]     =
10657         {
10658                 {
10659                         1,
10660                         "f16",
10661                         ""
10662                 },
10663                 {
10664                         2,
10665                         "v2f16",
10666                         "      %v2f16 = OpTypeVector %f16 2\n"
10667                 },
10668                 {
10669                         4,
10670                         "v4f16",
10671                         "      %v4f16 = OpTypeVector %f16 4\n"
10672                 },
10673         };
10674
10675         const deUint32  testTypeNdx     = (N == 1) ? 0
10676                                                                 : (N == 2) ? 1
10677                                                                 : (N == 4) ? 2
10678                                                                 : DE_LENGTH_OF_ARRAY(testTypes);
10679         const TestType& testType        =       testTypes[testTypeNdx];
10680
10681         DE_ASSERT(testTypeNdx < DE_LENGTH_OF_ARRAY(testTypes));
10682         DE_ASSERT(testType.typeComponents == N);
10683
10684         const StringTemplate preMain
10685         (
10686                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10687                 " %c_u32_xw = OpConstant %u32 ${items_by_x}\n"
10688                 "      %f16 = OpTypeFloat 16\n"
10689                 "${type_decls}"
10690                 " %up_${tt} = OpTypePointer Uniform %${tt}\n"
10691                 " %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10692                 "   %SSBO16 = OpTypeStruct %ra_${tt}\n"
10693                 "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10694                 " %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10695                 " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10696         );
10697
10698         const StringTemplate decoration
10699         (
10700                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10701                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10702                 "OpDecorate %SSBO16 BufferBlock\n"
10703                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10704                 "OpDecorate %ssbo_src Binding 0\n"
10705                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10706                 "OpDecorate %ssbo_dst Binding 1\n"
10707         );
10708
10709         const StringTemplate testFun
10710         (
10711                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10712                 "    %param = OpFunctionParameter %v4f32\n"
10713                 "    %entry = OpLabel\n"
10714
10715                 "  %loc_x_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_0\n"
10716                 "  %loc_y_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_1\n"
10717                 "      %x_c = OpLoad %f32 %loc_x_c\n"
10718                 "      %y_c = OpLoad %f32 %loc_y_c\n"
10719                 "    %x_idx = OpConvertFToU %u32 %x_c\n"
10720                 "    %y_idx = OpConvertFToU %u32 %y_c\n"
10721                 "    %ndx_y = OpIMul %u32 %y_idx %c_u32_xw\n"
10722                 "      %ndx = OpIAdd %u32 %ndx_y %x_idx\n"
10723
10724                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10725                 "  %val_src = OpLoad %${tt} %src\n"
10726                 "  %val_dst = ${op_code} %${tt} %val_src\n"
10727                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10728                 "             OpStore %dst %val_dst\n"
10729                 "             OpBranch %merge\n"
10730
10731                 "    %merge = OpLabel\n"
10732                 "             OpReturnValue %param\n"
10733
10734                 "             OpFunctionEnd\n"
10735         );
10736
10737         for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10738         {
10739                 const TestOp&           testOp                  = testOps[testOpsIdx];
10740                 const string            testName                = de::toLower(string(testOp.opCode));
10741                 const size_t            typeStride              = N * sizeof(deFloat16);
10742                 GraphicsResources       specResource;
10743                 map<string, string>     specs;
10744                 VulkanFeatures          features;
10745                 vector<string>          extensions;
10746                 map<string, string>     fragments;
10747                 SpecConstants           noSpecConstants;
10748                 PushConstants           noPushConstants;
10749                 GraphicsInterfaces      noInterfaces;
10750
10751                 specs["op_code"]                        = testOp.opCode;
10752                 specs["num_data_points"]        = de::toString(testOp.inputData.size() / N);
10753                 specs["items_by_x"]                     = de::toString(numDataPointsByAxis);
10754                 specs["tt"]                                     = testType.typeName;
10755                 specs["tt_stride"]                      = de::toString(typeStride);
10756                 specs["type_decls"]                     = testType.typeDecls;
10757
10758                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10759                 fragments["capability"]         = "OpCapability DerivativeControl\nOpCapability StorageUniformBufferBlock16\n";
10760                 fragments["decoration"]         = decoration.specialize(specs);
10761                 fragments["pre_main"]           = preMain.specialize(specs);
10762                 fragments["testfun"]            = testFun.specialize(specs);
10763
10764                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(testOp.inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10765                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10766                 specResource.verifyIO = testOp.verifyFunc;
10767
10768                 extensions.push_back("VK_KHR_16bit_storage");
10769                 extensions.push_back("VK_KHR_shader_float16_int8");
10770
10771                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10772                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10773
10774                 createTestForStage(VK_SHADER_STAGE_FRAGMENT_BIT, testName.c_str(), defaultColors, defaultColors, fragments, noSpecConstants,
10775                                                         noPushConstants, specResource, noInterfaces, extensions, features, testGroup.get(), QP_TEST_RESULT_FAIL, string(), true);
10776         }
10777
10778         return testGroup.release();
10779 }
10780
10781 bool compareFP16VectorExtractFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10782 {
10783         if (inputs.size() != 2 || outputAllocs.size() != 1)
10784                 return false;
10785
10786         vector<deUint8> input1Bytes;
10787         vector<deUint8> input2Bytes;
10788
10789         inputs[0].getBytes(input1Bytes);
10790         inputs[1].getBytes(input2Bytes);
10791
10792         DE_ASSERT(input1Bytes.size() > 0);
10793         DE_ASSERT(input2Bytes.size() > 0);
10794         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
10795
10796         const size_t                    iterations              = input2Bytes.size() / sizeof(deUint32);
10797         const size_t                    components              = input1Bytes.size() / (sizeof(deFloat16) * iterations);
10798         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
10799         const deUint32* const   inputIndices    = (const deUint32*)&input2Bytes[0];
10800         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
10801         std::string                             error;
10802
10803         DE_ASSERT(components == 2 || components == 4);
10804         DE_ASSERT(input1Bytes.size() == iterations * components * sizeof(deFloat16));
10805
10806         for (size_t idx = 0; idx < iterations; ++idx)
10807         {
10808                 const deUint32  componentNdx    = inputIndices[idx];
10809
10810                 DE_ASSERT(componentNdx < components);
10811
10812                 const deFloat16 expected                = input1AsFP16[components * idx + componentNdx];
10813
10814                 if (!compare16BitFloat(expected, outputAsFP16[idx], error))
10815                 {
10816                         log << TestLog::Message << "At " << idx << error << TestLog::EndMessage;
10817
10818                         return false;
10819                 }
10820         }
10821
10822         return true;
10823 }
10824
10825 template<class SpecResource>
10826 tcu::TestCaseGroup* createFloat16VectorExtractSet (tcu::TestContext& testCtx)
10827 {
10828         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorextractdynamic", "OpVectorExtractDynamic tests"));
10829
10830         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10831         const deUint32                                          numDataPoints           = 256;
10832         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10833         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10834
10835         struct TestType
10836         {
10837                 const deUint32  typeComponents;
10838                 const size_t    typeStride;
10839                 const char*             typeName;
10840                 const char*             typeDecls;
10841         };
10842
10843         const TestType  testTypes[]     =
10844         {
10845                 {
10846                         2,
10847                         2 * sizeof(deFloat16),
10848                         "v2f16",
10849                         "      %v2f16 = OpTypeVector %f16 2\n"
10850                 },
10851                 {
10852                         3,
10853                         4 * sizeof(deFloat16),
10854                         "v3f16",
10855                         "      %v3f16 = OpTypeVector %f16 3\n"
10856                 },
10857                 {
10858                         4,
10859                         4 * sizeof(deFloat16),
10860                         "v4f16",
10861                         "      %v4f16 = OpTypeVector %f16 4\n"
10862                 },
10863         };
10864
10865         const StringTemplate preMain
10866         (
10867                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10868                 "        %f16 = OpTypeFloat 16\n"
10869
10870                 "${type_decl}"
10871
10872                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10873                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10874                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
10875                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
10876
10877                 "     %up_u32 = OpTypePointer Uniform %u32\n"
10878                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
10879                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
10880                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
10881
10882                 "     %up_f16 = OpTypePointer Uniform %f16\n"
10883                 "     %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
10884                 "   %SSBO_DST = OpTypeStruct %ra_f16\n"
10885                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
10886
10887                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
10888                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
10889                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
10890         );
10891
10892         const StringTemplate decoration
10893         (
10894                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10895                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
10896                 "OpDecorate %SSBO_SRC BufferBlock\n"
10897                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10898                 "OpDecorate %ssbo_src Binding 0\n"
10899
10900                 "OpDecorate %ra_u32 ArrayStride 4\n"
10901                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
10902                 "OpDecorate %SSBO_IDX BufferBlock\n"
10903                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
10904                 "OpDecorate %ssbo_idx Binding 1\n"
10905
10906                 "OpDecorate %ra_f16 ArrayStride 2\n"
10907                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
10908                 "OpDecorate %SSBO_DST BufferBlock\n"
10909                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10910                 "OpDecorate %ssbo_dst Binding 2\n"
10911         );
10912
10913         const StringTemplate testFun
10914         (
10915                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10916                 "    %param = OpFunctionParameter %v4f32\n"
10917                 "    %entry = OpLabel\n"
10918
10919                 "        %i = OpVariable %fp_i32 Function\n"
10920                 "             OpStore %i %c_i32_0\n"
10921
10922                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
10923                 "             OpSelectionMerge %end_if None\n"
10924                 "             OpBranchConditional %will_run %run_test %end_if\n"
10925
10926                 " %run_test = OpLabel\n"
10927                 "             OpBranch %loop\n"
10928
10929                 "     %loop = OpLabel\n"
10930                 "    %i_cmp = OpLoad %i32 %i\n"
10931                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10932                 "             OpLoopMerge %merge %next None\n"
10933                 "             OpBranchConditional %lt %write %merge\n"
10934
10935                 "    %write = OpLabel\n"
10936                 "      %ndx = OpLoad %i32 %i\n"
10937
10938                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10939                 "  %val_src = OpLoad %${tt} %src\n"
10940
10941                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
10942                 "  %val_idx = OpLoad %u32 %src_idx\n"
10943
10944                 "  %val_dst = OpVectorExtractDynamic %f16 %val_src %val_idx\n"
10945                 "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10946
10947                 "             OpStore %dst %val_dst\n"
10948                 "             OpBranch %next\n"
10949
10950                 "     %next = OpLabel\n"
10951                 "    %i_cur = OpLoad %i32 %i\n"
10952                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10953                 "             OpStore %i %i_new\n"
10954                 "             OpBranch %loop\n"
10955
10956                 "    %merge = OpLabel\n"
10957                 "             OpBranch %end_if\n"
10958                 "   %end_if = OpLabel\n"
10959                 "             OpReturnValue %param\n"
10960
10961                 "             OpFunctionEnd\n"
10962         );
10963
10964         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10965         {
10966                 const TestType&         testType                = testTypes[testTypeIdx];
10967                 const string            testName                = testType.typeName;
10968                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
10969                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10970                 SpecResource            specResource;
10971                 map<string, string>     specs;
10972                 VulkanFeatures          features;
10973                 vector<deUint32>        inputDataNdx;
10974                 map<string, string>     fragments;
10975                 vector<string>          extensions;
10976
10977                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
10978                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
10979
10980                 specs["num_data_points"]        = de::toString(iterations);
10981                 specs["tt"]                                     = testType.typeName;
10982                 specs["tt_stride"]                      = de::toString(testType.typeStride);
10983                 specs["type_decl"]                      = testType.typeDecls;
10984
10985                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10986                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
10987                 fragments["decoration"]         = decoration.specialize(specs);
10988                 fragments["pre_main"]           = preMain.specialize(specs);
10989                 fragments["testfun"]            = testFun.specialize(specs);
10990
10991                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10992                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10993                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10994                 specResource.verifyIO = compareFP16VectorExtractFunc;
10995
10996                 extensions.push_back("VK_KHR_16bit_storage");
10997                 extensions.push_back("VK_KHR_shader_float16_int8");
10998
10999                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11000                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11001
11002                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11003         }
11004
11005         return testGroup.release();
11006 }
11007
11008 template<deUint32 COMPONENTS_COUNT, deUint32 REPLACEMENT>
11009 bool compareFP16VectorInsertFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11010 {
11011         if (inputs.size() != 2 || outputAllocs.size() != 1)
11012                 return false;
11013
11014         vector<deUint8> input1Bytes;
11015         vector<deUint8> input2Bytes;
11016
11017         inputs[0].getBytes(input1Bytes);
11018         inputs[1].getBytes(input2Bytes);
11019
11020         DE_ASSERT(input1Bytes.size() > 0);
11021         DE_ASSERT(input2Bytes.size() > 0);
11022         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
11023
11024         const size_t                    iterations                      = input2Bytes.size() / sizeof(deUint32);
11025         const size_t                    componentsStride        = input1Bytes.size() / (sizeof(deFloat16) * iterations);
11026         const deFloat16* const  input1AsFP16            = (const deFloat16*)&input1Bytes[0];
11027         const deUint32* const   inputIndices            = (const deUint32*)&input2Bytes[0];
11028         const deFloat16* const  outputAsFP16            = (const deFloat16*)outputAllocs[0]->getHostPtr();
11029         const deFloat16                 magic                           = tcu::Float16(float(REPLACEMENT)).bits();
11030         std::string                             error;
11031
11032         DE_ASSERT(componentsStride == 2 || componentsStride == 4);
11033         DE_ASSERT(input1Bytes.size() == iterations * componentsStride * sizeof(deFloat16));
11034
11035         for (size_t idx = 0; idx < iterations; ++idx)
11036         {
11037                 const deFloat16*        inputVec                = &input1AsFP16[componentsStride * idx];
11038                 const deFloat16*        outputVec               = &outputAsFP16[componentsStride * idx];
11039                 const deUint32          replacedCompNdx = inputIndices[idx];
11040
11041                 DE_ASSERT(replacedCompNdx < COMPONENTS_COUNT);
11042
11043                 for (size_t compNdx = 0; compNdx < COMPONENTS_COUNT; ++compNdx)
11044                 {
11045                         const deFloat16 expected        = (compNdx == replacedCompNdx) ? magic : inputVec[compNdx];
11046
11047                         if (!compare16BitFloat(expected, outputVec[compNdx], error))
11048                         {
11049                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11050
11051                                 return false;
11052                         }
11053                 }
11054         }
11055
11056         return true;
11057 }
11058
11059 template<class SpecResource>
11060 tcu::TestCaseGroup* createFloat16VectorInsertSet (tcu::TestContext& testCtx)
11061 {
11062         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorinsertdynamic", "OpVectorInsertDynamic tests"));
11063
11064         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
11065         const deUint32                                          replacement                     = 42;
11066         const deUint32                                          numDataPoints           = 256;
11067         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
11068         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
11069
11070         struct TestType
11071         {
11072                 const deUint32  typeComponents;
11073                 const size_t    typeStride;
11074                 const char*             typeName;
11075                 const char*             typeDecls;
11076                 VerifyIOFunc    verifyIOFunc;
11077         };
11078
11079         const TestType  testTypes[]     =
11080         {
11081                 {
11082                         2,
11083                         2 * sizeof(deFloat16),
11084                         "v2f16",
11085                         "      %v2f16 = OpTypeVector %f16 2\n",
11086                         compareFP16VectorInsertFunc<2, replacement>
11087                 },
11088                 {
11089                         3,
11090                         4 * sizeof(deFloat16),
11091                         "v3f16",
11092                         "      %v3f16 = OpTypeVector %f16 3\n",
11093                         compareFP16VectorInsertFunc<3, replacement>
11094                 },
11095                 {
11096                         4,
11097                         4 * sizeof(deFloat16),
11098                         "v4f16",
11099                         "      %v4f16 = OpTypeVector %f16 4\n",
11100                         compareFP16VectorInsertFunc<4, replacement>
11101                 },
11102         };
11103
11104         const StringTemplate preMain
11105         (
11106                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11107                 "        %f16 = OpTypeFloat 16\n"
11108                 "  %c_f16_ins = OpConstant %f16 ${replacement}\n"
11109
11110                 "${type_decl}"
11111
11112                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
11113                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
11114                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
11115                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
11116
11117                 "     %up_u32 = OpTypePointer Uniform %u32\n"
11118                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
11119                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
11120                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
11121
11122                 "   %SSBO_DST = OpTypeStruct %ra_${tt}\n"
11123                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
11124
11125                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
11126                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
11127                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
11128         );
11129
11130         const StringTemplate decoration
11131         (
11132                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
11133                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
11134                 "OpDecorate %SSBO_SRC BufferBlock\n"
11135                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11136                 "OpDecorate %ssbo_src Binding 0\n"
11137
11138                 "OpDecorate %ra_u32 ArrayStride 4\n"
11139                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
11140                 "OpDecorate %SSBO_IDX BufferBlock\n"
11141                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
11142                 "OpDecorate %ssbo_idx Binding 1\n"
11143
11144                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
11145                 "OpDecorate %SSBO_DST BufferBlock\n"
11146                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11147                 "OpDecorate %ssbo_dst Binding 2\n"
11148         );
11149
11150         const StringTemplate testFun
11151         (
11152                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11153                 "    %param = OpFunctionParameter %v4f32\n"
11154                 "    %entry = OpLabel\n"
11155
11156                 "        %i = OpVariable %fp_i32 Function\n"
11157                 "             OpStore %i %c_i32_0\n"
11158
11159                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11160                 "             OpSelectionMerge %end_if None\n"
11161                 "             OpBranchConditional %will_run %run_test %end_if\n"
11162
11163                 " %run_test = OpLabel\n"
11164                 "             OpBranch %loop\n"
11165
11166                 "     %loop = OpLabel\n"
11167                 "    %i_cmp = OpLoad %i32 %i\n"
11168                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11169                 "             OpLoopMerge %merge %next None\n"
11170                 "             OpBranchConditional %lt %write %merge\n"
11171
11172                 "    %write = OpLabel\n"
11173                 "      %ndx = OpLoad %i32 %i\n"
11174
11175                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
11176                 "  %val_src = OpLoad %${tt} %src\n"
11177
11178                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
11179                 "  %val_idx = OpLoad %u32 %src_idx\n"
11180
11181                 "  %val_dst = OpVectorInsertDynamic %${tt} %val_src %c_f16_ins %val_idx\n"
11182                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
11183
11184                 "             OpStore %dst %val_dst\n"
11185                 "             OpBranch %next\n"
11186
11187                 "     %next = OpLabel\n"
11188                 "    %i_cur = OpLoad %i32 %i\n"
11189                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11190                 "             OpStore %i %i_new\n"
11191                 "             OpBranch %loop\n"
11192
11193                 "    %merge = OpLabel\n"
11194                 "             OpBranch %end_if\n"
11195                 "   %end_if = OpLabel\n"
11196                 "             OpReturnValue %param\n"
11197
11198                 "             OpFunctionEnd\n"
11199         );
11200
11201         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
11202         {
11203                 const TestType&         testType                = testTypes[testTypeIdx];
11204                 const string            testName                = testType.typeName;
11205                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
11206                 const size_t            iterations              = float16InputData.size() / itemsPerType;
11207                 SpecResource            specResource;
11208                 map<string, string>     specs;
11209                 VulkanFeatures          features;
11210                 vector<deUint32>        inputDataNdx;
11211                 map<string, string>     fragments;
11212                 vector<string>          extensions;
11213
11214                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
11215                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
11216
11217                 specs["num_data_points"]        = de::toString(iterations);
11218                 specs["tt"]                                     = testType.typeName;
11219                 specs["tt_stride"]                      = de::toString(testType.typeStride);
11220                 specs["type_decl"]                      = testType.typeDecls;
11221                 specs["replacement"]            = de::toString(replacement);
11222
11223                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11224                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11225                 fragments["decoration"]         = decoration.specialize(specs);
11226                 fragments["pre_main"]           = preMain.specialize(specs);
11227                 fragments["testfun"]            = testFun.specialize(specs);
11228
11229                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11230                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11231                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11232                 specResource.verifyIO = testType.verifyIOFunc;
11233
11234                 extensions.push_back("VK_KHR_16bit_storage");
11235                 extensions.push_back("VK_KHR_shader_float16_int8");
11236
11237                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11238                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11239
11240                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11241         }
11242
11243         return testGroup.release();
11244 }
11245
11246 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)
11247 {
11248         const size_t    compNdxCount    = (vec1Len + vec2Len + 1);
11249         const size_t    compNdxLimited  = iteration % (compNdxCount * compNdxCount);
11250         size_t                  comp;
11251
11252         switch (componentNdx)
11253         {
11254                 case 0: comp = compNdxLimited / compNdxCount; break;
11255                 case 1: comp = compNdxLimited % compNdxCount; break;
11256                 case 2: comp = 0; break;
11257                 case 3: comp = 1; break;
11258                 default: TCU_THROW(InternalError, "Impossible");
11259         }
11260
11261         if (comp >= vec1Len + vec2Len)
11262         {
11263                 validate = false;
11264                 return 0;
11265         }
11266         else
11267         {
11268                 validate = true;
11269                 return (comp < vec1Len) ? input1Vec[comp] : input2Vec[comp - vec1Len];
11270         }
11271 }
11272
11273 template<deUint32 DST_COMPONENTS_COUNT, deUint32 SRC0_COMPONENTS_COUNT, deUint32 SRC1_COMPONENTS_COUNT>
11274 bool compareFP16VectorShuffleFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11275 {
11276         DE_STATIC_ASSERT(DST_COMPONENTS_COUNT == 2 || DST_COMPONENTS_COUNT == 3 || DST_COMPONENTS_COUNT == 4);
11277         DE_STATIC_ASSERT(SRC0_COMPONENTS_COUNT == 2 || SRC0_COMPONENTS_COUNT == 3 || SRC0_COMPONENTS_COUNT == 4);
11278         DE_STATIC_ASSERT(SRC1_COMPONENTS_COUNT == 2 || SRC1_COMPONENTS_COUNT == 3 || SRC1_COMPONENTS_COUNT == 4);
11279
11280         if (inputs.size() != 2 || outputAllocs.size() != 1)
11281                 return false;
11282
11283         vector<deUint8> input1Bytes;
11284         vector<deUint8> input2Bytes;
11285
11286         inputs[0].getBytes(input1Bytes);
11287         inputs[1].getBytes(input2Bytes);
11288
11289         DE_ASSERT(input1Bytes.size() > 0);
11290         DE_ASSERT(input2Bytes.size() > 0);
11291         DE_ASSERT(input2Bytes.size() % sizeof(deFloat16) == 0);
11292
11293         const size_t                    componentsStrideDst             = (DST_COMPONENTS_COUNT == 3) ? 4 : DST_COMPONENTS_COUNT;
11294         const size_t                    componentsStrideSrc0    = (SRC0_COMPONENTS_COUNT == 3) ? 4 : SRC0_COMPONENTS_COUNT;
11295         const size_t                    componentsStrideSrc1    = (SRC1_COMPONENTS_COUNT == 3) ? 4 : SRC1_COMPONENTS_COUNT;
11296         const size_t                    iterations                              = input1Bytes.size() / (componentsStrideSrc0 * sizeof(deFloat16));
11297         const deFloat16* const  input1AsFP16                    = (const deFloat16*)&input1Bytes[0];
11298         const deFloat16* const  input2AsFP16                    = (const deFloat16*)&input2Bytes[0];
11299         const deFloat16* const  outputAsFP16                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11300         std::string                             error;
11301
11302         DE_ASSERT(input1Bytes.size() == iterations * componentsStrideSrc0 * sizeof(deFloat16));
11303         DE_ASSERT(input2Bytes.size() == iterations * componentsStrideSrc1 * sizeof(deFloat16));
11304
11305         for (size_t idx = 0; idx < iterations; ++idx)
11306         {
11307                 const deFloat16*        input1Vec       = &input1AsFP16[componentsStrideSrc0 * idx];
11308                 const deFloat16*        input2Vec       = &input2AsFP16[componentsStrideSrc1 * idx];
11309                 const deFloat16*        outputVec       = &outputAsFP16[componentsStrideDst * idx];
11310
11311                 for (size_t compNdx = 0; compNdx < DST_COMPONENTS_COUNT; ++compNdx)
11312                 {
11313                         bool            validate        = true;
11314                         deFloat16       expected        = getShuffledComponent(idx, compNdx, input1Vec, input2Vec, SRC0_COMPONENTS_COUNT, SRC1_COMPONENTS_COUNT, validate);
11315
11316                         if (validate && !compare16BitFloat(expected, outputVec[compNdx], error))
11317                         {
11318                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11319
11320                                 return false;
11321                         }
11322                 }
11323         }
11324
11325         return true;
11326 }
11327
11328 VerifyIOFunc getFloat16VectorShuffleVerifyIOFunc (deUint32 dstComponentsCount, deUint32 src0ComponentsCount, deUint32 src1ComponentsCount)
11329 {
11330         DE_ASSERT(dstComponentsCount <= 4);
11331         DE_ASSERT(src0ComponentsCount <= 4);
11332         DE_ASSERT(src1ComponentsCount <= 4);
11333         deUint32 funcCode = 100 * dstComponentsCount + 10 * src0ComponentsCount + src1ComponentsCount;
11334
11335         switch (funcCode)
11336         {
11337                 case 222:return compareFP16VectorShuffleFunc<2, 2, 2>;
11338                 case 223:return compareFP16VectorShuffleFunc<2, 2, 3>;
11339                 case 224:return compareFP16VectorShuffleFunc<2, 2, 4>;
11340                 case 232:return compareFP16VectorShuffleFunc<2, 3, 2>;
11341                 case 233:return compareFP16VectorShuffleFunc<2, 3, 3>;
11342                 case 234:return compareFP16VectorShuffleFunc<2, 3, 4>;
11343                 case 242:return compareFP16VectorShuffleFunc<2, 4, 2>;
11344                 case 243:return compareFP16VectorShuffleFunc<2, 4, 3>;
11345                 case 244:return compareFP16VectorShuffleFunc<2, 4, 4>;
11346                 case 322:return compareFP16VectorShuffleFunc<3, 2, 2>;
11347                 case 323:return compareFP16VectorShuffleFunc<3, 2, 3>;
11348                 case 324:return compareFP16VectorShuffleFunc<3, 2, 4>;
11349                 case 332:return compareFP16VectorShuffleFunc<3, 3, 2>;
11350                 case 333:return compareFP16VectorShuffleFunc<3, 3, 3>;
11351                 case 334:return compareFP16VectorShuffleFunc<3, 3, 4>;
11352                 case 342:return compareFP16VectorShuffleFunc<3, 4, 2>;
11353                 case 343:return compareFP16VectorShuffleFunc<3, 4, 3>;
11354                 case 344:return compareFP16VectorShuffleFunc<3, 4, 4>;
11355                 case 422:return compareFP16VectorShuffleFunc<4, 2, 2>;
11356                 case 423:return compareFP16VectorShuffleFunc<4, 2, 3>;
11357                 case 424:return compareFP16VectorShuffleFunc<4, 2, 4>;
11358                 case 432:return compareFP16VectorShuffleFunc<4, 3, 2>;
11359                 case 433:return compareFP16VectorShuffleFunc<4, 3, 3>;
11360                 case 434:return compareFP16VectorShuffleFunc<4, 3, 4>;
11361                 case 442:return compareFP16VectorShuffleFunc<4, 4, 2>;
11362                 case 443:return compareFP16VectorShuffleFunc<4, 4, 3>;
11363                 case 444:return compareFP16VectorShuffleFunc<4, 4, 4>;
11364                 default: TCU_THROW(InternalError, "Invalid number of components specified.");
11365         }
11366 }
11367
11368 template<class SpecResource>
11369 tcu::TestCaseGroup* createFloat16VectorShuffleSet (tcu::TestContext& testCtx)
11370 {
11371         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorshuffle", "OpVectorShuffle tests"));
11372         const int                                                       testSpecificSeed        = deStringHash(testGroup->getName());
11373         const int                                                       seed                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
11374         de::Random                                                      rnd                                     (seed);
11375         const deUint32                                          numDataPoints           = 128;
11376         map<string, string>                                     fragments;
11377
11378         struct TestType
11379         {
11380                 const deUint32  typeComponents;
11381                 const char*             typeName;
11382         };
11383
11384         const TestType  testTypes[]     =
11385         {
11386                 {
11387                         2,
11388                         "v2f16",
11389                 },
11390                 {
11391                         3,
11392                         "v3f16",
11393                 },
11394                 {
11395                         4,
11396                         "v4f16",
11397                 },
11398         };
11399
11400         const StringTemplate preMain
11401         (
11402                 "    %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11403                 "     %c_i32_cc = OpConstant %i32 ${case_count}\n"
11404                 "          %f16 = OpTypeFloat 16\n"
11405                 "        %v2f16 = OpTypeVector %f16 2\n"
11406                 "        %v3f16 = OpTypeVector %f16 3\n"
11407                 "        %v4f16 = OpTypeVector %f16 4\n"
11408
11409                 "     %up_v2f16 = OpTypePointer Uniform %v2f16\n"
11410                 "     %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
11411                 "   %SSBO_v2f16 = OpTypeStruct %ra_v2f16\n"
11412                 "%up_SSBO_v2f16 = OpTypePointer Uniform %SSBO_v2f16\n"
11413
11414                 "     %up_v3f16 = OpTypePointer Uniform %v3f16\n"
11415                 "     %ra_v3f16 = OpTypeArray %v3f16 %c_i32_ndp\n"
11416                 "   %SSBO_v3f16 = OpTypeStruct %ra_v3f16\n"
11417                 "%up_SSBO_v3f16 = OpTypePointer Uniform %SSBO_v3f16\n"
11418
11419                 "     %up_v4f16 = OpTypePointer Uniform %v4f16\n"
11420                 "     %ra_v4f16 = OpTypeArray %v4f16 %c_i32_ndp\n"
11421                 "   %SSBO_v4f16 = OpTypeStruct %ra_v4f16\n"
11422                 "%up_SSBO_v4f16 = OpTypePointer Uniform %SSBO_v4f16\n"
11423
11424                 "        %fun_t = OpTypeFunction %${tt_dst} %${tt_src0} %${tt_src1} %i32\n"
11425
11426                 "    %ssbo_src0 = OpVariable %up_SSBO_${tt_src0} Uniform\n"
11427                 "    %ssbo_src1 = OpVariable %up_SSBO_${tt_src1} Uniform\n"
11428                 "     %ssbo_dst = OpVariable %up_SSBO_${tt_dst} Uniform\n"
11429         );
11430
11431         const StringTemplate decoration
11432         (
11433                 "OpDecorate %ra_v2f16 ArrayStride 4\n"
11434                 "OpDecorate %ra_v3f16 ArrayStride 8\n"
11435                 "OpDecorate %ra_v4f16 ArrayStride 8\n"
11436
11437                 "OpMemberDecorate %SSBO_v2f16 0 Offset 0\n"
11438                 "OpDecorate %SSBO_v2f16 BufferBlock\n"
11439
11440                 "OpMemberDecorate %SSBO_v3f16 0 Offset 0\n"
11441                 "OpDecorate %SSBO_v3f16 BufferBlock\n"
11442
11443                 "OpMemberDecorate %SSBO_v4f16 0 Offset 0\n"
11444                 "OpDecorate %SSBO_v4f16 BufferBlock\n"
11445
11446                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
11447                 "OpDecorate %ssbo_src0 Binding 0\n"
11448                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
11449                 "OpDecorate %ssbo_src1 Binding 1\n"
11450                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11451                 "OpDecorate %ssbo_dst Binding 2\n"
11452         );
11453
11454         const StringTemplate testFun
11455         (
11456                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11457                 "    %param = OpFunctionParameter %v4f32\n"
11458                 "    %entry = OpLabel\n"
11459
11460                 "        %i = OpVariable %fp_i32 Function\n"
11461                 "             OpStore %i %c_i32_0\n"
11462
11463                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11464                 "             OpSelectionMerge %end_if None\n"
11465                 "             OpBranchConditional %will_run %run_test %end_if\n"
11466
11467                 " %run_test = OpLabel\n"
11468                 "             OpBranch %loop\n"
11469
11470                 "     %loop = OpLabel\n"
11471                 "    %i_cmp = OpLoad %i32 %i\n"
11472                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11473                 "             OpLoopMerge %merge %next None\n"
11474                 "             OpBranchConditional %lt %write %merge\n"
11475
11476                 "    %write = OpLabel\n"
11477                 "      %ndx = OpLoad %i32 %i\n"
11478                 "     %src0 = OpAccessChain %up_${tt_src0} %ssbo_src0 %c_i32_0 %ndx\n"
11479                 " %val_src0 = OpLoad %${tt_src0} %src0\n"
11480                 "     %src1 = OpAccessChain %up_${tt_src1} %ssbo_src1 %c_i32_0 %ndx\n"
11481                 " %val_src1 = OpLoad %${tt_src1} %src1\n"
11482                 "  %val_dst = OpFunctionCall %${tt_dst} %sw_fun %val_src0 %val_src1 %ndx\n"
11483                 "      %dst = OpAccessChain %up_${tt_dst} %ssbo_dst %c_i32_0 %ndx\n"
11484                 "             OpStore %dst %val_dst\n"
11485                 "             OpBranch %next\n"
11486
11487                 "     %next = OpLabel\n"
11488                 "    %i_cur = OpLoad %i32 %i\n"
11489                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11490                 "             OpStore %i %i_new\n"
11491                 "             OpBranch %loop\n"
11492
11493                 "    %merge = OpLabel\n"
11494                 "             OpBranch %end_if\n"
11495                 "   %end_if = OpLabel\n"
11496                 "             OpReturnValue %param\n"
11497                 "             OpFunctionEnd\n"
11498                 "\n"
11499
11500                 "   %sw_fun = OpFunction %${tt_dst} None %fun_t\n"
11501                 "%sw_param0 = OpFunctionParameter %${tt_src0}\n"
11502                 "%sw_param1 = OpFunctionParameter %${tt_src1}\n"
11503                 "%sw_paramn = OpFunctionParameter %i32\n"
11504                 " %sw_entry = OpLabel\n"
11505                 "   %modulo = OpSMod %i32 %sw_paramn %c_i32_cc\n"
11506                 "             OpSelectionMerge %switch_e None\n"
11507                 "             OpSwitch %modulo %default ${case_list}\n"
11508                 "${case_bodies}"
11509                 "%default   = OpLabel\n"
11510                 "             OpUnreachable\n" // Unreachable default case for switch statement
11511                 "%switch_e  = OpLabel\n"
11512                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11513                 "             OpFunctionEnd\n"
11514         );
11515
11516         const StringTemplate testCaseBody
11517         (
11518                 "%case_${case_ndx}    = OpLabel\n"
11519                 "%val_dst_${case_ndx} = OpVectorShuffle %${tt_dst} %sw_param0 %sw_param1 ${shuffle}\n"
11520                 "             OpReturnValue %val_dst_${case_ndx}\n"
11521         );
11522
11523         for (deUint32 dstTypeIdx = 0; dstTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++dstTypeIdx)
11524         {
11525                 const TestType& dstType                 = testTypes[dstTypeIdx];
11526
11527                 for (deUint32 comp0Idx = 0; comp0Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp0Idx)
11528                 {
11529                         const TestType& src0Type        = testTypes[comp0Idx];
11530
11531                         for (deUint32 comp1Idx = 0; comp1Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp1Idx)
11532                         {
11533                                 const TestType&                 src1Type                        = testTypes[comp1Idx];
11534                                 const deUint32                  input0Stride            = (src0Type.typeComponents == 3) ? 4 : src0Type.typeComponents;
11535                                 const deUint32                  input1Stride            = (src1Type.typeComponents == 3) ? 4 : src1Type.typeComponents;
11536                                 const deUint32                  outputStride            = (dstType.typeComponents == 3) ? 4 : dstType.typeComponents;
11537                                 const vector<deFloat16> float16Input0Data       = getFloat16s(rnd, input0Stride * numDataPoints);
11538                                 const vector<deFloat16> float16Input1Data       = getFloat16s(rnd, input1Stride * numDataPoints);
11539                                 const vector<deFloat16> float16OutputDummy      (outputStride * numDataPoints, 0);
11540                                 const string                    testName                        = de::toString(dstType.typeComponents) + de::toString(src0Type.typeComponents) + de::toString(src1Type.typeComponents);
11541                                 deUint32                                caseCount                       = 0;
11542                                 SpecResource                    specResource;
11543                                 map<string, string>             specs;
11544                                 vector<string>                  extensions;
11545                                 VulkanFeatures                  features;
11546                                 string                                  caseBodies;
11547                                 string                                  caseList;
11548
11549                                 // Generate case
11550                                 {
11551                                         vector<string>  componentList;
11552
11553                                         // Generate component possible indices for OpVectorShuffle for components 0 and 1 in output vector
11554                                         {
11555                                                 deUint32                caseNo          = 0;
11556
11557                                                 for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < src0Type.typeComponents; ++comp0IdxLocal)
11558                                                         componentList.push_back(de::toString(caseNo++));
11559                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < src1Type.typeComponents; ++comp1IdxLocal)
11560                                                         componentList.push_back(de::toString(caseNo++));
11561                                                 componentList.push_back("0xFFFFFFFF");
11562                                         }
11563
11564                                         for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < componentList.size(); ++comp0IdxLocal)
11565                                         {
11566                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < componentList.size(); ++comp1IdxLocal)
11567                                                 {
11568                                                         map<string, string>     specCase;
11569                                                         string                          shuffle         = componentList[comp0IdxLocal] + " " + componentList[comp1IdxLocal];
11570
11571                                                         for (deUint32 compIdx = 2; compIdx < dstType.typeComponents; ++compIdx)
11572                                                                 shuffle += " " + de::toString(compIdx - 2);
11573
11574                                                         specCase["case_ndx"]    = de::toString(caseCount);
11575                                                         specCase["shuffle"]             = shuffle;
11576                                                         specCase["tt_dst"]              = dstType.typeName;
11577
11578                                                         caseBodies      += testCaseBody.specialize(specCase);
11579                                                         caseList        += de::toString(caseCount) + " %case_" + de::toString(caseCount) + " ";
11580
11581                                                         caseCount++;
11582                                                 }
11583                                         }
11584                                 }
11585
11586                                 specs["num_data_points"]        = de::toString(numDataPoints);
11587                                 specs["tt_dst"]                         = dstType.typeName;
11588                                 specs["tt_src0"]                        = src0Type.typeName;
11589                                 specs["tt_src1"]                        = src1Type.typeName;
11590                                 specs["case_bodies"]            = caseBodies;
11591                                 specs["case_list"]                      = caseList;
11592                                 specs["case_count"]                     = de::toString(caseCount);
11593
11594                                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11595                                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11596                                 fragments["decoration"]         = decoration.specialize(specs);
11597                                 fragments["pre_main"]           = preMain.specialize(specs);
11598                                 fragments["testfun"]            = testFun.specialize(specs);
11599
11600                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input0Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11601                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input1Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11602                                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11603                                 specResource.verifyIO = getFloat16VectorShuffleVerifyIOFunc(dstType.typeComponents, src0Type.typeComponents, src1Type.typeComponents);
11604
11605                                 extensions.push_back("VK_KHR_16bit_storage");
11606                                 extensions.push_back("VK_KHR_shader_float16_int8");
11607
11608                                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11609                                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11610
11611                                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11612                         }
11613                 }
11614         }
11615
11616         return testGroup.release();
11617 }
11618
11619 bool compareFP16CompositeFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11620 {
11621         if (inputs.size() != 1 || outputAllocs.size() != 1)
11622                 return false;
11623
11624         vector<deUint8> input1Bytes;
11625
11626         inputs[0].getBytes(input1Bytes);
11627
11628         DE_ASSERT(input1Bytes.size() > 0);
11629         DE_ASSERT(input1Bytes.size() % sizeof(deFloat16) == 0);
11630
11631         const size_t                    iterations              = input1Bytes.size() / sizeof(deFloat16);
11632         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
11633         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11634         const deFloat16                 exceptionValue  = tcu::Float16(-1.0).bits();
11635         std::string                             error;
11636
11637         for (size_t idx = 0; idx < iterations; ++idx)
11638         {
11639                 if (input1AsFP16[idx] == exceptionValue)
11640                         continue;
11641
11642                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
11643                 {
11644                         log << TestLog::Message << "At " << idx << ":" << error << TestLog::EndMessage;
11645
11646                         return false;
11647                 }
11648         }
11649
11650         return true;
11651 }
11652
11653 template<class SpecResource>
11654 tcu::TestCaseGroup* createFloat16CompositeConstructSet (tcu::TestContext& testCtx)
11655 {
11656         de::MovePtr<tcu::TestCaseGroup>         testGroup                               (new tcu::TestCaseGroup(testCtx, "opcompositeconstruct", "OpCompositeConstruct tests"));
11657         const deUint32                                          numElements                             = 8;
11658         const string                                            testName                                = "struct";
11659         const deUint32                                          structItemsCount                = 88;
11660         const deUint32                                          exceptionIndices[]              = { 1, 7, 15, 17, 25, 33, 51, 55, 59, 63, 67, 71, 84, 85, 86, 87 };
11661         const deFloat16                                         exceptionValue                  = tcu::Float16(-1.0).bits();
11662         const deUint32                                          fieldModifier                   = 2;
11663         const deUint32                                          fieldModifiedMulIndex   = 60;
11664         const deUint32                                          fieldModifiedAddIndex   = 66;
11665
11666         const StringTemplate preMain
11667         (
11668                 "    %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11669                 "          %f16 = OpTypeFloat 16\n"
11670                 "        %v2f16 = OpTypeVector %f16 2\n"
11671                 "        %v3f16 = OpTypeVector %f16 3\n"
11672                 "        %v4f16 = OpTypeVector %f16 4\n"
11673                 "    %c_f16_mod = OpConstant %f16 ${field_modifier}\n"
11674
11675                 "${consts}"
11676
11677                 "      %c_u32_5 = OpConstant %u32 5\n"
11678
11679                 " %f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11680                 " %v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11681                 " %v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11682                 " %v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11683                 " %v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11684                 " %struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11685                 " %struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11686                 " %st_test      = OpTypeStruct %f16 %v2f16 %v3f16 %v4f16 %f16arr3 %struct16arr3 %v2f16arr5 %f16 %v3f16arr5 %v4f16arr3\n"
11687
11688                 "        %up_st = OpTypePointer Uniform %st_test\n"
11689                 "        %ra_st = OpTypeArray %st_test %c_i32_ndp\n"
11690                 "      %SSBO_st = OpTypeStruct %ra_st\n"
11691                 "   %up_SSBO_st = OpTypePointer Uniform %SSBO_st\n"
11692
11693                 "     %ssbo_dst = OpVariable %up_SSBO_st Uniform\n"
11694         );
11695
11696         const StringTemplate decoration
11697         (
11698                 "OpDecorate %SSBO_st BufferBlock\n"
11699                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11700                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11701                 "OpDecorate %ssbo_dst Binding 1\n"
11702
11703                 "OpMemberDecorate %SSBO_st 0 Offset 0\n"
11704
11705                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11706                 "OpMemberDecorate %struct16 0 Offset 0\n"
11707                 "OpMemberDecorate %struct16 1 Offset 4\n"
11708                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11709                 "OpDecorate %f16arr3 ArrayStride 2\n"
11710                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11711                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11712                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11713
11714                 "OpMemberDecorate %st_test 0 Offset 0\n"
11715                 "OpMemberDecorate %st_test 1 Offset 4\n"
11716                 "OpMemberDecorate %st_test 2 Offset 8\n"
11717                 "OpMemberDecorate %st_test 3 Offset 16\n"
11718                 "OpMemberDecorate %st_test 4 Offset 24\n"
11719                 "OpMemberDecorate %st_test 5 Offset 32\n"
11720                 "OpMemberDecorate %st_test 6 Offset 80\n"
11721                 "OpMemberDecorate %st_test 7 Offset 100\n"
11722                 "OpMemberDecorate %st_test 8 Offset 104\n"
11723                 "OpMemberDecorate %st_test 9 Offset 144\n"
11724         );
11725
11726         const StringTemplate testFun
11727         (
11728                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11729                 "     %param = OpFunctionParameter %v4f32\n"
11730                 "     %entry = OpLabel\n"
11731
11732                 "         %i = OpVariable %fp_i32 Function\n"
11733                 "              OpStore %i %c_i32_0\n"
11734
11735                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11736                 "              OpSelectionMerge %end_if None\n"
11737                 "              OpBranchConditional %will_run %run_test %end_if\n"
11738
11739                 "  %run_test = OpLabel\n"
11740                 "              OpBranch %loop\n"
11741
11742                 "      %loop = OpLabel\n"
11743                 "     %i_cmp = OpLoad %i32 %i\n"
11744                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11745                 "              OpLoopMerge %merge %next None\n"
11746                 "              OpBranchConditional %lt %write %merge\n"
11747
11748                 "     %write = OpLabel\n"
11749                 "       %ndx = OpLoad %i32 %i\n"
11750
11751                 "      %fld1 = OpCompositeConstruct %v2f16 %c_f16_2 %c_f16_3\n"
11752                 "      %fld2 = OpCompositeConstruct %v3f16 %c_f16_4 %c_f16_5 %c_f16_6\n"
11753                 "      %fld3 = OpCompositeConstruct %v4f16 %c_f16_8 %c_f16_9 %c_f16_10 %c_f16_11\n"
11754
11755                 "      %fld4 = OpCompositeConstruct %f16arr3 %c_f16_12 %c_f16_13 %c_f16_14\n"
11756
11757                 "%fld5_0_1_0 = OpCompositeConstruct %v2f16 %c_f16_18 %c_f16_19\n"
11758                 "%fld5_0_1_1 = OpCompositeConstruct %v2f16 %c_f16_20 %c_f16_21\n"
11759                 "%fld5_0_1_2 = OpCompositeConstruct %v2f16 %c_f16_22 %c_f16_23\n"
11760                 "  %fld5_0_1 = OpCompositeConstruct %v2f16arr3 %fld5_0_1_0 %fld5_0_1_1 %fld5_0_1_2\n"
11761                 "    %fld5_0 = OpCompositeConstruct %struct16 %c_f16_16 %fld5_0_1\n"
11762
11763                 "%fld5_1_1_0 = OpCompositeConstruct %v2f16 %c_f16_26 %c_f16_27\n"
11764                 "%fld5_1_1_1 = OpCompositeConstruct %v2f16 %c_f16_28 %c_f16_29\n"
11765                 "%fld5_1_1_2 = OpCompositeConstruct %v2f16 %c_f16_30 %c_f16_31\n"
11766                 "  %fld5_1_1 = OpCompositeConstruct %v2f16arr3 %fld5_1_1_0 %fld5_1_1_1 %fld5_1_1_2\n"
11767                 "    %fld5_1 = OpCompositeConstruct %struct16 %c_f16_24 %fld5_1_1\n"
11768
11769                 "%fld5_2_1_0 = OpCompositeConstruct %v2f16 %c_f16_34 %c_f16_35\n"
11770                 "%fld5_2_1_1 = OpCompositeConstruct %v2f16 %c_f16_36 %c_f16_37\n"
11771                 "%fld5_2_1_2 = OpCompositeConstruct %v2f16 %c_f16_38 %c_f16_39\n"
11772                 "  %fld5_2_1 = OpCompositeConstruct %v2f16arr3 %fld5_2_1_0 %fld5_2_1_1 %fld5_2_1_2\n"
11773                 "    %fld5_2 = OpCompositeConstruct %struct16 %c_f16_32 %fld5_2_1\n"
11774
11775                 "      %fld5 = OpCompositeConstruct %struct16arr3 %fld5_0 %fld5_1 %fld5_2\n"
11776
11777                 "    %fld6_0 = OpCompositeConstruct %v2f16 %c_f16_40 %c_f16_41\n"
11778                 "    %fld6_1 = OpCompositeConstruct %v2f16 %c_f16_42 %c_f16_43\n"
11779                 "    %fld6_2 = OpCompositeConstruct %v2f16 %c_f16_44 %c_f16_45\n"
11780                 "    %fld6_3 = OpCompositeConstruct %v2f16 %c_f16_46 %c_f16_47\n"
11781                 "    %fld6_4 = OpCompositeConstruct %v2f16 %c_f16_48 %c_f16_49\n"
11782                 "      %fld6 = OpCompositeConstruct %v2f16arr5 %fld6_0 %fld6_1 %fld6_2 %fld6_3 %fld6_4\n"
11783
11784                 "      %fndx = OpConvertSToF %f16 %ndx\n"
11785                 "  %fld8_2a0 = OpFMul %f16 %fndx %c_f16_mod\n"
11786                 "  %fld8_3b1 = OpFAdd %f16 %fndx %c_f16_mod\n"
11787
11788                 "   %fld8_2a = OpCompositeConstruct %v2f16 %fld8_2a0 %c_f16_61\n"
11789                 "   %fld8_3b = OpCompositeConstruct %v2f16 %c_f16_65 %fld8_3b1\n"
11790                 "    %fld8_0 = OpCompositeConstruct %v3f16 %c_f16_52 %c_f16_53 %c_f16_54\n"
11791                 "    %fld8_1 = OpCompositeConstruct %v3f16 %c_f16_56 %c_f16_57 %c_f16_58\n"
11792                 "    %fld8_2 = OpCompositeConstruct %v3f16 %fld8_2a %c_f16_62\n"
11793                 "    %fld8_3 = OpCompositeConstruct %v3f16 %c_f16_64 %fld8_3b\n"
11794                 "    %fld8_4 = OpCompositeConstruct %v3f16 %c_f16_68 %c_f16_69 %c_f16_70\n"
11795                 "      %fld8 = OpCompositeConstruct %v3f16arr5 %fld8_0 %fld8_1 %fld8_2 %fld8_3 %fld8_4\n"
11796
11797                 "    %fld9_0 = OpCompositeConstruct %v4f16 %c_f16_72 %c_f16_73 %c_f16_74 %c_f16_75\n"
11798                 "    %fld9_1 = OpCompositeConstruct %v4f16 %c_f16_76 %c_f16_77 %c_f16_78 %c_f16_79\n"
11799                 "    %fld9_2 = OpCompositeConstruct %v4f16 %c_f16_80 %c_f16_81 %c_f16_82 %c_f16_83\n"
11800                 "      %fld9 = OpCompositeConstruct %v4f16arr3 %fld9_0 %fld9_1 %fld9_2\n"
11801
11802                 "    %st_val = OpCompositeConstruct %st_test %c_f16_0 %fld1 %fld2 %fld3 %fld4 %fld5 %fld6 %c_f16_50 %fld8 %fld9\n"
11803                 "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %ndx\n"
11804                 "              OpStore %dst %st_val\n"
11805
11806                 "              OpBranch %next\n"
11807
11808                 "      %next = OpLabel\n"
11809                 "     %i_cur = OpLoad %i32 %i\n"
11810                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11811                 "              OpStore %i %i_new\n"
11812                 "              OpBranch %loop\n"
11813
11814                 "     %merge = OpLabel\n"
11815                 "              OpBranch %end_if\n"
11816                 "    %end_if = OpLabel\n"
11817                 "              OpReturnValue %param\n"
11818                 "              OpFunctionEnd\n"
11819         );
11820
11821         {
11822                 SpecResource            specResource;
11823                 map<string, string>     specs;
11824                 VulkanFeatures          features;
11825                 map<string, string>     fragments;
11826                 vector<string>          extensions;
11827                 vector<deFloat16>       expectedOutput;
11828                 string                          consts;
11829
11830                 for (deUint32 elementNdx = 0; elementNdx < numElements; ++elementNdx)
11831                 {
11832                         vector<deFloat16>       expectedIterationOutput;
11833
11834                         for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
11835                                 expectedIterationOutput.push_back(tcu::Float16(float(structItemNdx)).bits());
11836
11837                         for (deUint32 structItemNdx = 0; structItemNdx < DE_LENGTH_OF_ARRAY(exceptionIndices); ++structItemNdx)
11838                                 expectedIterationOutput[exceptionIndices[structItemNdx]] = exceptionValue;
11839
11840                         expectedIterationOutput[fieldModifiedMulIndex] = tcu::Float16(float(elementNdx * fieldModifier)).bits();
11841                         expectedIterationOutput[fieldModifiedAddIndex] = tcu::Float16(float(elementNdx + fieldModifier)).bits();
11842
11843                         expectedOutput.insert(expectedOutput.end(), expectedIterationOutput.begin(), expectedIterationOutput.end());
11844                 }
11845
11846                 for (deUint32 i = 0; i < structItemsCount; ++i)
11847                         consts += "     %c_f16_" + de::toString(i) + " = OpConstant %f16 "  + de::toString(i) + "\n";
11848
11849                 specs["num_elements"]           = de::toString(numElements);
11850                 specs["struct_item_size"]       = de::toString(structItemsCount * sizeof(deFloat16));
11851                 specs["field_modifier"]         = de::toString(fieldModifier);
11852                 specs["consts"]                         = consts;
11853
11854                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11855                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11856                 fragments["decoration"]         = decoration.specialize(specs);
11857                 fragments["pre_main"]           = preMain.specialize(specs);
11858                 fragments["testfun"]            = testFun.specialize(specs);
11859
11860                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11861                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11862                 specResource.verifyIO = compareFP16CompositeFunc;
11863
11864                 extensions.push_back("VK_KHR_16bit_storage");
11865                 extensions.push_back("VK_KHR_shader_float16_int8");
11866
11867                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11868                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11869
11870                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11871         }
11872
11873         return testGroup.release();
11874 }
11875
11876 template<class SpecResource>
11877 tcu::TestCaseGroup* createFloat16CompositeInsertExtractSet (tcu::TestContext& testCtx, const char* op)
11878 {
11879         de::MovePtr<tcu::TestCaseGroup>         testGroup               (new tcu::TestCaseGroup(testCtx, de::toLower(op).c_str(), op));
11880         const deFloat16                                         exceptionValue  = tcu::Float16(-1.0).bits();
11881         const string                                            opName                  (op);
11882         const deUint32                                          opIndex                 = (opName == "OpCompositeInsert") ? 0
11883                                                                                                                 : (opName == "OpCompositeExtract") ? 1
11884                                                                                                                 : -1;
11885
11886         const StringTemplate preMain
11887         (
11888                 "   %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11889                 "         %f16 = OpTypeFloat 16\n"
11890                 "       %v2f16 = OpTypeVector %f16 2\n"
11891                 "       %v3f16 = OpTypeVector %f16 3\n"
11892                 "       %v4f16 = OpTypeVector %f16 4\n"
11893                 "    %c_f16_na = OpConstant %f16 -1.0\n"
11894                 "     %c_u32_5 = OpConstant %u32 5\n"
11895
11896                 "%f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11897                 "%v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11898                 "%v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11899                 "%v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11900                 "%v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11901                 "%struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11902                 "%struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11903                 "%st_test      = OpTypeStruct %${field_type}\n"
11904
11905                 "      %up_f16 = OpTypePointer Uniform %f16\n"
11906                 "       %up_st = OpTypePointer Uniform %st_test\n"
11907                 "      %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
11908                 "       %ra_st = OpTypeArray %st_test %c_i32_1\n"
11909
11910                 "${op_premain_decls}"
11911
11912                 " %up_SSBO_src = OpTypePointer Uniform %SSBO_src\n"
11913                 " %up_SSBO_dst = OpTypePointer Uniform %SSBO_dst\n"
11914
11915                 "    %ssbo_src = OpVariable %up_SSBO_src Uniform\n"
11916                 "    %ssbo_dst = OpVariable %up_SSBO_dst Uniform\n"
11917         );
11918
11919         const StringTemplate decoration
11920         (
11921                 "OpDecorate %SSBO_src BufferBlock\n"
11922                 "OpDecorate %SSBO_dst BufferBlock\n"
11923                 "OpDecorate %ra_f16 ArrayStride 2\n"
11924                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11925                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11926                 "OpDecorate %ssbo_src Binding 0\n"
11927                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11928                 "OpDecorate %ssbo_dst Binding 1\n"
11929
11930                 "OpMemberDecorate %SSBO_src 0 Offset 0\n"
11931                 "OpMemberDecorate %SSBO_dst 0 Offset 0\n"
11932
11933                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11934                 "OpMemberDecorate %struct16 0 Offset 0\n"
11935                 "OpMemberDecorate %struct16 1 Offset 4\n"
11936                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11937                 "OpDecorate %f16arr3 ArrayStride 2\n"
11938                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11939                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11940                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11941
11942                 "OpMemberDecorate %st_test 0 Offset 0\n"
11943         );
11944
11945         const StringTemplate testFun
11946         (
11947                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11948                 "     %param = OpFunctionParameter %v4f32\n"
11949                 "     %entry = OpLabel\n"
11950
11951                 "         %i = OpVariable %fp_i32 Function\n"
11952                 "              OpStore %i %c_i32_0\n"
11953
11954                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11955                 "              OpSelectionMerge %end_if None\n"
11956                 "              OpBranchConditional %will_run %run_test %end_if\n"
11957
11958                 "  %run_test = OpLabel\n"
11959                 "              OpBranch %loop\n"
11960
11961                 "      %loop = OpLabel\n"
11962                 "     %i_cmp = OpLoad %i32 %i\n"
11963                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11964                 "              OpLoopMerge %merge %next None\n"
11965                 "              OpBranchConditional %lt %write %merge\n"
11966
11967                 "     %write = OpLabel\n"
11968                 "       %ndx = OpLoad %i32 %i\n"
11969
11970                 "${op_sw_fun_call}"
11971
11972                 "              OpStore %dst %val_dst\n"
11973                 "              OpBranch %next\n"
11974
11975                 "      %next = OpLabel\n"
11976                 "     %i_cur = OpLoad %i32 %i\n"
11977                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11978                 "              OpStore %i %i_new\n"
11979                 "              OpBranch %loop\n"
11980
11981                 "     %merge = OpLabel\n"
11982                 "              OpBranch %end_if\n"
11983                 "    %end_if = OpLabel\n"
11984                 "              OpReturnValue %param\n"
11985                 "              OpFunctionEnd\n"
11986
11987                 "${op_sw_fun_header}"
11988                 " %sw_param = OpFunctionParameter %st_test\n"
11989                 "%sw_paramn = OpFunctionParameter %i32\n"
11990                 " %sw_entry = OpLabel\n"
11991                 "             OpSelectionMerge %switch_e None\n"
11992                 "             OpSwitch %sw_paramn %default ${case_list}\n"
11993
11994                 "${case_bodies}"
11995
11996                 "%default   = OpLabel\n"
11997                 "             OpReturnValue ${op_case_default_value}\n"
11998                 "%switch_e  = OpLabel\n"
11999                 "             OpUnreachable\n" // Unreachable merge block for switch statement
12000                 "             OpFunctionEnd\n"
12001         );
12002
12003         const StringTemplate testCaseBody
12004         (
12005                 "%case_${case_ndx}    = OpLabel\n"
12006                 "%val_ret_${case_ndx} = ${op_name} ${op_args_part} ${access_path}\n"
12007                 "             OpReturnValue %val_ret_${case_ndx}\n"
12008         );
12009
12010         struct OpParts
12011         {
12012                 const char*     premainDecls;
12013                 const char*     swFunCall;
12014                 const char*     swFunHeader;
12015                 const char*     caseDefaultValue;
12016                 const char*     argsPartial;
12017         };
12018
12019         OpParts                                                         opPartsArray[]                  =
12020         {
12021                 // OpCompositeInsert
12022                 {
12023                         "       %fun_t = OpTypeFunction %st_test %f16 %st_test %i32\n"
12024                         "    %SSBO_src = OpTypeStruct %ra_f16\n"
12025                         "    %SSBO_dst = OpTypeStruct %ra_st\n",
12026
12027                         "       %src = OpAccessChain %up_f16 %ssbo_src %c_i32_0 %ndx\n"
12028                         "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %c_i32_0\n"
12029                         "   %val_new = OpLoad %f16 %src\n"
12030                         "   %val_old = OpLoad %st_test %dst\n"
12031                         "   %val_dst = OpFunctionCall %st_test %sw_fun %val_new %val_old %ndx\n",
12032
12033                         "   %sw_fun = OpFunction %st_test None %fun_t\n"
12034                         "%sw_paramv = OpFunctionParameter %f16\n",
12035
12036                         "%sw_param",
12037
12038                         "%st_test %sw_paramv %sw_param",
12039                 },
12040                 // OpCompositeExtract
12041                 {
12042                         "       %fun_t = OpTypeFunction %f16 %st_test %i32\n"
12043                         "    %SSBO_src = OpTypeStruct %ra_st\n"
12044                         "    %SSBO_dst = OpTypeStruct %ra_f16\n",
12045
12046                         "       %src = OpAccessChain %up_st %ssbo_src %c_i32_0 %c_i32_0\n"
12047                         "       %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
12048                         "   %val_src = OpLoad %st_test %src\n"
12049                         "   %val_dst = OpFunctionCall %f16 %sw_fun %val_src %ndx\n",
12050
12051                         "   %sw_fun = OpFunction %f16 None %fun_t\n",
12052
12053                         "%c_f16_na",
12054
12055                         "%f16 %sw_param",
12056                 },
12057         };
12058
12059         DE_ASSERT(opIndex >= 0 && opIndex < DE_LENGTH_OF_ARRAY(opPartsArray));
12060
12061         const char*     accessPathF16[] =
12062         {
12063                 "0",                    // %f16
12064                 DE_NULL,
12065         };
12066         const char*     accessPathV2F16[] =
12067         {
12068                 "0 0",                  // %v2f16
12069                 "0 1",
12070         };
12071         const char*     accessPathV3F16[] =
12072         {
12073                 "0 0",                  // %v3f16
12074                 "0 1",
12075                 "0 2",
12076                 DE_NULL,
12077         };
12078         const char*     accessPathV4F16[] =
12079         {
12080                 "0 0",                  // %v4f16"
12081                 "0 1",
12082                 "0 2",
12083                 "0 3",
12084         };
12085         const char*     accessPathF16Arr3[] =
12086         {
12087                 "0 0",                  // %f16arr3
12088                 "0 1",
12089                 "0 2",
12090                 DE_NULL,
12091         };
12092         const char*     accessPathStruct16Arr3[] =
12093         {
12094                 "0 0 0",                // %struct16arr3
12095                 DE_NULL,
12096                 "0 0 1 0 0",
12097                 "0 0 1 0 1",
12098                 "0 0 1 1 0",
12099                 "0 0 1 1 1",
12100                 "0 0 1 2 0",
12101                 "0 0 1 2 1",
12102                 "0 1 0",
12103                 DE_NULL,
12104                 "0 1 1 0 0",
12105                 "0 1 1 0 1",
12106                 "0 1 1 1 0",
12107                 "0 1 1 1 1",
12108                 "0 1 1 2 0",
12109                 "0 1 1 2 1",
12110                 "0 2 0",
12111                 DE_NULL,
12112                 "0 2 1 0 0",
12113                 "0 2 1 0 1",
12114                 "0 2 1 1 0",
12115                 "0 2 1 1 1",
12116                 "0 2 1 2 0",
12117                 "0 2 1 2 1",
12118         };
12119         const char*     accessPathV2F16Arr5[] =
12120         {
12121                 "0 0 0",                // %v2f16arr5
12122                 "0 0 1",
12123                 "0 1 0",
12124                 "0 1 1",
12125                 "0 2 0",
12126                 "0 2 1",
12127                 "0 3 0",
12128                 "0 3 1",
12129                 "0 4 0",
12130                 "0 4 1",
12131         };
12132         const char*     accessPathV3F16Arr5[] =
12133         {
12134                 "0 0 0",                // %v3f16arr5
12135                 "0 0 1",
12136                 "0 0 2",
12137                 DE_NULL,
12138                 "0 1 0",
12139                 "0 1 1",
12140                 "0 1 2",
12141                 DE_NULL,
12142                 "0 2 0",
12143                 "0 2 1",
12144                 "0 2 2",
12145                 DE_NULL,
12146                 "0 3 0",
12147                 "0 3 1",
12148                 "0 3 2",
12149                 DE_NULL,
12150                 "0 4 0",
12151                 "0 4 1",
12152                 "0 4 2",
12153                 DE_NULL,
12154         };
12155         const char*     accessPathV4F16Arr3[] =
12156         {
12157                 "0 0 0",                // %v4f16arr3
12158                 "0 0 1",
12159                 "0 0 2",
12160                 "0 0 3",
12161                 "0 1 0",
12162                 "0 1 1",
12163                 "0 1 2",
12164                 "0 1 3",
12165                 "0 2 0",
12166                 "0 2 1",
12167                 "0 2 2",
12168                 "0 2 3",
12169                 DE_NULL,
12170                 DE_NULL,
12171                 DE_NULL,
12172                 DE_NULL,
12173         };
12174
12175         struct TypeTestParameters
12176         {
12177                 const char*             name;
12178                 size_t                  accessPathLength;
12179                 const char**    accessPath;
12180         };
12181
12182         const TypeTestParameters typeTestParameters[] =
12183         {
12184                 {       "f16",                  DE_LENGTH_OF_ARRAY(accessPathF16),                      accessPathF16                   },
12185                 {       "v2f16",                DE_LENGTH_OF_ARRAY(accessPathV2F16),            accessPathV2F16                 },
12186                 {       "v3f16",                DE_LENGTH_OF_ARRAY(accessPathV3F16),            accessPathV3F16                 },
12187                 {       "v4f16",                DE_LENGTH_OF_ARRAY(accessPathV4F16),            accessPathV4F16                 },
12188                 {       "f16arr3",              DE_LENGTH_OF_ARRAY(accessPathF16Arr3),          accessPathF16Arr3               },
12189                 {       "v2f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV2F16Arr5),        accessPathV2F16Arr5             },
12190                 {       "v3f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV3F16Arr5),        accessPathV3F16Arr5             },
12191                 {       "v4f16arr3",    DE_LENGTH_OF_ARRAY(accessPathV4F16Arr3),        accessPathV4F16Arr3             },
12192                 {       "struct16arr3", DE_LENGTH_OF_ARRAY(accessPathStruct16Arr3),     accessPathStruct16Arr3  },
12193         };
12194
12195         for (size_t typeTestNdx = 0; typeTestNdx < DE_LENGTH_OF_ARRAY(typeTestParameters); ++typeTestNdx)
12196         {
12197                 const OpParts           opParts                         = opPartsArray[opIndex];
12198                 const string            testName                        = typeTestParameters[typeTestNdx].name;
12199                 const size_t            structItemsCount        = typeTestParameters[typeTestNdx].accessPathLength;
12200                 const char**            accessPath                      = typeTestParameters[typeTestNdx].accessPath;
12201                 SpecResource            specResource;
12202                 map<string, string>     specs;
12203                 VulkanFeatures          features;
12204                 map<string, string>     fragments;
12205                 vector<string>          extensions;
12206                 vector<deFloat16>       inputFP16;
12207                 vector<deFloat16>       dummyFP16Output;
12208
12209                 // Generate values for input
12210                 inputFP16.reserve(structItemsCount);
12211                 for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
12212                         inputFP16.push_back((accessPath[structItemNdx] == DE_NULL) ? exceptionValue : tcu::Float16(float(structItemNdx)).bits());
12213
12214                 dummyFP16Output.resize(structItemsCount);
12215
12216                 // Generate cases for OpSwitch
12217                 {
12218                         string  caseBodies;
12219                         string  caseList;
12220
12221                         for (deUint32 caseNdx = 0; caseNdx < structItemsCount; ++caseNdx)
12222                                 if (accessPath[caseNdx] != DE_NULL)
12223                                 {
12224                                         map<string, string>     specCase;
12225
12226                                         specCase["case_ndx"]            = de::toString(caseNdx);
12227                                         specCase["access_path"]         = accessPath[caseNdx];
12228                                         specCase["op_args_part"]        = opParts.argsPartial;
12229                                         specCase["op_name"]                     = opName;
12230
12231                                         caseBodies      += testCaseBody.specialize(specCase);
12232                                         caseList        += de::toString(caseNdx) + " %case_" + de::toString(caseNdx) + " ";
12233                                 }
12234
12235                         specs["case_bodies"]    = caseBodies;
12236                         specs["case_list"]              = caseList;
12237                 }
12238
12239                 specs["num_elements"]                   = de::toString(structItemsCount);
12240                 specs["field_type"]                             = typeTestParameters[typeTestNdx].name;
12241                 specs["struct_item_size"]               = de::toString(structItemsCount * sizeof(deFloat16));
12242                 specs["op_premain_decls"]               = opParts.premainDecls;
12243                 specs["op_sw_fun_call"]                 = opParts.swFunCall;
12244                 specs["op_sw_fun_header"]               = opParts.swFunHeader;
12245                 specs["op_case_default_value"]  = opParts.caseDefaultValue;
12246
12247                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
12248                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
12249                 fragments["decoration"]         = decoration.specialize(specs);
12250                 fragments["pre_main"]           = preMain.specialize(specs);
12251                 fragments["testfun"]            = testFun.specialize(specs);
12252
12253                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputFP16)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12254                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(dummyFP16Output)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12255                 specResource.verifyIO = compareFP16CompositeFunc;
12256
12257                 extensions.push_back("VK_KHR_16bit_storage");
12258                 extensions.push_back("VK_KHR_shader_float16_int8");
12259
12260                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
12261                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
12262
12263                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
12264         }
12265
12266         return testGroup.release();
12267 }
12268
12269 struct fp16PerComponent
12270 {
12271         fp16PerComponent()
12272                 : flavor(0)
12273                 , floatFormat16 (-14, 15, 10, true)
12274                 , outCompCount(0)
12275                 , argCompCount(3, 0)
12276         {
12277         }
12278
12279         bool                    callOncePerComponent    ()                                                                      { return true; }
12280         deUint32                getComponentValidity    ()                                                                      { return static_cast<deUint32>(-1); }
12281
12282         virtual double  getULPs                                 (vector<const deFloat16*>&)                     { return 1.0; }
12283         virtual double  getMin                                  (double value, double ulps)                     { return value - floatFormat16.ulp(deAbs(value), ulps); }
12284         virtual double  getMax                                  (double value, double ulps)                     { return value + floatFormat16.ulp(deAbs(value), ulps); }
12285
12286         virtual size_t  getFlavorCount                  ()                                                                      { return flavorNames.empty() ? 1 : flavorNames.size(); }
12287         virtual void    setFlavor                               (size_t flavorNo)                                       { DE_ASSERT(flavorNo < getFlavorCount()); flavor = flavorNo; }
12288         virtual size_t  getFlavor                               ()                                                                      { return flavor; }
12289         virtual string  getCurrentFlavorName    ()                                                                      { return flavorNames.empty() ? string("") : flavorNames[getFlavor()]; }
12290
12291         virtual void    setOutCompCount                 (size_t compCount)                                      { outCompCount = compCount; }
12292         virtual size_t  getOutCompCount                 ()                                                                      { return outCompCount; }
12293
12294         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)        { argCompCount[argNo] = compCount; }
12295         virtual size_t  getArgCompCount                 (size_t argNo)                                          { return argCompCount[argNo]; }
12296
12297 protected:
12298         size_t                          flavor;
12299         tcu::FloatFormat        floatFormat16;
12300         size_t                          outCompCount;
12301         vector<size_t>          argCompCount;
12302         vector<string>          flavorNames;
12303 };
12304
12305 struct fp16OpFNegate : public fp16PerComponent
12306 {
12307         template <class fp16type>
12308         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12309         {
12310                 const fp16type  x               (*in[0]);
12311                 const double    d               (x.asDouble());
12312                 const double    result  (0.0 - d);
12313
12314                 out[0] = fp16type(result).bits();
12315                 min[0] = getMin(result, getULPs(in));
12316                 max[0] = getMax(result, getULPs(in));
12317
12318                 return true;
12319         }
12320 };
12321
12322 struct fp16Round : public fp16PerComponent
12323 {
12324         fp16Round() : fp16PerComponent()
12325         {
12326                 flavorNames.push_back("Floor(x+0.5)");
12327                 flavorNames.push_back("Floor(x-0.5)");
12328                 flavorNames.push_back("RoundEven");
12329         }
12330
12331         template<class fp16type>
12332         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12333         {
12334                 const fp16type  x               (*in[0]);
12335                 const double    d               (x.asDouble());
12336                 double                  result  (0.0);
12337
12338                 switch (flavor)
12339                 {
12340                         case 0:         result = deRound(d);            break;
12341                         case 1:         result = deFloor(d - 0.5);      break;
12342                         case 2:         result = deRoundEven(d);        break;
12343                         default:        TCU_THROW(InternalError, "Invalid flavor specified");
12344                 }
12345
12346                 out[0] = fp16type(result).bits();
12347                 min[0] = getMin(result, getULPs(in));
12348                 max[0] = getMax(result, getULPs(in));
12349
12350                 return true;
12351         }
12352 };
12353
12354 struct fp16RoundEven : public fp16PerComponent
12355 {
12356         template<class fp16type>
12357         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12358         {
12359                 const fp16type  x               (*in[0]);
12360                 const double    d               (x.asDouble());
12361                 const double    result  (deRoundEven(d));
12362
12363                 out[0] = fp16type(result).bits();
12364                 min[0] = getMin(result, getULPs(in));
12365                 max[0] = getMax(result, getULPs(in));
12366
12367                 return true;
12368         }
12369 };
12370
12371 struct fp16Trunc : public fp16PerComponent
12372 {
12373         template<class fp16type>
12374         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12375         {
12376                 const fp16type  x               (*in[0]);
12377                 const double    d               (x.asDouble());
12378                 const double    result  (deTrunc(d));
12379
12380                 out[0] = fp16type(result).bits();
12381                 min[0] = getMin(result, getULPs(in));
12382                 max[0] = getMax(result, getULPs(in));
12383
12384                 return true;
12385         }
12386 };
12387
12388 struct fp16FAbs : public fp16PerComponent
12389 {
12390         template<class fp16type>
12391         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12392         {
12393                 const fp16type  x               (*in[0]);
12394                 const double    d               (x.asDouble());
12395                 const double    result  (deAbs(d));
12396
12397                 out[0] = fp16type(result).bits();
12398                 min[0] = getMin(result, getULPs(in));
12399                 max[0] = getMax(result, getULPs(in));
12400
12401                 return true;
12402         }
12403 };
12404
12405 struct fp16FSign : public fp16PerComponent
12406 {
12407         template<class fp16type>
12408         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12409         {
12410                 const fp16type  x               (*in[0]);
12411                 const double    d               (x.asDouble());
12412                 const double    result  (deSign(d));
12413
12414                 if (x.isNaN())
12415                         return false;
12416
12417                 out[0] = fp16type(result).bits();
12418                 min[0] = getMin(result, getULPs(in));
12419                 max[0] = getMax(result, getULPs(in));
12420
12421                 return true;
12422         }
12423 };
12424
12425 struct fp16Floor : public fp16PerComponent
12426 {
12427         template<class fp16type>
12428         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12429         {
12430                 const fp16type  x               (*in[0]);
12431                 const double    d               (x.asDouble());
12432                 const double    result  (deFloor(d));
12433
12434                 out[0] = fp16type(result).bits();
12435                 min[0] = getMin(result, getULPs(in));
12436                 max[0] = getMax(result, getULPs(in));
12437
12438                 return true;
12439         }
12440 };
12441
12442 struct fp16Ceil : public fp16PerComponent
12443 {
12444         template<class fp16type>
12445         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12446         {
12447                 const fp16type  x               (*in[0]);
12448                 const double    d               (x.asDouble());
12449                 const double    result  (deCeil(d));
12450
12451                 out[0] = fp16type(result).bits();
12452                 min[0] = getMin(result, getULPs(in));
12453                 max[0] = getMax(result, getULPs(in));
12454
12455                 return true;
12456         }
12457 };
12458
12459 struct fp16Fract : public fp16PerComponent
12460 {
12461         template<class fp16type>
12462         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12463         {
12464                 const fp16type  x               (*in[0]);
12465                 const double    d               (x.asDouble());
12466                 const double    result  (deFrac(d));
12467
12468                 out[0] = fp16type(result).bits();
12469                 min[0] = getMin(result, getULPs(in));
12470                 max[0] = getMax(result, getULPs(in));
12471
12472                 return true;
12473         }
12474 };
12475
12476 struct fp16Radians : public fp16PerComponent
12477 {
12478         virtual double getULPs (vector<const deFloat16*>& in)
12479         {
12480                 DE_UNREF(in);
12481
12482                 return 2.5;
12483         }
12484
12485         template<class fp16type>
12486         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12487         {
12488                 const fp16type  x               (*in[0]);
12489                 const float             d               (x.asFloat());
12490                 const float             result  (deFloatRadians(d));
12491
12492                 out[0] = fp16type(result).bits();
12493                 min[0] = getMin(result, getULPs(in));
12494                 max[0] = getMax(result, getULPs(in));
12495
12496                 return true;
12497         }
12498 };
12499
12500 struct fp16Degrees : public fp16PerComponent
12501 {
12502         virtual double getULPs (vector<const deFloat16*>& in)
12503         {
12504                 DE_UNREF(in);
12505
12506                 return 2.5;
12507         }
12508
12509         template<class fp16type>
12510         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12511         {
12512                 const fp16type  x               (*in[0]);
12513                 const float             d               (x.asFloat());
12514                 const float             result  (deFloatDegrees(d));
12515
12516                 out[0] = fp16type(result).bits();
12517                 min[0] = getMin(result, getULPs(in));
12518                 max[0] = getMax(result, getULPs(in));
12519
12520                 return true;
12521         }
12522 };
12523
12524 struct fp16Sin : public fp16PerComponent
12525 {
12526         template<class fp16type>
12527         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12528         {
12529                 const fp16type  x                       (*in[0]);
12530                 const double    d                       (x.asDouble());
12531                 const double    result          (deSin(d));
12532                 const double    unspecUlp       (16.0);
12533                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12534
12535                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12536                         return false;
12537
12538                 out[0] = fp16type(result).bits();
12539                 min[0] = result - err;
12540                 max[0] = result + err;
12541
12542                 return true;
12543         }
12544 };
12545
12546 struct fp16Cos : public fp16PerComponent
12547 {
12548         template<class fp16type>
12549         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12550         {
12551                 const fp16type  x                       (*in[0]);
12552                 const double    d                       (x.asDouble());
12553                 const double    result          (deCos(d));
12554                 const double    unspecUlp       (16.0);
12555                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12556
12557                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12558                         return false;
12559
12560                 out[0] = fp16type(result).bits();
12561                 min[0] = result - err;
12562                 max[0] = result + err;
12563
12564                 return true;
12565         }
12566 };
12567
12568 struct fp16Tan : public fp16PerComponent
12569 {
12570         template<class fp16type>
12571         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12572         {
12573                 const fp16type  x               (*in[0]);
12574                 const double    d               (x.asDouble());
12575                 const double    result  (deTan(d));
12576
12577                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12578                         return false;
12579
12580                 out[0] = fp16type(result).bits();
12581                 {
12582                         const double    err                     = deLdExp(1.0, -7);
12583                         const double    s1                      = deSin(d) + err;
12584                         const double    s2                      = deSin(d) - err;
12585                         const double    c1                      = deCos(d) + err;
12586                         const double    c2                      = deCos(d) - err;
12587                         const double    edgeVals[]      = {s1/c1, s1/c2, s2/c1, s2/c2};
12588                         double                  edgeLeft        = out[0];
12589                         double                  edgeRight       = out[0];
12590
12591                         if (deSign(c1 * c2) < 0.0)
12592                         {
12593                                 edgeLeft        = -std::numeric_limits<double>::infinity();
12594                                 edgeRight       = +std::numeric_limits<double>::infinity();
12595                         }
12596                         else
12597                         {
12598                                 edgeLeft        = *std::min_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12599                                 edgeRight       = *std::max_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12600                         }
12601
12602                         min[0] = edgeLeft;
12603                         max[0] = edgeRight;
12604                 }
12605
12606                 return true;
12607         }
12608 };
12609
12610 struct fp16Asin : public fp16PerComponent
12611 {
12612         template<class fp16type>
12613         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12614         {
12615                 const fp16type  x               (*in[0]);
12616                 const double    d               (x.asDouble());
12617                 const double    result  (deAsin(d));
12618                 const double    error   (deAtan2(d, sqrt(1.0 - d * d)));
12619
12620                 if (!x.isNaN() && deAbs(d) > 1.0)
12621                         return false;
12622
12623                 out[0] = fp16type(result).bits();
12624                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12625                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12626
12627                 return true;
12628         }
12629 };
12630
12631 struct fp16Acos : public fp16PerComponent
12632 {
12633         template<class fp16type>
12634         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12635         {
12636                 const fp16type  x               (*in[0]);
12637                 const double    d               (x.asDouble());
12638                 const double    result  (deAcos(d));
12639                 const double    error   (deAtan2(sqrt(1.0 - d * d), d));
12640
12641                 if (!x.isNaN() && deAbs(d) > 1.0)
12642                         return false;
12643
12644                 out[0] = fp16type(result).bits();
12645                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12646                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12647
12648                 return true;
12649         }
12650 };
12651
12652 struct fp16Atan : public fp16PerComponent
12653 {
12654         virtual double getULPs(vector<const deFloat16*>& in)
12655         {
12656                 DE_UNREF(in);
12657
12658                 return 2 * 5.0; // This is not a precision test. Value is not from spec
12659         }
12660
12661         template<class fp16type>
12662         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12663         {
12664                 const fp16type  x               (*in[0]);
12665                 const double    d               (x.asDouble());
12666                 const double    result  (deAtanOver(d));
12667
12668                 out[0] = fp16type(result).bits();
12669                 min[0] = getMin(result, getULPs(in));
12670                 max[0] = getMax(result, getULPs(in));
12671
12672                 return true;
12673         }
12674 };
12675
12676 struct fp16Sinh : public fp16PerComponent
12677 {
12678         fp16Sinh() : fp16PerComponent()
12679         {
12680                 flavorNames.push_back("Double");
12681                 flavorNames.push_back("ExpFP16");
12682         }
12683
12684         template<class fp16type>
12685         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12686         {
12687                 const fp16type  x               (*in[0]);
12688                 const double    d               (x.asDouble());
12689                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12690                 double                  result  (0.0);
12691                 double                  error   (0.0);
12692
12693                 if (getFlavor() == 0)
12694                 {
12695                         result  = deSinh(d);
12696                         error   = floatFormat16.ulp(deAbs(result), ulps);
12697                 }
12698                 else if (getFlavor() == 1)
12699                 {
12700                         const fp16type  epx     (deExp(d));
12701                         const fp16type  enx     (deExp(-d));
12702                         const fp16type  esx     (epx.asDouble() - enx.asDouble());
12703                         const fp16type  sx2     (esx.asDouble() / 2.0);
12704
12705                         result  = sx2.asDouble();
12706                         error   = deAbs(floatFormat16.ulp(epx.asDouble(), ulps)) + deAbs(floatFormat16.ulp(enx.asDouble(), ulps));
12707                 }
12708                 else
12709                 {
12710                         TCU_THROW(InternalError, "Unknown flavor");
12711                 }
12712
12713                 out[0] = fp16type(result).bits();
12714                 min[0] = result - error;
12715                 max[0] = result + error;
12716
12717                 return true;
12718         }
12719 };
12720
12721 struct fp16Cosh : public fp16PerComponent
12722 {
12723         fp16Cosh() : fp16PerComponent()
12724         {
12725                 flavorNames.push_back("Double");
12726                 flavorNames.push_back("ExpFP16");
12727         }
12728
12729         template<class fp16type>
12730         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12731         {
12732                 const fp16type  x               (*in[0]);
12733                 const double    d               (x.asDouble());
12734                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12735                 double                  result  (0.0);
12736
12737                 if (getFlavor() == 0)
12738                 {
12739                         result = deCosh(d);
12740                 }
12741                 else if (getFlavor() == 1)
12742                 {
12743                         const fp16type  epx     (deExp(d));
12744                         const fp16type  enx     (deExp(-d));
12745                         const fp16type  esx     (epx.asDouble() + enx.asDouble());
12746                         const fp16type  sx2     (esx.asDouble() / 2.0);
12747
12748                         result = sx2.asDouble();
12749                 }
12750                 else
12751                 {
12752                         TCU_THROW(InternalError, "Unknown flavor");
12753                 }
12754
12755                 out[0] = fp16type(result).bits();
12756                 min[0] = result - floatFormat16.ulp(deAbs(result), ulps);
12757                 max[0] = result + floatFormat16.ulp(deAbs(result), ulps);
12758
12759                 return true;
12760         }
12761 };
12762
12763 struct fp16Tanh : public fp16PerComponent
12764 {
12765         fp16Tanh() : fp16PerComponent()
12766         {
12767                 flavorNames.push_back("Tanh");
12768                 flavorNames.push_back("SinhCosh");
12769                 flavorNames.push_back("SinhCoshFP16");
12770                 flavorNames.push_back("PolyFP16");
12771         }
12772
12773         virtual double getULPs (vector<const deFloat16*>& in)
12774         {
12775                 const tcu::Float16      x       (*in[0]);
12776                 const double            d       (x.asDouble());
12777
12778                 return 2 * (1.0 + 2 * deAbs(d)); // This is not a precision test. Value is not from spec
12779         }
12780
12781         template<class fp16type>
12782         inline double calcPoly (const fp16type& espx, const fp16type& esnx, const fp16type& ecpx, const fp16type& ecnx)
12783         {
12784                 const fp16type  esx     (espx.asDouble() - esnx.asDouble());
12785                 const fp16type  sx2     (esx.asDouble() / 2.0);
12786                 const fp16type  ecx     (ecpx.asDouble() + ecnx.asDouble());
12787                 const fp16type  cx2     (ecx.asDouble() / 2.0);
12788                 const fp16type  tg      (sx2.asDouble() / cx2.asDouble());
12789                 const double    rez     (tg.asDouble());
12790
12791                 return rez;
12792         }
12793
12794         template<class fp16type>
12795         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12796         {
12797                 const fp16type  x               (*in[0]);
12798                 const double    d               (x.asDouble());
12799                 double                  result  (0.0);
12800
12801                 if (getFlavor() == 0)
12802                 {
12803                         result  = deTanh(d);
12804                         min[0]  = getMin(result, getULPs(in));
12805                         max[0]  = getMax(result, getULPs(in));
12806                 }
12807                 else if (getFlavor() == 1)
12808                 {
12809                         result  = deSinh(d) / deCosh(d);
12810                         min[0]  = getMin(result, getULPs(in));
12811                         max[0]  = getMax(result, getULPs(in));
12812                 }
12813                 else if (getFlavor() == 2)
12814                 {
12815                         const fp16type  s       (deSinh(d));
12816                         const fp16type  c       (deCosh(d));
12817
12818                         result  = s.asDouble() / c.asDouble();
12819                         min[0]  = getMin(result, getULPs(in));
12820                         max[0]  = getMax(result, getULPs(in));
12821                 }
12822                 else if (getFlavor() == 3)
12823                 {
12824                         const double    ulps    (getULPs(in));
12825                         const double    epxm    (deExp( d));
12826                         const double    enxm    (deExp(-d));
12827                         const double    epxmerr = floatFormat16.ulp(epxm, ulps);
12828                         const double    enxmerr = floatFormat16.ulp(enxm, ulps);
12829                         const fp16type  epx[]   = { fp16type(epxm - epxmerr), fp16type(epxm + epxmerr) };
12830                         const fp16type  enx[]   = { fp16type(enxm - enxmerr), fp16type(enxm + enxmerr) };
12831                         const fp16type  epxm16  (epxm);
12832                         const fp16type  enxm16  (enxm);
12833                         vector<double>  tgs;
12834
12835                         for (size_t spNdx = 0; spNdx < DE_LENGTH_OF_ARRAY(epx); ++spNdx)
12836                         for (size_t snNdx = 0; snNdx < DE_LENGTH_OF_ARRAY(enx); ++snNdx)
12837                         for (size_t cpNdx = 0; cpNdx < DE_LENGTH_OF_ARRAY(epx); ++cpNdx)
12838                         for (size_t cnNdx = 0; cnNdx < DE_LENGTH_OF_ARRAY(enx); ++cnNdx)
12839                         {
12840                                 const double tgh = calcPoly(epx[spNdx], enx[snNdx], epx[cpNdx], enx[cnNdx]);
12841
12842                                 tgs.push_back(tgh);
12843                         }
12844
12845                         result = calcPoly(epxm16, enxm16, epxm16, enxm16);
12846                         min[0] = *std::min_element(tgs.begin(), tgs.end());
12847                         max[0] = *std::max_element(tgs.begin(), tgs.end());
12848                 }
12849                 else
12850                 {
12851                         TCU_THROW(InternalError, "Unknown flavor");
12852                 }
12853
12854                 out[0] = fp16type(result).bits();
12855
12856                 return true;
12857         }
12858 };
12859
12860 struct fp16Asinh : public fp16PerComponent
12861 {
12862         fp16Asinh() : fp16PerComponent()
12863         {
12864                 flavorNames.push_back("Double");
12865                 flavorNames.push_back("PolyFP16Wiki");
12866                 flavorNames.push_back("PolyFP16Abs");
12867         }
12868
12869         virtual double getULPs (vector<const deFloat16*>& in)
12870         {
12871                 DE_UNREF(in);
12872
12873                 return 256.0; // This is not a precision test. Value is not from spec
12874         }
12875
12876         template<class fp16type>
12877         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12878         {
12879                 const fp16type  x               (*in[0]);
12880                 const double    d               (x.asDouble());
12881                 double                  result  (0.0);
12882
12883                 if (getFlavor() == 0)
12884                 {
12885                         result = deAsinh(d);
12886                 }
12887                 else if (getFlavor() == 1)
12888                 {
12889                         const fp16type  x2              (d * d);
12890                         const fp16type  x2p1    (x2.asDouble() + 1.0);
12891                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
12892                         const fp16type  sxsq    (d + sq.asDouble());
12893                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12894
12895                         if (lsxsq.isInf())
12896                                 return false;
12897
12898                         result = lsxsq.asDouble();
12899                 }
12900                 else if (getFlavor() == 2)
12901                 {
12902                         const fp16type  x2              (d * d);
12903                         const fp16type  x2p1    (x2.asDouble() + 1.0);
12904                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
12905                         const fp16type  sxsq    (deAbs(d) + sq.asDouble());
12906                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12907
12908                         result = deSign(d) * lsxsq.asDouble();
12909                 }
12910                 else
12911                 {
12912                         TCU_THROW(InternalError, "Unknown flavor");
12913                 }
12914
12915                 out[0] = fp16type(result).bits();
12916                 min[0] = getMin(result, getULPs(in));
12917                 max[0] = getMax(result, getULPs(in));
12918
12919                 return true;
12920         }
12921 };
12922
12923 struct fp16Acosh : public fp16PerComponent
12924 {
12925         fp16Acosh() : fp16PerComponent()
12926         {
12927                 flavorNames.push_back("Double");
12928                 flavorNames.push_back("PolyFP16");
12929         }
12930
12931         virtual double getULPs (vector<const deFloat16*>& in)
12932         {
12933                 DE_UNREF(in);
12934
12935                 return 16.0; // This is not a precision test. Value is not from spec
12936         }
12937
12938         template<class fp16type>
12939         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12940         {
12941                 const fp16type  x               (*in[0]);
12942                 const double    d               (x.asDouble());
12943                 double                  result  (0.0);
12944
12945                 if (!x.isNaN() && d < 1.0)
12946                         return false;
12947
12948                 if (getFlavor() == 0)
12949                 {
12950                         result = deAcosh(d);
12951                 }
12952                 else if (getFlavor() == 1)
12953                 {
12954                         const fp16type  x2              (d * d);
12955                         const fp16type  x2m1    (x2.asDouble() - 1.0);
12956                         const fp16type  sq              (deSqrt(x2m1.asDouble()));
12957                         const fp16type  sxsq    (d + sq.asDouble());
12958                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
12959
12960                         result = lsxsq.asDouble();
12961                 }
12962                 else
12963                 {
12964                         TCU_THROW(InternalError, "Unknown flavor");
12965                 }
12966
12967                 out[0] = fp16type(result).bits();
12968                 min[0] = getMin(result, getULPs(in));
12969                 max[0] = getMax(result, getULPs(in));
12970
12971                 return true;
12972         }
12973 };
12974
12975 struct fp16Atanh : public fp16PerComponent
12976 {
12977         fp16Atanh() : fp16PerComponent()
12978         {
12979                 flavorNames.push_back("Double");
12980                 flavorNames.push_back("PolyFP16");
12981         }
12982
12983         template<class fp16type>
12984         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12985         {
12986                 const fp16type  x               (*in[0]);
12987                 const double    d               (x.asDouble());
12988                 double                  result  (0.0);
12989
12990                 if (deAbs(d) >= 1.0)
12991                         return false;
12992
12993                 if (getFlavor() == 0)
12994                 {
12995                         const double    ulps    (16.0); // This is not a precision test. Value is not from spec
12996
12997                         result = deAtanh(d);
12998                         min[0] = getMin(result, ulps);
12999                         max[0] = getMax(result, ulps);
13000                 }
13001                 else if (getFlavor() == 1)
13002                 {
13003                         const fp16type  x1a             (1.0 + d);
13004                         const fp16type  x1b             (1.0 - d);
13005                         const fp16type  x1d             (x1a.asDouble() / x1b.asDouble());
13006                         const fp16type  lx1d    (deLog(x1d.asDouble()));
13007                         const fp16type  lx1d2   (0.5 * lx1d.asDouble());
13008                         const double    error   (2 * (de::inRange(deAbs(x1d.asDouble()), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(x1d.asDouble()), 3.0)));
13009
13010                         result = lx1d2.asDouble();
13011                         min[0] = result - error;
13012                         max[0] = result + error;
13013                 }
13014                 else
13015                 {
13016                         TCU_THROW(InternalError, "Unknown flavor");
13017                 }
13018
13019                 out[0] = fp16type(result).bits();
13020
13021                 return true;
13022         }
13023 };
13024
13025 struct fp16Exp : public fp16PerComponent
13026 {
13027         template<class fp16type>
13028         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13029         {
13030                 const fp16type  x               (*in[0]);
13031                 const double    d               (x.asDouble());
13032                 const double    ulps    (10.0 * (1.0 + 2.0 * deAbs(d)));
13033                 const double    result  (deExp(d));
13034
13035                 out[0] = fp16type(result).bits();
13036                 min[0] = getMin(result, ulps);
13037                 max[0] = getMax(result, ulps);
13038
13039                 return true;
13040         }
13041 };
13042
13043 struct fp16Log : public fp16PerComponent
13044 {
13045         template<class fp16type>
13046         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13047         {
13048                 const fp16type  x               (*in[0]);
13049                 const double    d               (x.asDouble());
13050                 const double    result  (deLog(d));
13051                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13052
13053                 if (d <= 0.0)
13054                         return false;
13055
13056                 out[0] = fp16type(result).bits();
13057                 min[0] = result - error;
13058                 max[0] = result + error;
13059
13060                 return true;
13061         }
13062 };
13063
13064 struct fp16Exp2 : public fp16PerComponent
13065 {
13066         template<class fp16type>
13067         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13068         {
13069                 const fp16type  x               (*in[0]);
13070                 const double    d               (x.asDouble());
13071                 const double    result  (deExp2(d));
13072                 const double    ulps    (1.0 + 2.0 * deAbs(fp16type(in[0][0]).asDouble()));
13073
13074                 out[0] = fp16type(result).bits();
13075                 min[0] = getMin(result, ulps);
13076                 max[0] = getMax(result, ulps);
13077
13078                 return true;
13079         }
13080 };
13081
13082 struct fp16Log2 : public fp16PerComponent
13083 {
13084         template<class fp16type>
13085         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13086         {
13087                 const fp16type  x               (*in[0]);
13088                 const double    d               (x.asDouble());
13089                 const double    result  (deLog2(d));
13090                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13091
13092                 if (d <= 0.0)
13093                         return false;
13094
13095                 out[0] = fp16type(result).bits();
13096                 min[0] = result - error;
13097                 max[0] = result + error;
13098
13099                 return true;
13100         }
13101 };
13102
13103 struct fp16Sqrt : public fp16PerComponent
13104 {
13105         virtual double getULPs (vector<const deFloat16*>& in)
13106         {
13107                 DE_UNREF(in);
13108
13109                 return 6.0;
13110         }
13111
13112         template<class fp16type>
13113         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13114         {
13115                 const fp16type  x               (*in[0]);
13116                 const double    d               (x.asDouble());
13117                 const double    result  (deSqrt(d));
13118
13119                 if (!x.isNaN() && d < 0.0)
13120                         return false;
13121
13122                 out[0] = fp16type(result).bits();
13123                 min[0] = getMin(result, getULPs(in));
13124                 max[0] = getMax(result, getULPs(in));
13125
13126                 return true;
13127         }
13128 };
13129
13130 struct fp16InverseSqrt : public fp16PerComponent
13131 {
13132         virtual double getULPs (vector<const deFloat16*>& in)
13133         {
13134                 DE_UNREF(in);
13135
13136                 return 2.0;
13137         }
13138
13139         template<class fp16type>
13140         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13141         {
13142                 const fp16type  x               (*in[0]);
13143                 const double    d               (x.asDouble());
13144                 const double    result  (1.0/deSqrt(d));
13145
13146                 if (!x.isNaN() && d <= 0.0)
13147                         return false;
13148
13149                 out[0] = fp16type(result).bits();
13150                 min[0] = getMin(result, getULPs(in));
13151                 max[0] = getMax(result, getULPs(in));
13152
13153                 return true;
13154         }
13155 };
13156
13157 struct fp16ModfFrac : public fp16PerComponent
13158 {
13159         template<class fp16type>
13160         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13161         {
13162                 const fp16type  x               (*in[0]);
13163                 const double    d               (x.asDouble());
13164                 double                  i               (0.0);
13165                 const double    result  (deModf(d, &i));
13166
13167                 if (x.isInf() || x.isNaN())
13168                         return false;
13169
13170                 out[0] = fp16type(result).bits();
13171                 min[0] = getMin(result, getULPs(in));
13172                 max[0] = getMax(result, getULPs(in));
13173
13174                 return true;
13175         }
13176 };
13177
13178 struct fp16ModfInt : public fp16PerComponent
13179 {
13180         template<class fp16type>
13181         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13182         {
13183                 const fp16type  x               (*in[0]);
13184                 const double    d               (x.asDouble());
13185                 double                  i               (0.0);
13186                 const double    dummy   (deModf(d, &i));
13187                 const double    result  (i);
13188
13189                 DE_UNREF(dummy);
13190
13191                 if (x.isInf() || x.isNaN())
13192                         return false;
13193
13194                 out[0] = fp16type(result).bits();
13195                 min[0] = getMin(result, getULPs(in));
13196                 max[0] = getMax(result, getULPs(in));
13197
13198                 return true;
13199         }
13200 };
13201
13202 struct fp16FrexpS : public fp16PerComponent
13203 {
13204         template<class fp16type>
13205         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13206         {
13207                 const fp16type  x               (*in[0]);
13208                 const double    d               (x.asDouble());
13209                 int                             e               (0);
13210                 const double    result  (deFrExp(d, &e));
13211
13212                 if (x.isNaN() || x.isInf())
13213                         return false;
13214
13215                 out[0] = fp16type(result).bits();
13216                 min[0] = getMin(result, getULPs(in));
13217                 max[0] = getMax(result, getULPs(in));
13218
13219                 return true;
13220         }
13221 };
13222
13223 struct fp16FrexpE : public fp16PerComponent
13224 {
13225         template<class fp16type>
13226         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13227         {
13228                 const fp16type  x               (*in[0]);
13229                 const double    d               (x.asDouble());
13230                 int                             e               (0);
13231                 const double    dummy   (deFrExp(d, &e));
13232                 const double    result  (static_cast<double>(e));
13233
13234                 DE_UNREF(dummy);
13235
13236                 if (x.isNaN() || x.isInf())
13237                         return false;
13238
13239                 out[0] = fp16type(result).bits();
13240                 min[0] = getMin(result, getULPs(in));
13241                 max[0] = getMax(result, getULPs(in));
13242
13243                 return true;
13244         }
13245 };
13246
13247 struct fp16OpFAdd : public fp16PerComponent
13248 {
13249         template<class fp16type>
13250         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13251         {
13252                 const fp16type  x               (*in[0]);
13253                 const fp16type  y               (*in[1]);
13254                 const double    xd              (x.asDouble());
13255                 const double    yd              (y.asDouble());
13256                 const double    result  (xd + yd);
13257
13258                 out[0] = fp16type(result).bits();
13259                 min[0] = getMin(result, getULPs(in));
13260                 max[0] = getMax(result, getULPs(in));
13261
13262                 return true;
13263         }
13264 };
13265
13266 struct fp16OpFSub : public fp16PerComponent
13267 {
13268         template<class fp16type>
13269         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13270         {
13271                 const fp16type  x               (*in[0]);
13272                 const fp16type  y               (*in[1]);
13273                 const double    xd              (x.asDouble());
13274                 const double    yd              (y.asDouble());
13275                 const double    result  (xd - yd);
13276
13277                 out[0] = fp16type(result).bits();
13278                 min[0] = getMin(result, getULPs(in));
13279                 max[0] = getMax(result, getULPs(in));
13280
13281                 return true;
13282         }
13283 };
13284
13285 struct fp16OpFMul : public fp16PerComponent
13286 {
13287         template<class fp16type>
13288         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13289         {
13290                 const fp16type  x               (*in[0]);
13291                 const fp16type  y               (*in[1]);
13292                 const double    xd              (x.asDouble());
13293                 const double    yd              (y.asDouble());
13294                 const double    result  (xd * yd);
13295
13296                 out[0] = fp16type(result).bits();
13297                 min[0] = getMin(result, getULPs(in));
13298                 max[0] = getMax(result, getULPs(in));
13299
13300                 return true;
13301         }
13302 };
13303
13304 struct fp16OpFDiv : public fp16PerComponent
13305 {
13306         fp16OpFDiv() : fp16PerComponent()
13307         {
13308                 flavorNames.push_back("DirectDiv");
13309                 flavorNames.push_back("InverseDiv");
13310         }
13311
13312         template<class fp16type>
13313         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13314         {
13315                 const fp16type  x                       (*in[0]);
13316                 const fp16type  y                       (*in[1]);
13317                 const double    xd                      (x.asDouble());
13318                 const double    yd                      (y.asDouble());
13319                 const double    unspecUlp       (16.0);
13320                 const double    ulpCnt          (de::inRange(deAbs(yd), deLdExp(1, -14), deLdExp(1, 14)) ? 2.5 : unspecUlp);
13321                 double                  result          (0.0);
13322
13323                 if (y.isZero())
13324                         return false;
13325
13326                 if (getFlavor() == 0)
13327                 {
13328                         result = (xd / yd);
13329                 }
13330                 else if (getFlavor() == 1)
13331                 {
13332                         const double    invyd   (1.0 / yd);
13333                         const fp16type  invy    (invyd);
13334
13335                         result = (xd * invy.asDouble());
13336                 }
13337                 else
13338                 {
13339                         TCU_THROW(InternalError, "Unknown flavor");
13340                 }
13341
13342                 out[0] = fp16type(result).bits();
13343                 min[0] = getMin(result, ulpCnt);
13344                 max[0] = getMax(result, ulpCnt);
13345
13346                 return true;
13347         }
13348 };
13349
13350 struct fp16Atan2 : public fp16PerComponent
13351 {
13352         fp16Atan2() : fp16PerComponent()
13353         {
13354                 flavorNames.push_back("DoubleCalc");
13355                 flavorNames.push_back("DoubleCalc_PI");
13356         }
13357
13358         virtual double getULPs(vector<const deFloat16*>& in)
13359         {
13360                 DE_UNREF(in);
13361
13362                 return 2 * 5.0; // This is not a precision test. Value is not from spec
13363         }
13364
13365         template<class fp16type>
13366         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13367         {
13368                 const fp16type  x               (*in[0]);
13369                 const fp16type  y               (*in[1]);
13370                 const double    xd              (x.asDouble());
13371                 const double    yd              (y.asDouble());
13372                 double                  result  (0.0);
13373
13374                 if (x.isZero() && y.isZero())
13375                         return false;
13376
13377                 if (getFlavor() == 0)
13378                 {
13379                         result  = deAtan2(xd, yd);
13380                 }
13381                 else if (getFlavor() == 1)
13382                 {
13383                         const double    ulps    (2.0 * 5.0); // This is not a precision test. Value is not from spec
13384                         const double    eps             (floatFormat16.ulp(DE_PI_DOUBLE, ulps));
13385
13386                         result  = deAtan2(xd, yd);
13387
13388                         if (de::inRange(deAbs(result), DE_PI_DOUBLE - eps, DE_PI_DOUBLE + eps))
13389                                 result  = -result;
13390                 }
13391                 else
13392                 {
13393                         TCU_THROW(InternalError, "Unknown flavor");
13394                 }
13395
13396                 out[0] = fp16type(result).bits();
13397                 min[0] = getMin(result, getULPs(in));
13398                 max[0] = getMax(result, getULPs(in));
13399
13400                 return true;
13401         }
13402 };
13403
13404 struct fp16Pow : public fp16PerComponent
13405 {
13406         fp16Pow() : fp16PerComponent()
13407         {
13408                 flavorNames.push_back("Pow");
13409                 flavorNames.push_back("PowLog2");
13410                 flavorNames.push_back("PowLog2FP16");
13411         }
13412
13413         template<class fp16type>
13414         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13415         {
13416                 const fp16type  x               (*in[0]);
13417                 const fp16type  y               (*in[1]);
13418                 const double    xd              (x.asDouble());
13419                 const double    yd              (y.asDouble());
13420                 const double    logxeps (de::inRange(deAbs(xd), 0.5, 2.0) ? deLdExp(1.0, -7) : floatFormat16.ulp(deLog2(xd), 3.0));
13421                 const double    ulps1   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) - logxeps)));
13422                 const double    ulps2   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) + logxeps)));
13423                 const double    ulps    (deMax(deAbs(ulps1), deAbs(ulps2)));
13424                 double                  result  (0.0);
13425
13426                 if (xd < 0.0)
13427                         return false;
13428
13429                 if (x.isZero() && yd <= 0.0)
13430                         return false;
13431
13432                 if (getFlavor() == 0)
13433                 {
13434                         result = dePow(xd, yd);
13435                 }
13436                 else if (getFlavor() == 1)
13437                 {
13438                         const double    l2d     (deLog2(xd));
13439                         const double    e2d     (deExp2(yd * l2d));
13440
13441                         result = e2d;
13442                 }
13443                 else if (getFlavor() == 2)
13444                 {
13445                         const double    l2d     (deLog2(xd));
13446                         const fp16type  l2      (l2d);
13447                         const double    e2d     (deExp2(yd * l2.asDouble()));
13448                         const fp16type  e2      (e2d);
13449
13450                         result = e2.asDouble();
13451                 }
13452                 else
13453                 {
13454                         TCU_THROW(InternalError, "Unknown flavor");
13455                 }
13456
13457                 out[0] = fp16type(result).bits();
13458                 min[0] = getMin(result, ulps);
13459                 max[0] = getMax(result, ulps);
13460
13461                 return true;
13462         }
13463 };
13464
13465 struct fp16FMin : public fp16PerComponent
13466 {
13467         template<class fp16type>
13468         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13469         {
13470                 const fp16type  x               (*in[0]);
13471                 const fp16type  y               (*in[1]);
13472                 const double    xd              (x.asDouble());
13473                 const double    yd              (y.asDouble());
13474                 const double    result  (deMin(xd, yd));
13475
13476                 if (x.isNaN() || y.isNaN())
13477                         return false;
13478
13479                 out[0] = fp16type(result).bits();
13480                 min[0] = getMin(result, getULPs(in));
13481                 max[0] = getMax(result, getULPs(in));
13482
13483                 return true;
13484         }
13485 };
13486
13487 struct fp16FMax : public fp16PerComponent
13488 {
13489         template<class fp16type>
13490         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13491         {
13492                 const fp16type  x               (*in[0]);
13493                 const fp16type  y               (*in[1]);
13494                 const double    xd              (x.asDouble());
13495                 const double    yd              (y.asDouble());
13496                 const double    result  (deMax(xd, yd));
13497
13498                 if (x.isNaN() || y.isNaN())
13499                         return false;
13500
13501                 out[0] = fp16type(result).bits();
13502                 min[0] = getMin(result, getULPs(in));
13503                 max[0] = getMax(result, getULPs(in));
13504
13505                 return true;
13506         }
13507 };
13508
13509 struct fp16Step : public fp16PerComponent
13510 {
13511         template<class fp16type>
13512         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13513         {
13514                 const fp16type  edge    (*in[0]);
13515                 const fp16type  x               (*in[1]);
13516                 const double    edged   (edge.asDouble());
13517                 const double    xd              (x.asDouble());
13518                 const double    result  (deStep(edged, xd));
13519
13520                 out[0] = fp16type(result).bits();
13521                 min[0] = getMin(result, getULPs(in));
13522                 max[0] = getMax(result, getULPs(in));
13523
13524                 return true;
13525         }
13526 };
13527
13528 struct fp16Ldexp : public fp16PerComponent
13529 {
13530         template<class fp16type>
13531         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13532         {
13533                 const fp16type  x               (*in[0]);
13534                 const fp16type  y               (*in[1]);
13535                 const double    xd              (x.asDouble());
13536                 const int               yd              (static_cast<int>(deTrunc(y.asDouble())));
13537                 const double    result  (deLdExp(xd, yd));
13538
13539                 if (y.isNaN() || y.isInf() || y.isDenorm() || yd < -14 || yd > 15)
13540                         return false;
13541
13542                 // Spec: "If this product is too large to be represented in the floating-point type, the result is undefined."
13543                 if (fp16type(result).isInf())
13544                         return false;
13545
13546                 out[0] = fp16type(result).bits();
13547                 min[0] = getMin(result, getULPs(in));
13548                 max[0] = getMax(result, getULPs(in));
13549
13550                 return true;
13551         }
13552 };
13553
13554 struct fp16FClamp : public fp16PerComponent
13555 {
13556         template<class fp16type>
13557         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13558         {
13559                 const fp16type  x               (*in[0]);
13560                 const fp16type  minVal  (*in[1]);
13561                 const fp16type  maxVal  (*in[2]);
13562                 const double    xd              (x.asDouble());
13563                 const double    minVald (minVal.asDouble());
13564                 const double    maxVald (maxVal.asDouble());
13565                 const double    result  (deClamp(xd, minVald, maxVald));
13566
13567                 if (minVal.isNaN() || maxVal.isNaN() || minVald > maxVald)
13568                         return false;
13569
13570                 out[0] = fp16type(result).bits();
13571                 min[0] = getMin(result, getULPs(in));
13572                 max[0] = getMax(result, getULPs(in));
13573
13574                 return true;
13575         }
13576 };
13577
13578 struct fp16FMix : public fp16PerComponent
13579 {
13580         fp16FMix() : fp16PerComponent()
13581         {
13582                 flavorNames.push_back("DoubleCalc");
13583                 flavorNames.push_back("EmulatingFP16");
13584                 flavorNames.push_back("EmulatingFP16YminusX");
13585         }
13586
13587         template<class fp16type>
13588         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13589         {
13590                 const fp16type  x               (*in[0]);
13591                 const fp16type  y               (*in[1]);
13592                 const fp16type  a               (*in[2]);
13593                 const double    ulps    (8.0); // This is not a precision test. Value is not from spec
13594                 double                  result  (0.0);
13595
13596                 if (getFlavor() == 0)
13597                 {
13598                         const double    xd              (x.asDouble());
13599                         const double    yd              (y.asDouble());
13600                         const double    ad              (a.asDouble());
13601                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13602                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13603                         const double    eps             (xeps + yeps);
13604
13605                         result = deMix(xd, yd, ad);
13606                         min[0] = result - eps;
13607                         max[0] = result + eps;
13608                 }
13609                 else if (getFlavor() == 1)
13610                 {
13611                         const double    xd              (x.asDouble());
13612                         const double    yd              (y.asDouble());
13613                         const double    ad              (a.asDouble());
13614                         const fp16type  am              (1.0 - ad);
13615                         const double    amd             (am.asDouble());
13616                         const fp16type  xam             (xd * amd);
13617                         const double    xamd    (xam.asDouble());
13618                         const fp16type  ya              (yd * ad);
13619                         const double    yad             (ya.asDouble());
13620                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13621                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13622                         const double    eps             (xeps + yeps);
13623
13624                         result = xamd + yad;
13625                         min[0] = result - eps;
13626                         max[0] = result + eps;
13627                 }
13628                 else if (getFlavor() == 2)
13629                 {
13630                         const double    xd              (x.asDouble());
13631                         const double    yd              (y.asDouble());
13632                         const double    ad              (a.asDouble());
13633                         const fp16type  ymx             (yd - xd);
13634                         const double    ymxd    (ymx.asDouble());
13635                         const fp16type  ymxa    (ymxd * ad);
13636                         const double    ymxad   (ymxa.asDouble());
13637                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13638                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13639                         const double    eps             (xeps + yeps);
13640
13641                         result = xd + ymxad;
13642                         min[0] = result - eps;
13643                         max[0] = result + eps;
13644                 }
13645                 else
13646                 {
13647                         TCU_THROW(InternalError, "Unknown flavor");
13648                 }
13649
13650                 out[0] = fp16type(result).bits();
13651
13652                 return true;
13653         }
13654 };
13655
13656 struct fp16SmoothStep : public fp16PerComponent
13657 {
13658         fp16SmoothStep() : fp16PerComponent()
13659         {
13660                 flavorNames.push_back("FloatCalc");
13661                 flavorNames.push_back("EmulatingFP16");
13662                 flavorNames.push_back("EmulatingFP16WClamp");
13663         }
13664
13665         virtual double getULPs(vector<const deFloat16*>& in)
13666         {
13667                 DE_UNREF(in);
13668
13669                 return 4.0; // This is not a precision test. Value is not from spec
13670         }
13671
13672         template<class fp16type>
13673         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13674         {
13675                 const fp16type  edge0   (*in[0]);
13676                 const fp16type  edge1   (*in[1]);
13677                 const fp16type  x               (*in[2]);
13678                 double                  result  (0.0);
13679
13680                 if (edge0.isNaN() || edge1.isNaN() || x.isNaN() || edge0.asDouble() >= edge1.asDouble())
13681                         return false;
13682
13683                 if (edge0.isInf() || edge1.isInf() || x.isInf())
13684                         return false;
13685
13686                 if (getFlavor() == 0)
13687                 {
13688                         const float     edge0d  (edge0.asFloat());
13689                         const float     edge1d  (edge1.asFloat());
13690                         const float     xd              (x.asFloat());
13691                         const float     sstep   (deFloatSmoothStep(edge0d, edge1d, xd));
13692
13693                         result = sstep;
13694                 }
13695                 else if (getFlavor() == 1)
13696                 {
13697                         const double    edge0d  (edge0.asDouble());
13698                         const double    edge1d  (edge1.asDouble());
13699                         const double    xd              (x.asDouble());
13700
13701                         if (xd <= edge0d)
13702                                 result = 0.0;
13703                         else if (xd >= edge1d)
13704                                 result = 1.0;
13705                         else
13706                         {
13707                                 const fp16type  a       (xd - edge0d);
13708                                 const fp16type  b       (edge1d - edge0d);
13709                                 const fp16type  t       (a.asDouble() / b.asDouble());
13710                                 const fp16type  t2      (2.0 * t.asDouble());
13711                                 const fp16type  t3      (3.0 - t2.asDouble());
13712                                 const fp16type  t4      (t.asDouble() * t3.asDouble());
13713                                 const fp16type  t5      (t.asDouble() * t4.asDouble());
13714
13715                                 result = t5.asDouble();
13716                         }
13717                 }
13718                 else if (getFlavor() == 2)
13719                 {
13720                         const double    edge0d  (edge0.asDouble());
13721                         const double    edge1d  (edge1.asDouble());
13722                         const double    xd              (x.asDouble());
13723                         const fp16type  a       (xd - edge0d);
13724                         const fp16type  b       (edge1d - edge0d);
13725                         const fp16type  bi      (1.0 / b.asDouble());
13726                         const fp16type  t0      (a.asDouble() * bi.asDouble());
13727                         const double    tc      (deClamp(t0.asDouble(), 0.0, 1.0));
13728                         const fp16type  t       (tc);
13729                         const fp16type  t2      (2.0 * t.asDouble());
13730                         const fp16type  t3      (3.0 - t2.asDouble());
13731                         const fp16type  t4      (t.asDouble() * t3.asDouble());
13732                         const fp16type  t5      (t.asDouble() * t4.asDouble());
13733
13734                         result = t5.asDouble();
13735                 }
13736                 else
13737                 {
13738                         TCU_THROW(InternalError, "Unknown flavor");
13739                 }
13740
13741                 out[0] = fp16type(result).bits();
13742                 min[0] = getMin(result, getULPs(in));
13743                 max[0] = getMax(result, getULPs(in));
13744
13745                 return true;
13746         }
13747 };
13748
13749 struct fp16Fma : public fp16PerComponent
13750 {
13751         fp16Fma()
13752         {
13753                 flavorNames.push_back("DoubleCalc");
13754                 flavorNames.push_back("EmulatingFP16");
13755         }
13756
13757         virtual double getULPs(vector<const deFloat16*>& in)
13758         {
13759                 DE_UNREF(in);
13760
13761                 return 16.0;
13762         }
13763
13764         template<class fp16type>
13765         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13766         {
13767                 DE_ASSERT(in.size() == 3);
13768                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13769                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
13770                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
13771                 DE_ASSERT(getOutCompCount() > 0);
13772
13773                 const fp16type  a               (*in[0]);
13774                 const fp16type  b               (*in[1]);
13775                 const fp16type  c               (*in[2]);
13776                 double                  result  (0.0);
13777
13778                 if (getFlavor() == 0)
13779                 {
13780                         const double    ad      (a.asDouble());
13781                         const double    bd      (b.asDouble());
13782                         const double    cd      (c.asDouble());
13783
13784                         result  = deMadd(ad, bd, cd);
13785                 }
13786                 else if (getFlavor() == 1)
13787                 {
13788                         const double    ad      (a.asDouble());
13789                         const double    bd      (b.asDouble());
13790                         const double    cd      (c.asDouble());
13791                         const fp16type  ab      (ad * bd);
13792                         const fp16type  r       (ab.asDouble() + cd);
13793
13794                         result  = r.asDouble();
13795                 }
13796                 else
13797                 {
13798                         TCU_THROW(InternalError, "Unknown flavor");
13799                 }
13800
13801                 out[0] = fp16type(result).bits();
13802                 min[0] = getMin(result, getULPs(in));
13803                 max[0] = getMax(result, getULPs(in));
13804
13805                 return true;
13806         }
13807 };
13808
13809
13810 struct fp16AllComponents : public fp16PerComponent
13811 {
13812         bool            callOncePerComponent    ()      { return false; }
13813 };
13814
13815 struct fp16Length : public fp16AllComponents
13816 {
13817         fp16Length() : fp16AllComponents()
13818         {
13819                 flavorNames.push_back("EmulatingFP16");
13820                 flavorNames.push_back("DoubleCalc");
13821         }
13822
13823         virtual double getULPs(vector<const deFloat16*>& in)
13824         {
13825                 DE_UNREF(in);
13826
13827                 return 4.0;
13828         }
13829
13830         template<class fp16type>
13831         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13832         {
13833                 DE_ASSERT(getOutCompCount() == 1);
13834                 DE_ASSERT(in.size() == 1);
13835
13836                 double  result  (0.0);
13837
13838                 if (getFlavor() == 0)
13839                 {
13840                         fp16type        r       (0.0);
13841
13842                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13843                         {
13844                                 const fp16type  x       (in[0][componentNdx]);
13845                                 const fp16type  q       (x.asDouble() * x.asDouble());
13846
13847                                 r = fp16type(r.asDouble() + q.asDouble());
13848                         }
13849
13850                         result = deSqrt(r.asDouble());
13851
13852                         out[0] = fp16type(result).bits();
13853                 }
13854                 else if (getFlavor() == 1)
13855                 {
13856                         double  r       (0.0);
13857
13858                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13859                         {
13860                                 const fp16type  x       (in[0][componentNdx]);
13861                                 const double    q       (x.asDouble() * x.asDouble());
13862
13863                                 r += q;
13864                         }
13865
13866                         result = deSqrt(r);
13867
13868                         out[0] = fp16type(result).bits();
13869                 }
13870                 else
13871                 {
13872                         TCU_THROW(InternalError, "Unknown flavor");
13873                 }
13874
13875                 min[0] = getMin(result, getULPs(in));
13876                 max[0] = getMax(result, getULPs(in));
13877
13878                 return true;
13879         }
13880 };
13881
13882 struct fp16Distance : public fp16AllComponents
13883 {
13884         fp16Distance() : fp16AllComponents()
13885         {
13886                 flavorNames.push_back("EmulatingFP16");
13887                 flavorNames.push_back("DoubleCalc");
13888         }
13889
13890         virtual double getULPs(vector<const deFloat16*>& in)
13891         {
13892                 DE_UNREF(in);
13893
13894                 return 4.0;
13895         }
13896
13897         template<class fp16type>
13898         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13899         {
13900                 DE_ASSERT(getOutCompCount() == 1);
13901                 DE_ASSERT(in.size() == 2);
13902                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
13903
13904                 double  result  (0.0);
13905
13906                 if (getFlavor() == 0)
13907                 {
13908                         fp16type        r       (0.0);
13909
13910                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13911                         {
13912                                 const fp16type  x       (in[0][componentNdx]);
13913                                 const fp16type  y       (in[1][componentNdx]);
13914                                 const fp16type  d       (x.asDouble() - y.asDouble());
13915                                 const fp16type  q       (d.asDouble() * d.asDouble());
13916
13917                                 r = fp16type(r.asDouble() + q.asDouble());
13918                         }
13919
13920                         result = deSqrt(r.asDouble());
13921                 }
13922                 else if (getFlavor() == 1)
13923                 {
13924                         double  r       (0.0);
13925
13926                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
13927                         {
13928                                 const fp16type  x       (in[0][componentNdx]);
13929                                 const fp16type  y       (in[1][componentNdx]);
13930                                 const double    d       (x.asDouble() - y.asDouble());
13931                                 const double    q       (d * d);
13932
13933                                 r += q;
13934                         }
13935
13936                         result = deSqrt(r);
13937                 }
13938                 else
13939                 {
13940                         TCU_THROW(InternalError, "Unknown flavor");
13941                 }
13942
13943                 out[0] = fp16type(result).bits();
13944                 min[0] = getMin(result, getULPs(in));
13945                 max[0] = getMax(result, getULPs(in));
13946
13947                 return true;
13948         }
13949 };
13950
13951 struct fp16Cross : public fp16AllComponents
13952 {
13953         fp16Cross() : fp16AllComponents()
13954         {
13955                 flavorNames.push_back("EmulatingFP16");
13956                 flavorNames.push_back("DoubleCalc");
13957         }
13958
13959         virtual double getULPs(vector<const deFloat16*>& in)
13960         {
13961                 DE_UNREF(in);
13962
13963                 return 4.0;
13964         }
13965
13966         template<class fp16type>
13967         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13968         {
13969                 DE_ASSERT(getOutCompCount() == 3);
13970                 DE_ASSERT(in.size() == 2);
13971                 DE_ASSERT(getArgCompCount(0) == 3);
13972                 DE_ASSERT(getArgCompCount(1) == 3);
13973
13974                 if (getFlavor() == 0)
13975                 {
13976                         const fp16type  x0              (in[0][0]);
13977                         const fp16type  x1              (in[0][1]);
13978                         const fp16type  x2              (in[0][2]);
13979                         const fp16type  y0              (in[1][0]);
13980                         const fp16type  y1              (in[1][1]);
13981                         const fp16type  y2              (in[1][2]);
13982                         const fp16type  x1y2    (x1.asDouble() * y2.asDouble());
13983                         const fp16type  y1x2    (y1.asDouble() * x2.asDouble());
13984                         const fp16type  x2y0    (x2.asDouble() * y0.asDouble());
13985                         const fp16type  y2x0    (y2.asDouble() * x0.asDouble());
13986                         const fp16type  x0y1    (x0.asDouble() * y1.asDouble());
13987                         const fp16type  y0x1    (y0.asDouble() * x1.asDouble());
13988
13989                         out[0] = fp16type(x1y2.asDouble() - y1x2.asDouble()).bits();
13990                         out[1] = fp16type(x2y0.asDouble() - y2x0.asDouble()).bits();
13991                         out[2] = fp16type(x0y1.asDouble() - y0x1.asDouble()).bits();
13992                 }
13993                 else if (getFlavor() == 1)
13994                 {
13995                         const fp16type  x0              (in[0][0]);
13996                         const fp16type  x1              (in[0][1]);
13997                         const fp16type  x2              (in[0][2]);
13998                         const fp16type  y0              (in[1][0]);
13999                         const fp16type  y1              (in[1][1]);
14000                         const fp16type  y2              (in[1][2]);
14001                         const double    x1y2    (x1.asDouble() * y2.asDouble());
14002                         const double    y1x2    (y1.asDouble() * x2.asDouble());
14003                         const double    x2y0    (x2.asDouble() * y0.asDouble());
14004                         const double    y2x0    (y2.asDouble() * x0.asDouble());
14005                         const double    x0y1    (x0.asDouble() * y1.asDouble());
14006                         const double    y0x1    (y0.asDouble() * x1.asDouble());
14007
14008                         out[0] = fp16type(x1y2 - y1x2).bits();
14009                         out[1] = fp16type(x2y0 - y2x0).bits();
14010                         out[2] = fp16type(x0y1 - y0x1).bits();
14011                 }
14012                 else
14013                 {
14014                         TCU_THROW(InternalError, "Unknown flavor");
14015                 }
14016
14017                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14018                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14019                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14020                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14021
14022                 return true;
14023         }
14024 };
14025
14026 struct fp16Normalize : public fp16AllComponents
14027 {
14028         fp16Normalize() : fp16AllComponents()
14029         {
14030                 flavorNames.push_back("EmulatingFP16");
14031                 flavorNames.push_back("DoubleCalc");
14032
14033                 // flavorNames will be extended later
14034         }
14035
14036         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14037         {
14038                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14039
14040                 if (argNo == 0 && argCompCount[argNo] == 0)
14041                 {
14042                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14043                         std::vector<int>        indices;
14044
14045                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14046                                 indices.push_back(static_cast<int>(componentNdx));
14047
14048                         m_permutations.reserve(maxPermutationsCount);
14049
14050                         permutationsFlavorStart = flavorNames.size();
14051
14052                         do
14053                         {
14054                                 tcu::UVec4      permutation;
14055                                 std::string     name            = "Permutted_";
14056
14057                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14058                                 {
14059                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14060                                         name += de::toString(indices[componentNdx]);
14061                                 }
14062
14063                                 m_permutations.push_back(permutation);
14064                                 flavorNames.push_back(name);
14065
14066                         } while(std::next_permutation(indices.begin(), indices.end()));
14067
14068                         permutationsFlavorEnd = flavorNames.size();
14069                 }
14070
14071                 fp16AllComponents::setArgCompCount(argNo, compCount);
14072         }
14073         virtual double getULPs(vector<const deFloat16*>& in)
14074         {
14075                 DE_UNREF(in);
14076
14077                 return 8.0;
14078         }
14079
14080         template<class fp16type>
14081         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14082         {
14083                 DE_ASSERT(in.size() == 1);
14084                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14085
14086                 if (getFlavor() == 0)
14087                 {
14088                         fp16type        r(0.0);
14089
14090                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14091                         {
14092                                 const fp16type  x       (in[0][componentNdx]);
14093                                 const fp16type  q       (x.asDouble() * x.asDouble());
14094
14095                                 r = fp16type(r.asDouble() + q.asDouble());
14096                         }
14097
14098                         r = fp16type(deSqrt(r.asDouble()));
14099
14100                         if (r.isZero())
14101                                 return false;
14102
14103                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14104                         {
14105                                 const fp16type  x       (in[0][componentNdx]);
14106
14107                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14108                         }
14109                 }
14110                 else if (getFlavor() == 1)
14111                 {
14112                         double  r(0.0);
14113
14114                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14115                         {
14116                                 const fp16type  x       (in[0][componentNdx]);
14117                                 const double    q       (x.asDouble() * x.asDouble());
14118
14119                                 r += q;
14120                         }
14121
14122                         r = deSqrt(r);
14123
14124                         if (r == 0)
14125                                 return false;
14126
14127                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14128                         {
14129                                 const fp16type  x       (in[0][componentNdx]);
14130
14131                                 out[componentNdx] = fp16type(x.asDouble() / r).bits();
14132                         }
14133                 }
14134                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14135                 {
14136                         const int                       compCount               (static_cast<int>(getArgCompCount(0)));
14137                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14138                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14139                         fp16type                        r                               (0.0);
14140
14141                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14142                         {
14143                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14144                                 const fp16type  x                               (in[0][componentNdx]);
14145                                 const fp16type  q                               (x.asDouble() * x.asDouble());
14146
14147                                 r = fp16type(r.asDouble() + q.asDouble());
14148                         }
14149
14150                         r = fp16type(deSqrt(r.asDouble()));
14151
14152                         if (r.isZero())
14153                                 return false;
14154
14155                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14156                         {
14157                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14158                                 const fp16type  x                               (in[0][componentNdx]);
14159
14160                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14161                         }
14162                 }
14163                 else
14164                 {
14165                         TCU_THROW(InternalError, "Unknown flavor");
14166                 }
14167
14168                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14169                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14170                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14171                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14172
14173                 return true;
14174         }
14175
14176 private:
14177         std::vector<tcu::UVec4> m_permutations;
14178         size_t                                  permutationsFlavorStart;
14179         size_t                                  permutationsFlavorEnd;
14180 };
14181
14182 struct fp16FaceForward : public fp16AllComponents
14183 {
14184         virtual double getULPs(vector<const deFloat16*>& in)
14185         {
14186                 DE_UNREF(in);
14187
14188                 return 4.0;
14189         }
14190
14191         template<class fp16type>
14192         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14193         {
14194                 DE_ASSERT(in.size() == 3);
14195                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14196                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14197                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
14198
14199                 fp16type        dp(0.0);
14200
14201                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14202                 {
14203                         const fp16type  x       (in[1][componentNdx]);
14204                         const fp16type  y       (in[2][componentNdx]);
14205                         const double    xd      (x.asDouble());
14206                         const double    yd      (y.asDouble());
14207                         const fp16type  q       (xd * yd);
14208
14209                         dp = fp16type(dp.asDouble() + q.asDouble());
14210                 }
14211
14212                 if (dp.isNaN() || dp.isZero())
14213                         return false;
14214
14215                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14216                 {
14217                         const fp16type  n       (in[0][componentNdx]);
14218
14219                         out[componentNdx] = (dp.signBit() == 1) ? n.bits() : fp16type(-n.asDouble()).bits();
14220                 }
14221
14222                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14223                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14224                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14225                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14226
14227                 return true;
14228         }
14229 };
14230
14231 struct fp16Reflect : public fp16AllComponents
14232 {
14233         fp16Reflect() : fp16AllComponents()
14234         {
14235                 flavorNames.push_back("EmulatingFP16");
14236                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14237                 flavorNames.push_back("FloatCalc");
14238                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14239                 flavorNames.push_back("EmulatingFP16+2Nfirst");
14240                 flavorNames.push_back("EmulatingFP16+2Ifirst");
14241         }
14242
14243         virtual double getULPs(vector<const deFloat16*>& in)
14244         {
14245                 DE_UNREF(in);
14246
14247                 return 256.0; // This is not a precision test. Value is not from spec
14248         }
14249
14250         template<class fp16type>
14251         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14252         {
14253                 DE_ASSERT(in.size() == 2);
14254                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14255                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14256
14257                 if (getFlavor() < 4)
14258                 {
14259                         const bool      keepZeroSign    ((flavor & 1) != 0 ? true : false);
14260                         const bool      floatCalc               ((flavor & 2) != 0 ? true : false);
14261
14262                         if (floatCalc)
14263                         {
14264                                 float   dp(0.0f);
14265
14266                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14267                                 {
14268                                         const fp16type  i       (in[0][componentNdx]);
14269                                         const fp16type  n       (in[1][componentNdx]);
14270                                         const float             id      (i.asFloat());
14271                                         const float             nd      (n.asFloat());
14272                                         const float             qd      (id * nd);
14273
14274                                         if (keepZeroSign)
14275                                                 dp = (componentNdx == 0) ? qd : dp + qd;
14276                                         else
14277                                                 dp = dp + qd;
14278                                 }
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 float             dpnd    (dp * n.asFloat());
14285                                         const float             dpn2d   (2.0f * dpnd);
14286                                         const float             idpn2d  (i.asFloat() - dpn2d);
14287                                         const fp16type  result  (idpn2d);
14288
14289                                         out[componentNdx] = result.bits();
14290                                 }
14291                         }
14292                         else
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                                         if (keepZeroSign)
14305                                                 dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14306                                         else
14307                                                 dp = fp16type(dp.asDouble() + q.asDouble());
14308                                 }
14309
14310                                 if (dp.isNaN())
14311                                         return false;
14312
14313                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14314                                 {
14315                                         const fp16type  i               (in[0][componentNdx]);
14316                                         const fp16type  n               (in[1][componentNdx]);
14317                                         const fp16type  dpn             (dp.asDouble() * n.asDouble());
14318                                         const fp16type  dpn2    (2 * dpn.asDouble());
14319                                         const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14320
14321                                         out[componentNdx] = idpn2.bits();
14322                                 }
14323                         }
14324                 }
14325                 else if (getFlavor() == 4)
14326                 {
14327                         fp16type        dp(0.0);
14328
14329                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14330                         {
14331                                 const fp16type  i       (in[0][componentNdx]);
14332                                 const fp16type  n       (in[1][componentNdx]);
14333                                 const double    id      (i.asDouble());
14334                                 const double    nd      (n.asDouble());
14335                                 const fp16type  q       (id * nd);
14336
14337                                 dp = fp16type(dp.asDouble() + q.asDouble());
14338                         }
14339
14340                         if (dp.isNaN())
14341                                 return false;
14342
14343                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14344                         {
14345                                 const fp16type  i               (in[0][componentNdx]);
14346                                 const fp16type  n               (in[1][componentNdx]);
14347                                 const fp16type  n2              (2 * n.asDouble());
14348                                 const fp16type  dpn2    (dp.asDouble() * n2.asDouble());
14349                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14350
14351                                 out[componentNdx] = idpn2.bits();
14352                         }
14353                 }
14354                 else if (getFlavor() == 5)
14355                 {
14356                         fp16type        dp2(0.0);
14357
14358                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14359                         {
14360                                 const fp16type  i       (in[0][componentNdx]);
14361                                 const fp16type  n       (in[1][componentNdx]);
14362                                 const fp16type  i2      (2.0 * i.asDouble());
14363                                 const double    i2d     (i2.asDouble());
14364                                 const double    nd      (n.asDouble());
14365                                 const fp16type  q       (i2d * nd);
14366
14367                                 dp2 = fp16type(dp2.asDouble() + q.asDouble());
14368                         }
14369
14370                         if (dp2.isNaN())
14371                                 return false;
14372
14373                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14374                         {
14375                                 const fp16type  i               (in[0][componentNdx]);
14376                                 const fp16type  n               (in[1][componentNdx]);
14377                                 const fp16type  dpn2    (dp2.asDouble() * n.asDouble());
14378                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14379
14380                                 out[componentNdx] = idpn2.bits();
14381                         }
14382                 }
14383                 else
14384                 {
14385                         TCU_THROW(InternalError, "Unknown flavor");
14386                 }
14387
14388                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14389                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14390                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14391                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14392
14393                 return true;
14394         }
14395 };
14396
14397 struct fp16Refract : public fp16AllComponents
14398 {
14399         fp16Refract() : fp16AllComponents()
14400         {
14401                 flavorNames.push_back("EmulatingFP16");
14402                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14403                 flavorNames.push_back("FloatCalc");
14404                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14405         }
14406
14407         virtual double getULPs(vector<const deFloat16*>& in)
14408         {
14409                 DE_UNREF(in);
14410
14411                 return 8192.0; // This is not a precision test. Value is not from spec
14412         }
14413
14414         template<class fp16type>
14415         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14416         {
14417                 DE_ASSERT(in.size() == 3);
14418                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14419                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14420                 DE_ASSERT(getArgCompCount(2) == 1);
14421
14422                 const bool              keepZeroSign    ((flavor & 1) != 0 ? true : false);
14423                 const bool              doubleCalc              ((flavor & 2) != 0 ? true : false);
14424                 const fp16type  eta                             (*in[2]);
14425
14426                 if (doubleCalc)
14427                 {
14428                         double  dp      (0.0);
14429
14430                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14431                         {
14432                                 const fp16type  i       (in[0][componentNdx]);
14433                                 const fp16type  n       (in[1][componentNdx]);
14434                                 const double    id      (i.asDouble());
14435                                 const double    nd      (n.asDouble());
14436                                 const double    qd      (id * nd);
14437
14438                                 if (keepZeroSign)
14439                                         dp = (componentNdx == 0) ? qd : dp + qd;
14440                                 else
14441                                         dp = dp + qd;
14442                         }
14443
14444                         const double    eta2    (eta.asDouble() * eta.asDouble());
14445                         const double    dp2             (dp * dp);
14446                         const double    dp1             (1.0 - dp2);
14447                         const double    dpe             (eta2 * dp1);
14448                         const double    k               (1.0 - dpe);
14449
14450                         if (k < 0.0)
14451                         {
14452                                 const fp16type  zero    (0.0);
14453
14454                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14455                                         out[componentNdx] = zero.bits();
14456                         }
14457                         else
14458                         {
14459                                 const double    sk      (deSqrt(k));
14460
14461                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14462                                 {
14463                                         const fp16type  i               (in[0][componentNdx]);
14464                                         const fp16type  n               (in[1][componentNdx]);
14465                                         const double    etai    (i.asDouble() * eta.asDouble());
14466                                         const double    etadp   (eta.asDouble() * dp);
14467                                         const double    etadpk  (etadp + sk);
14468                                         const double    etadpkn (etadpk * n.asDouble());
14469                                         const double    full    (etai - etadpkn);
14470                                         const fp16type  result  (full);
14471
14472                                         if (result.isInf())
14473                                                 return false;
14474
14475                                         out[componentNdx] = result.bits();
14476                                 }
14477                         }
14478                 }
14479                 else
14480                 {
14481                         fp16type        dp      (0.0);
14482
14483                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14484                         {
14485                                 const fp16type  i       (in[0][componentNdx]);
14486                                 const fp16type  n       (in[1][componentNdx]);
14487                                 const double    id      (i.asDouble());
14488                                 const double    nd      (n.asDouble());
14489                                 const fp16type  q       (id * nd);
14490
14491                                 if (keepZeroSign)
14492                                         dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14493                                 else
14494                                         dp = fp16type(dp.asDouble() + q.asDouble());
14495                         }
14496
14497                         if (dp.isNaN())
14498                                 return false;
14499
14500                         const fp16type  eta2(eta.asDouble() * eta.asDouble());
14501                         const fp16type  dp2     (dp.asDouble() * dp.asDouble());
14502                         const fp16type  dp1     (1.0 - dp2.asDouble());
14503                         const fp16type  dpe     (eta2.asDouble() * dp1.asDouble());
14504                         const fp16type  k       (1.0 - dpe.asDouble());
14505
14506                         if (k.asDouble() < 0.0)
14507                         {
14508                                 const fp16type  zero    (0.0);
14509
14510                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14511                                         out[componentNdx] = zero.bits();
14512                         }
14513                         else
14514                         {
14515                                 const fp16type  sk      (deSqrt(k.asDouble()));
14516
14517                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14518                                 {
14519                                         const fp16type  i               (in[0][componentNdx]);
14520                                         const fp16type  n               (in[1][componentNdx]);
14521                                         const fp16type  etai    (i.asDouble() * eta.asDouble());
14522                                         const fp16type  etadp   (eta.asDouble() * dp.asDouble());
14523                                         const fp16type  etadpk  (etadp.asDouble() + sk.asDouble());
14524                                         const fp16type  etadpkn (etadpk.asDouble() * n.asDouble());
14525                                         const fp16type  full    (etai.asDouble() - etadpkn.asDouble());
14526
14527                                         if (full.isNaN() || full.isInf())
14528                                                 return false;
14529
14530                                         out[componentNdx] = full.bits();
14531                                 }
14532                         }
14533                 }
14534
14535                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14536                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14537                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14538                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14539
14540                 return true;
14541         }
14542 };
14543
14544 struct fp16Dot : public fp16AllComponents
14545 {
14546         fp16Dot() : fp16AllComponents()
14547         {
14548                 flavorNames.push_back("EmulatingFP16");
14549                 flavorNames.push_back("FloatCalc");
14550                 flavorNames.push_back("DoubleCalc");
14551
14552                 // flavorNames will be extended later
14553         }
14554
14555         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14556         {
14557                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14558
14559                 if (argNo == 0 && argCompCount[argNo] == 0)
14560                 {
14561                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14562                         std::vector<int>        indices;
14563
14564                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14565                                 indices.push_back(static_cast<int>(componentNdx));
14566
14567                         m_permutations.reserve(maxPermutationsCount);
14568
14569                         permutationsFlavorStart = flavorNames.size();
14570
14571                         do
14572                         {
14573                                 tcu::UVec4      permutation;
14574                                 std::string     name            = "Permutted_";
14575
14576                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14577                                 {
14578                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14579                                         name += de::toString(indices[componentNdx]);
14580                                 }
14581
14582                                 m_permutations.push_back(permutation);
14583                                 flavorNames.push_back(name);
14584
14585                         } while(std::next_permutation(indices.begin(), indices.end()));
14586
14587                         permutationsFlavorEnd = flavorNames.size();
14588                 }
14589
14590                 fp16AllComponents::setArgCompCount(argNo, compCount);
14591         }
14592
14593         virtual double  getULPs(vector<const deFloat16*>& in)
14594         {
14595                 DE_UNREF(in);
14596
14597                 return 16.0; // This is not a precision test. Value is not from spec
14598         }
14599
14600         template<class fp16type>
14601         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14602         {
14603                 DE_ASSERT(in.size() == 2);
14604                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
14605                 DE_ASSERT(getOutCompCount() == 1);
14606
14607                 double  result  (0.0);
14608                 double  eps             (0.0);
14609
14610                 if (getFlavor() == 0)
14611                 {
14612                         fp16type        dp      (0.0);
14613
14614                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14615                         {
14616                                 const fp16type  x       (in[0][componentNdx]);
14617                                 const fp16type  y       (in[1][componentNdx]);
14618                                 const fp16type  q       (x.asDouble() * y.asDouble());
14619
14620                                 dp = fp16type(dp.asDouble() + q.asDouble());
14621                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14622                         }
14623
14624                         result = dp.asDouble();
14625                 }
14626                 else if (getFlavor() == 1)
14627                 {
14628                         float   dp      (0.0);
14629
14630                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14631                         {
14632                                 const fp16type  x       (in[0][componentNdx]);
14633                                 const fp16type  y       (in[1][componentNdx]);
14634                                 const float             q       (x.asFloat() * y.asFloat());
14635
14636                                 dp += q;
14637                                 eps += floatFormat16.ulp(static_cast<double>(q), 2.0);
14638                         }
14639
14640                         result = dp;
14641                 }
14642                 else if (getFlavor() == 2)
14643                 {
14644                         double  dp      (0.0);
14645
14646                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14647                         {
14648                                 const fp16type  x       (in[0][componentNdx]);
14649                                 const fp16type  y       (in[1][componentNdx]);
14650                                 const double    q       (x.asDouble() * y.asDouble());
14651
14652                                 dp += q;
14653                                 eps += floatFormat16.ulp(q, 2.0);
14654                         }
14655
14656                         result = dp;
14657                 }
14658                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14659                 {
14660                         const int                       compCount               (static_cast<int>(getArgCompCount(1)));
14661                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14662                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14663                         fp16type                        dp                              (0.0);
14664
14665                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14666                         {
14667                                 const size_t            componentNdx    (permutation[permComponentNdx]);
14668                                 const fp16type          x                               (in[0][componentNdx]);
14669                                 const fp16type          y                               (in[1][componentNdx]);
14670                                 const fp16type          q                               (x.asDouble() * y.asDouble());
14671
14672                                 dp = fp16type(dp.asDouble() + q.asDouble());
14673                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14674                         }
14675
14676                         result = dp.asDouble();
14677                 }
14678                 else
14679                 {
14680                         TCU_THROW(InternalError, "Unknown flavor");
14681                 }
14682
14683                 out[0] = fp16type(result).bits();
14684                 min[0] = result - eps;
14685                 max[0] = result + eps;
14686
14687                 return true;
14688         }
14689
14690 private:
14691         std::vector<tcu::UVec4> m_permutations;
14692         size_t                                  permutationsFlavorStart;
14693         size_t                                  permutationsFlavorEnd;
14694 };
14695
14696 struct fp16VectorTimesScalar : public fp16AllComponents
14697 {
14698         virtual double getULPs(vector<const deFloat16*>& in)
14699         {
14700                 DE_UNREF(in);
14701
14702                 return 2.0;
14703         }
14704
14705         template<class fp16type>
14706         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14707         {
14708                 DE_ASSERT(in.size() == 2);
14709                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14710                 DE_ASSERT(getArgCompCount(1) == 1);
14711
14712                 fp16type        s       (*in[1]);
14713
14714                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14715                 {
14716                         const fp16type  x          (in[0][componentNdx]);
14717                         const double    result (s.asDouble() * x.asDouble());
14718                         const fp16type  m          (result);
14719
14720                         out[componentNdx] = m.bits();
14721                         min[componentNdx] = getMin(result, getULPs(in));
14722                         max[componentNdx] = getMax(result, getULPs(in));
14723                 }
14724
14725                 return true;
14726         }
14727 };
14728
14729 struct fp16MatrixBase : public fp16AllComponents
14730 {
14731         deUint32                getComponentValidity                    ()
14732         {
14733                 return static_cast<deUint32>(-1);
14734         }
14735
14736         inline size_t   getNdx                                                  (const size_t rowCount, const size_t col, const size_t row)
14737         {
14738                 const size_t minComponentCount  = 0;
14739                 const size_t maxComponentCount  = 3;
14740                 const size_t alignedRowsCount   = (rowCount == 3) ? 4 : rowCount;
14741
14742                 DE_ASSERT(de::inRange(rowCount, minComponentCount + 1, maxComponentCount + 1));
14743                 DE_ASSERT(de::inRange(col, minComponentCount, maxComponentCount));
14744                 DE_ASSERT(de::inBounds(row, minComponentCount, rowCount));
14745                 DE_UNREF(minComponentCount);
14746                 DE_UNREF(maxComponentCount);
14747
14748                 return col * alignedRowsCount + row;
14749         }
14750
14751         deUint32                getComponentMatrixValidityMask  (size_t cols, size_t rows)
14752         {
14753                 deUint32        result  = 0u;
14754
14755                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14756                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14757                         {
14758                                 const size_t bitNdx = getNdx(rows, colNdx, rowNdx);
14759
14760                                 DE_ASSERT(bitNdx < sizeof(result) * 8);
14761
14762                                 result |= (1<<bitNdx);
14763                         }
14764
14765                 return result;
14766         }
14767 };
14768
14769 template<size_t cols, size_t rows>
14770 struct fp16Transpose : public fp16MatrixBase
14771 {
14772         virtual double getULPs(vector<const deFloat16*>& in)
14773         {
14774                 DE_UNREF(in);
14775
14776                 return 1.0;
14777         }
14778
14779         deUint32        getComponentValidity    ()
14780         {
14781                 return getComponentMatrixValidityMask(rows, cols);
14782         }
14783
14784         template<class fp16type>
14785         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14786         {
14787                 DE_ASSERT(in.size() == 1);
14788
14789                 const size_t            alignedCols     = (cols == 3) ? 4 : cols;
14790                 const size_t            alignedRows     = (rows == 3) ? 4 : rows;
14791                 vector<deFloat16>       output          (alignedCols * alignedRows, 0);
14792
14793                 DE_ASSERT(output.size() == alignedCols * alignedRows);
14794
14795                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14796                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14797                                 output[rowNdx * alignedCols + colNdx] = in[0][colNdx * alignedRows + rowNdx];
14798
14799                 deMemcpy(out, &output[0], sizeof(deFloat16) * output.size());
14800                 deMemcpy(min, &output[0], sizeof(deFloat16) * output.size());
14801                 deMemcpy(max, &output[0], sizeof(deFloat16) * output.size());
14802
14803                 return true;
14804         }
14805 };
14806
14807 template<size_t cols, size_t rows>
14808 struct fp16MatrixTimesScalar : public fp16MatrixBase
14809 {
14810         virtual double getULPs(vector<const deFloat16*>& in)
14811         {
14812                 DE_UNREF(in);
14813
14814                 return 4.0;
14815         }
14816
14817         deUint32        getComponentValidity    ()
14818         {
14819                 return getComponentMatrixValidityMask(cols, rows);
14820         }
14821
14822         template<class fp16type>
14823         bool calc(vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14824         {
14825                 DE_ASSERT(in.size() == 2);
14826                 DE_ASSERT(getArgCompCount(1) == 1);
14827
14828                 const fp16type  y                       (in[1][0]);
14829                 const float             scalar          (y.asFloat());
14830                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14831                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14832
14833                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14834                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
14835                 DE_UNREF(alignedCols);
14836
14837                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14838                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14839                         {
14840                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
14841                                 const fp16type  x       (in[0][ndx]);
14842                                 const double    result  (scalar * x.asFloat());
14843
14844                                 out[ndx] = fp16type(result).bits();
14845                                 min[ndx] = getMin(result, getULPs(in));
14846                                 max[ndx] = getMax(result, getULPs(in));
14847                         }
14848
14849                 return true;
14850         }
14851 };
14852
14853 template<size_t cols, size_t rows>
14854 struct fp16VectorTimesMatrix : public fp16MatrixBase
14855 {
14856         fp16VectorTimesMatrix() : fp16MatrixBase()
14857         {
14858                 flavorNames.push_back("EmulatingFP16");
14859                 flavorNames.push_back("FloatCalc");
14860         }
14861
14862         virtual double getULPs (vector<const deFloat16*>& in)
14863         {
14864                 DE_UNREF(in);
14865
14866                 return (8.0 * cols);
14867         }
14868
14869         deUint32 getComponentValidity ()
14870         {
14871                 return getComponentMatrixValidityMask(cols, 1);
14872         }
14873
14874         template<class fp16type>
14875         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14876         {
14877                 DE_ASSERT(in.size() == 2);
14878
14879                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14880                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14881
14882                 DE_ASSERT(getOutCompCount() == cols);
14883                 DE_ASSERT(getArgCompCount(0) == rows);
14884                 DE_ASSERT(getArgCompCount(1) == alignedCols * alignedRows);
14885                 DE_UNREF(alignedCols);
14886
14887                 if (getFlavor() == 0)
14888                 {
14889                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14890                         {
14891                                 fp16type        s       (fp16type::zero(1));
14892
14893                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14894                                 {
14895                                         const fp16type  v       (in[0][rowNdx]);
14896                                         const float             vf      (v.asFloat());
14897                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14898                                         const fp16type  x       (in[1][ndx]);
14899                                         const float             xf      (x.asFloat());
14900                                         const fp16type  m       (vf * xf);
14901
14902                                         s = fp16type(s.asFloat() + m.asFloat());
14903                                 }
14904
14905                                 out[colNdx] = s.bits();
14906                                 min[colNdx] = getMin(s.asDouble(), getULPs(in));
14907                                 max[colNdx] = getMax(s.asDouble(), getULPs(in));
14908                         }
14909                 }
14910                 else if (getFlavor() == 1)
14911                 {
14912                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14913                         {
14914                                 float   s       (0.0f);
14915
14916                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14917                                 {
14918                                         const fp16type  v       (in[0][rowNdx]);
14919                                         const float             vf      (v.asFloat());
14920                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14921                                         const fp16type  x       (in[1][ndx]);
14922                                         const float             xf      (x.asFloat());
14923                                         const float             m       (vf * xf);
14924
14925                                         s += m;
14926                                 }
14927
14928                                 out[colNdx] = fp16type(s).bits();
14929                                 min[colNdx] = getMin(static_cast<double>(s), getULPs(in));
14930                                 max[colNdx] = getMax(static_cast<double>(s), getULPs(in));
14931                         }
14932                 }
14933                 else
14934                 {
14935                         TCU_THROW(InternalError, "Unknown flavor");
14936                 }
14937
14938                 return true;
14939         }
14940 };
14941
14942 template<size_t cols, size_t rows>
14943 struct fp16MatrixTimesVector : public fp16MatrixBase
14944 {
14945         fp16MatrixTimesVector() : fp16MatrixBase()
14946         {
14947                 flavorNames.push_back("EmulatingFP16");
14948                 flavorNames.push_back("FloatCalc");
14949         }
14950
14951         virtual double getULPs (vector<const deFloat16*>& in)
14952         {
14953                 DE_UNREF(in);
14954
14955                 return (8.0 * rows);
14956         }
14957
14958         deUint32 getComponentValidity ()
14959         {
14960                 return getComponentMatrixValidityMask(rows, 1);
14961         }
14962
14963         template<class fp16type>
14964         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14965         {
14966                 DE_ASSERT(in.size() == 2);
14967
14968                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
14969                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
14970
14971                 DE_ASSERT(getOutCompCount() == rows);
14972                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
14973                 DE_ASSERT(getArgCompCount(1) == cols);
14974                 DE_UNREF(alignedCols);
14975
14976                 if (getFlavor() == 0)
14977                 {
14978                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14979                         {
14980                                 fp16type        s       (fp16type::zero(1));
14981
14982                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14983                                 {
14984                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
14985                                         const fp16type  x       (in[0][ndx]);
14986                                         const float             xf      (x.asFloat());
14987                                         const fp16type  v       (in[1][colNdx]);
14988                                         const float             vf      (v.asFloat());
14989                                         const fp16type  m       (vf * xf);
14990
14991                                         s = fp16type(s.asFloat() + m.asFloat());
14992                                 }
14993
14994                                 out[rowNdx] = s.bits();
14995                                 min[rowNdx] = getMin(s.asDouble(), getULPs(in));
14996                                 max[rowNdx] = getMax(s.asDouble(), getULPs(in));
14997                         }
14998                 }
14999                 else if (getFlavor() == 1)
15000                 {
15001                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15002                         {
15003                                 float   s       (0.0f);
15004
15005                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15006                                 {
15007                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
15008                                         const fp16type  x       (in[0][ndx]);
15009                                         const float             xf      (x.asFloat());
15010                                         const fp16type  v       (in[1][colNdx]);
15011                                         const float             vf      (v.asFloat());
15012                                         const float             m       (vf * xf);
15013
15014                                         s += m;
15015                                 }
15016
15017                                 out[rowNdx] = fp16type(s).bits();
15018                                 min[rowNdx] = getMin(static_cast<double>(s), getULPs(in));
15019                                 max[rowNdx] = getMax(static_cast<double>(s), getULPs(in));
15020                         }
15021                 }
15022                 else
15023                 {
15024                         TCU_THROW(InternalError, "Unknown flavor");
15025                 }
15026
15027                 return true;
15028         }
15029 };
15030
15031 template<size_t colsL, size_t rowsL, size_t colsR, size_t rowsR>
15032 struct fp16MatrixTimesMatrix : public fp16MatrixBase
15033 {
15034         fp16MatrixTimesMatrix() : fp16MatrixBase()
15035         {
15036                 flavorNames.push_back("EmulatingFP16");
15037                 flavorNames.push_back("FloatCalc");
15038         }
15039
15040         virtual double getULPs (vector<const deFloat16*>& in)
15041         {
15042                 DE_UNREF(in);
15043
15044                 return 32.0;
15045         }
15046
15047         deUint32 getComponentValidity ()
15048         {
15049                 return getComponentMatrixValidityMask(colsR, rowsL);
15050         }
15051
15052         template<class fp16type>
15053         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15054         {
15055                 DE_STATIC_ASSERT(colsL == rowsR);
15056
15057                 DE_ASSERT(in.size() == 2);
15058
15059                 const size_t    alignedColsL    = (colsL == 3) ? 4 : colsL;
15060                 const size_t    alignedRowsL    = (rowsL == 3) ? 4 : rowsL;
15061                 const size_t    alignedColsR    = (colsR == 3) ? 4 : colsR;
15062                 const size_t    alignedRowsR    = (rowsR == 3) ? 4 : rowsR;
15063
15064                 DE_ASSERT(getOutCompCount() == alignedColsR * alignedRowsL);
15065                 DE_ASSERT(getArgCompCount(0) == alignedColsL * alignedRowsL);
15066                 DE_ASSERT(getArgCompCount(1) == alignedColsR * alignedRowsR);
15067                 DE_UNREF(alignedColsL);
15068                 DE_UNREF(alignedColsR);
15069
15070                 if (getFlavor() == 0)
15071                 {
15072                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15073                         {
15074                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15075                                 {
15076                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15077                                         fp16type                s       (fp16type::zero(1));
15078
15079                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15080                                         {
15081                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15082                                                 const fp16type  l               (in[0][ndxl]);
15083                                                 const float             lf              (l.asFloat());
15084                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15085                                                 const fp16type  r               (in[1][ndxr]);
15086                                                 const float             rf              (r.asFloat());
15087                                                 const fp16type  m               (lf * rf);
15088
15089                                                 s = fp16type(s.asFloat() + m.asFloat());
15090                                         }
15091
15092                                         out[ndx] = s.bits();
15093                                         min[ndx] = getMin(s.asDouble(), getULPs(in));
15094                                         max[ndx] = getMax(s.asDouble(), getULPs(in));
15095                                 }
15096                         }
15097                 }
15098                 else if (getFlavor() == 1)
15099                 {
15100                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15101                         {
15102                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15103                                 {
15104                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15105                                         float                   s       (0.0f);
15106
15107                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15108                                         {
15109                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15110                                                 const fp16type  l               (in[0][ndxl]);
15111                                                 const float             lf              (l.asFloat());
15112                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15113                                                 const fp16type  r               (in[1][ndxr]);
15114                                                 const float             rf              (r.asFloat());
15115                                                 const float             m               (lf * rf);
15116
15117                                                 s += m;
15118                                         }
15119
15120                                         out[ndx] = fp16type(s).bits();
15121                                         min[ndx] = getMin(static_cast<double>(s), getULPs(in));
15122                                         max[ndx] = getMax(static_cast<double>(s), getULPs(in));
15123                                 }
15124                         }
15125                 }
15126                 else
15127                 {
15128                         TCU_THROW(InternalError, "Unknown flavor");
15129                 }
15130
15131                 return true;
15132         }
15133 };
15134
15135 template<size_t cols, size_t rows>
15136 struct fp16OuterProduct : public fp16MatrixBase
15137 {
15138         virtual double getULPs (vector<const deFloat16*>& in)
15139         {
15140                 DE_UNREF(in);
15141
15142                 return 2.0;
15143         }
15144
15145         deUint32 getComponentValidity ()
15146         {
15147                 return getComponentMatrixValidityMask(cols, rows);
15148         }
15149
15150         template<class fp16type>
15151         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15152         {
15153                 DE_ASSERT(in.size() == 2);
15154
15155                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15156                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15157
15158                 DE_ASSERT(getArgCompCount(0) == rows);
15159                 DE_ASSERT(getArgCompCount(1) == cols);
15160                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
15161                 DE_UNREF(alignedCols);
15162
15163                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15164                 {
15165                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15166                         {
15167                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15168                                 const fp16type  x       (in[0][rowNdx]);
15169                                 const float             xf      (x.asFloat());
15170                                 const fp16type  y       (in[1][colNdx]);
15171                                 const float             yf      (y.asFloat());
15172                                 const fp16type  m       (xf * yf);
15173
15174                                 out[ndx] = m.bits();
15175                                 min[ndx] = getMin(m.asDouble(), getULPs(in));
15176                                 max[ndx] = getMax(m.asDouble(), getULPs(in));
15177                         }
15178                 }
15179
15180                 return true;
15181         }
15182 };
15183
15184 template<size_t size>
15185 struct fp16Determinant;
15186
15187 template<>
15188 struct fp16Determinant<2> : public fp16MatrixBase
15189 {
15190         virtual double getULPs (vector<const deFloat16*>& in)
15191         {
15192                 DE_UNREF(in);
15193
15194                 return 128.0; // This is not a precision test. Value is not from spec
15195         }
15196
15197         deUint32 getComponentValidity ()
15198         {
15199                 return 1;
15200         }
15201
15202         template<class fp16type>
15203         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15204         {
15205                 const size_t    cols            = 2;
15206                 const size_t    rows            = 2;
15207                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15208                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15209
15210                 DE_ASSERT(in.size() == 1);
15211                 DE_ASSERT(getOutCompCount() == 1);
15212                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15213                 DE_UNREF(alignedCols);
15214                 DE_UNREF(alignedRows);
15215
15216                 // [ a b ]
15217                 // [ c d ]
15218                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15219                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15220                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15221                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15222                 const float             ad              (a * d);
15223                 const fp16type  adf16   (ad);
15224                 const float             bc              (b * c);
15225                 const fp16type  bcf16   (bc);
15226                 const float             r               (adf16.asFloat() - bcf16.asFloat());
15227                 const fp16type  rf16    (r);
15228
15229                 out[0] = rf16.bits();
15230                 min[0] = getMin(r, getULPs(in));
15231                 max[0] = getMax(r, getULPs(in));
15232
15233                 return true;
15234         }
15235 };
15236
15237 template<>
15238 struct fp16Determinant<3> : public fp16MatrixBase
15239 {
15240         virtual double getULPs (vector<const deFloat16*>& in)
15241         {
15242                 DE_UNREF(in);
15243
15244                 return 128.0; // This is not a precision test. Value is not from spec
15245         }
15246
15247         deUint32 getComponentValidity ()
15248         {
15249                 return 1;
15250         }
15251
15252         template<class fp16type>
15253         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15254         {
15255                 const size_t    cols            = 3;
15256                 const size_t    rows            = 3;
15257                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15258                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15259
15260                 DE_ASSERT(in.size() == 1);
15261                 DE_ASSERT(getOutCompCount() == 1);
15262                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15263                 DE_UNREF(alignedCols);
15264                 DE_UNREF(alignedRows);
15265
15266                 // [ a b c ]
15267                 // [ d e f ]
15268                 // [ g h i ]
15269                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15270                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15271                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15272                 const float             d               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15273                 const float             e               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15274                 const float             f               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15275                 const float             g               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15276                 const float             h               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15277                 const float             i               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15278                 const fp16type  aei             (a * e * i);
15279                 const fp16type  bfg             (b * f * g);
15280                 const fp16type  cdh             (c * d * h);
15281                 const fp16type  ceg             (c * e * g);
15282                 const fp16type  bdi             (b * d * i);
15283                 const fp16type  afh             (a * f * h);
15284                 const float             r               (aei.asFloat() + bfg.asFloat() + cdh.asFloat() - ceg.asFloat() - bdi.asFloat() - afh.asFloat());
15285                 const fp16type  rf16    (r);
15286
15287                 out[0] = rf16.bits();
15288                 min[0] = getMin(r, getULPs(in));
15289                 max[0] = getMax(r, getULPs(in));
15290
15291                 return true;
15292         }
15293 };
15294
15295 template<>
15296 struct fp16Determinant<4> : public fp16MatrixBase
15297 {
15298         virtual double getULPs (vector<const deFloat16*>& in)
15299         {
15300                 DE_UNREF(in);
15301
15302                 return 128.0; // This is not a precision test. Value is not from spec
15303         }
15304
15305         deUint32 getComponentValidity ()
15306         {
15307                 return 1;
15308         }
15309
15310         template<class fp16type>
15311         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15312         {
15313                 const size_t    rows            = 4;
15314                 const size_t    cols            = 4;
15315                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15316                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15317
15318                 DE_ASSERT(in.size() == 1);
15319                 DE_ASSERT(getOutCompCount() == 1);
15320                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15321                 DE_UNREF(alignedCols);
15322                 DE_UNREF(alignedRows);
15323
15324                 // [ a b c d ]
15325                 // [ e f g h ]
15326                 // [ i j k l ]
15327                 // [ m n o p ]
15328                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15329                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15330                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15331                 const float             d               (fp16type(in[0][getNdx(rows, 3, 0)]).asFloat());
15332                 const float             e               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15333                 const float             f               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15334                 const float             g               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15335                 const float             h               (fp16type(in[0][getNdx(rows, 3, 1)]).asFloat());
15336                 const float             i               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15337                 const float             j               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15338                 const float             k               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15339                 const float             l               (fp16type(in[0][getNdx(rows, 3, 2)]).asFloat());
15340                 const float             m               (fp16type(in[0][getNdx(rows, 0, 3)]).asFloat());
15341                 const float             n               (fp16type(in[0][getNdx(rows, 1, 3)]).asFloat());
15342                 const float             o               (fp16type(in[0][getNdx(rows, 2, 3)]).asFloat());
15343                 const float             p               (fp16type(in[0][getNdx(rows, 3, 3)]).asFloat());
15344
15345                 // [ f g h ]
15346                 // [ j k l ]
15347                 // [ n o p ]
15348                 const fp16type  fkp             (f * k * p);
15349                 const fp16type  gln             (g * l * n);
15350                 const fp16type  hjo             (h * j * o);
15351                 const fp16type  hkn             (h * k * n);
15352                 const fp16type  gjp             (g * j * p);
15353                 const fp16type  flo             (f * l * o);
15354                 const fp16type  detA    (a * (fkp.asFloat() + gln.asFloat() + hjo.asFloat() - hkn.asFloat() - gjp.asFloat() - flo.asFloat()));
15355
15356                 // [ e g h ]
15357                 // [ i k l ]
15358                 // [ m o p ]
15359                 const fp16type  ekp             (e * k * p);
15360                 const fp16type  glm             (g * l * m);
15361                 const fp16type  hio             (h * i * o);
15362                 const fp16type  hkm             (h * k * m);
15363                 const fp16type  gip             (g * i * p);
15364                 const fp16type  elo             (e * l * o);
15365                 const fp16type  detB    (b * (ekp.asFloat() + glm.asFloat() + hio.asFloat() - hkm.asFloat() - gip.asFloat() - elo.asFloat()));
15366
15367                 // [ e f h ]
15368                 // [ i j l ]
15369                 // [ m n p ]
15370                 const fp16type  ejp             (e * j * p);
15371                 const fp16type  flm             (f * l * m);
15372                 const fp16type  hin             (h * i * n);
15373                 const fp16type  hjm             (h * j * m);
15374                 const fp16type  fip             (f * i * p);
15375                 const fp16type  eln             (e * l * n);
15376                 const fp16type  detC    (c * (ejp.asFloat() + flm.asFloat() + hin.asFloat() - hjm.asFloat() - fip.asFloat() - eln.asFloat()));
15377
15378                 // [ e f g ]
15379                 // [ i j k ]
15380                 // [ m n o ]
15381                 const fp16type  ejo             (e * j * o);
15382                 const fp16type  fkm             (f * k * m);
15383                 const fp16type  gin             (g * i * n);
15384                 const fp16type  gjm             (g * j * m);
15385                 const fp16type  fio             (f * i * o);
15386                 const fp16type  ekn             (e * k * n);
15387                 const fp16type  detD    (d * (ejo.asFloat() + fkm.asFloat() + gin.asFloat() - gjm.asFloat() - fio.asFloat() - ekn.asFloat()));
15388
15389                 const float             r               (detA.asFloat() - detB.asFloat() + detC.asFloat() - detD.asFloat());
15390                 const fp16type  rf16    (r);
15391
15392                 out[0] = rf16.bits();
15393                 min[0] = getMin(r, getULPs(in));
15394                 max[0] = getMax(r, getULPs(in));
15395
15396                 return true;
15397         }
15398 };
15399
15400 template<size_t size>
15401 struct fp16Inverse;
15402
15403 template<>
15404 struct fp16Inverse<2> : public fp16MatrixBase
15405 {
15406         virtual double getULPs (vector<const deFloat16*>& in)
15407         {
15408                 DE_UNREF(in);
15409
15410                 return 128.0; // This is not a precision test. Value is not from spec
15411         }
15412
15413         deUint32 getComponentValidity ()
15414         {
15415                 return getComponentMatrixValidityMask(2, 2);
15416         }
15417
15418         template<class fp16type>
15419         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15420         {
15421                 const size_t    cols            = 2;
15422                 const size_t    rows            = 2;
15423                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15424                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15425
15426                 DE_ASSERT(in.size() == 1);
15427                 DE_ASSERT(getOutCompCount() == alignedRows * alignedCols);
15428                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15429                 DE_UNREF(alignedCols);
15430
15431                 // [ a b ]
15432                 // [ c d ]
15433                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15434                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15435                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15436                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15437                 const float             ad              (a * d);
15438                 const fp16type  adf16   (ad);
15439                 const float             bc              (b * c);
15440                 const fp16type  bcf16   (bc);
15441                 const float             det             (adf16.asFloat() - bcf16.asFloat());
15442                 const fp16type  det16   (det);
15443
15444                 out[0] = fp16type( d / det16.asFloat()).bits();
15445                 out[1] = fp16type(-c / det16.asFloat()).bits();
15446                 out[2] = fp16type(-b / det16.asFloat()).bits();
15447                 out[3] = fp16type( a / det16.asFloat()).bits();
15448
15449                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15450                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15451                         {
15452                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15453                                 const fp16type  s       (out[ndx]);
15454
15455                                 min[ndx] = getMin(s.asDouble(), getULPs(in));
15456                                 max[ndx] = getMax(s.asDouble(), getULPs(in));
15457                         }
15458
15459                 return true;
15460         }
15461 };
15462
15463 inline std::string fp16ToString(deFloat16 val)
15464 {
15465         return tcu::toHex<4>(val).toString() + " (" + de::floatToString(tcu::Float16(val).asFloat(), 10) + ")";
15466 }
15467
15468 template <size_t RES_COMPONENTS, size_t ARG0_COMPONENTS, size_t ARG1_COMPONENTS, size_t ARG2_COMPONENTS, class TestedArithmeticFunction>
15469 bool compareFP16ArithmeticFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
15470 {
15471         if (inputs.size() < 1 || inputs.size() > 3 || outputAllocs.size() != 1 || expectedOutputs.size() != 1)
15472                 return false;
15473
15474         const size_t    resultStep                      = (RES_COMPONENTS == 3) ? 4 : RES_COMPONENTS;
15475         const size_t    iterationsCount         = expectedOutputs[0].getByteSize() / (sizeof(deFloat16) * resultStep);
15476         const size_t    inputsSteps[3]          =
15477         {
15478                 (ARG0_COMPONENTS == 3) ? 4 : ARG0_COMPONENTS,
15479                 (ARG1_COMPONENTS == 3) ? 4 : ARG1_COMPONENTS,
15480                 (ARG2_COMPONENTS == 3) ? 4 : ARG2_COMPONENTS,
15481         };
15482
15483         DE_ASSERT(expectedOutputs[0].getByteSize() > 0);
15484         DE_ASSERT(expectedOutputs[0].getByteSize() == sizeof(deFloat16) * iterationsCount * resultStep);
15485
15486         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15487         {
15488                 DE_ASSERT(inputs[inputNdx].getByteSize() > 0);
15489                 DE_ASSERT(inputs[inputNdx].getByteSize() == sizeof(deFloat16) * iterationsCount * inputsSteps[inputNdx]);
15490         }
15491
15492         const deFloat16* const          outputAsFP16                                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
15493         TestedArithmeticFunction        func;
15494
15495         func.setOutCompCount(RES_COMPONENTS);
15496         func.setArgCompCount(0, ARG0_COMPONENTS);
15497         func.setArgCompCount(1, ARG1_COMPONENTS);
15498         func.setArgCompCount(2, ARG2_COMPONENTS);
15499
15500         const bool                                      callOncePerComponent                    = func.callOncePerComponent();
15501         const deUint32                          componentValidityMask                   = func.getComponentValidity();
15502         const size_t                            denormModesCount                                = 2;
15503         const char*                                     denormModes[denormModesCount]   = { "keep denormal numbers", "flush to zero" };
15504         const size_t                            successfulRunsPerComponent              = denormModesCount * func.getFlavorCount();
15505         bool                                            success                                                 = true;
15506         size_t                                          validatedCount                                  = 0;
15507
15508         vector<deUint8> inputBytes[3];
15509
15510         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15511                 inputs[inputNdx].getBytes(inputBytes[inputNdx]);
15512
15513         const deFloat16* const                  inputsAsFP16[3]                 =
15514         {
15515                 inputs.size() >= 1 ? (const deFloat16*)&inputBytes[0][0] : DE_NULL,
15516                 inputs.size() >= 2 ? (const deFloat16*)&inputBytes[1][0] : DE_NULL,
15517                 inputs.size() >= 3 ? (const deFloat16*)&inputBytes[2][0] : DE_NULL,
15518         };
15519
15520         for (size_t idx = 0; idx < iterationsCount; ++idx)
15521         {
15522                 std::vector<size_t>                     successfulRuns          (RES_COMPONENTS, successfulRunsPerComponent);
15523                 std::vector<std::string>        errors                          (RES_COMPONENTS);
15524                 bool                                            iterationValidated      (true);
15525
15526                 for (size_t denormNdx = 0; denormNdx < 2; ++denormNdx)
15527                 {
15528                         for (size_t flavorNdx = 0; flavorNdx < func.getFlavorCount(); ++flavorNdx)
15529                         {
15530                                 func.setFlavor(flavorNdx);
15531
15532                                 const deFloat16*                        iterationOutputFP16             = &outputAsFP16[idx * resultStep];
15533                                 vector<deFloat16>                       iterationCalculatedFP16 (resultStep, 0);
15534                                 vector<double>                          iterationEdgeMin                (resultStep, 0.0);
15535                                 vector<double>                          iterationEdgeMax                (resultStep, 0.0);
15536                                 vector<const deFloat16*>        arguments;
15537
15538                                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15539                                 {
15540                                         std::string     error;
15541                                         bool            reportError = false;
15542
15543                                         if (callOncePerComponent || componentNdx == 0)
15544                                         {
15545                                                 bool funcCallResult;
15546
15547                                                 arguments.clear();
15548
15549                                                 for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15550                                                         arguments.push_back(&inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + componentNdx]);
15551
15552                                                 if (denormNdx == 0)
15553                                                         funcCallResult = func.template calc<tcu::Float16>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15554                                                 else
15555                                                         funcCallResult = func.template calc<tcu::Float16Denormless>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15556
15557                                                 if (!funcCallResult)
15558                                                 {
15559                                                         iterationValidated = false;
15560
15561                                                         if (callOncePerComponent)
15562                                                                 continue;
15563                                                         else
15564                                                                 break;
15565                                                 }
15566                                         }
15567
15568                                         if ((componentValidityMask != 0) && (componentValidityMask & (1<<componentNdx)) == 0)
15569                                                 continue;
15570
15571                                         reportError = !compare16BitFloat(iterationCalculatedFP16[componentNdx], iterationOutputFP16[componentNdx], error);
15572
15573                                         if (reportError)
15574                                         {
15575                                                 tcu::Float16 expected   (iterationCalculatedFP16[componentNdx]);
15576                                                 tcu::Float16 outputted  (iterationOutputFP16[componentNdx]);
15577
15578                                                 if (reportError && expected.isNaN())
15579                                                         reportError = false;
15580
15581                                                 if (reportError && !expected.isNaN() && !outputted.isNaN())
15582                                                 {
15583                                                         if (reportError && !expected.isInf() && !outputted.isInf())
15584                                                         {
15585                                                                 // Ignore rounding
15586                                                                 if (expected.bits() == outputted.bits() + 1 || expected.bits() + 1 == outputted.bits())
15587                                                                         reportError = false;
15588                                                         }
15589
15590                                                         if (reportError && expected.isInf())
15591                                                         {
15592                                                                 // RTZ rounding mode returns +/-65504 instead of Inf on overflow
15593                                                                 if (expected.sign() == 1 && outputted.bits() == 0x7bff && iterationEdgeMin[componentNdx] <= std::numeric_limits<double>::max())
15594                                                                         reportError = false;
15595                                                                 else if (expected.sign() == -1 && outputted.bits() == 0xfbff && iterationEdgeMax[componentNdx] >= -std::numeric_limits<double>::max())
15596                                                                         reportError = false;
15597                                                         }
15598
15599                                                         if (reportError)
15600                                                         {
15601                                                                 const double    outputtedDouble = outputted.asDouble();
15602
15603                                                                 DE_ASSERT(iterationEdgeMin[componentNdx] <= iterationEdgeMax[componentNdx]);
15604
15605                                                                 if (de::inRange(outputtedDouble, iterationEdgeMin[componentNdx], iterationEdgeMax[componentNdx]))
15606                                                                         reportError = false;
15607                                                         }
15608                                                 }
15609
15610                                                 if (reportError)
15611                                                 {
15612                                                         const size_t            inputsComps[3]  =
15613                                                         {
15614                                                                 ARG0_COMPONENTS,
15615                                                                 ARG1_COMPONENTS,
15616                                                                 ARG2_COMPONENTS,
15617                                                         };
15618                                                         string                          inputsValues    ("Inputs:");
15619                                                         string                          flavorName              (func.getFlavorCount() == 1 ? "" : string(" flavor ") + de::toString(flavorNdx) + " (" + func.getCurrentFlavorName() + ")");
15620                                                         std::stringstream       errStream;
15621
15622                                                         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15623                                                         {
15624                                                                 const size_t    inputCompsCount = inputsComps[inputNdx];
15625
15626                                                                 inputsValues += " [" + de::toString(inputNdx) + "]=(";
15627
15628                                                                 for (size_t compNdx = 0; compNdx < inputCompsCount; ++compNdx)
15629                                                                 {
15630                                                                         const deFloat16 inputComponentValue = inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + compNdx];
15631
15632                                                                         inputsValues += fp16ToString(inputComponentValue) + ((compNdx + 1 == inputCompsCount) ? ")": ", ");
15633                                                                 }
15634                                                         }
15635
15636                                                         errStream       << "At"
15637                                                                                 << " iteration " << de::toString(idx)
15638                                                                                 << " component " << de::toString(componentNdx)
15639                                                                                 << " denormMode " << de::toString(denormNdx)
15640                                                                                 << " (" << denormModes[denormNdx] << ")"
15641                                                                                 << " " << flavorName
15642                                                                                 << " " << inputsValues
15643                                                                                 << " outputted:" + fp16ToString(iterationOutputFP16[componentNdx])
15644                                                                                 << " expected:" + fp16ToString(iterationCalculatedFP16[componentNdx])
15645                                                                                 << " or in range: [" << iterationEdgeMin[componentNdx] << ", " << iterationEdgeMax[componentNdx] << "]."
15646                                                                                 << " " << error << "."
15647                                                                                 << std::endl;
15648
15649                                                         errors[componentNdx] += errStream.str();
15650
15651                                                         successfulRuns[componentNdx]--;
15652                                                 }
15653                                         }
15654                                 }
15655                         }
15656                 }
15657
15658                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15659                 {
15660                         // Check if any component has total failure
15661                         if (successfulRuns[componentNdx] == 0)
15662                         {
15663                                 // Test failed in all denorm modes and all flavors for certain component: dump errors
15664                                 log << TestLog::Message << errors[componentNdx] << TestLog::EndMessage;
15665
15666                                 success = false;
15667                         }
15668                 }
15669
15670                 if (iterationValidated)
15671                         validatedCount++;
15672         }
15673
15674         if (validatedCount < 16)
15675                 TCU_THROW(InternalError, "Too few samples has been validated.");
15676
15677         return success;
15678 }
15679
15680 // IEEE-754 floating point numbers:
15681 // +--------+------+----------+-------------+
15682 // | binary | sign | exponent | significand |
15683 // +--------+------+----------+-------------+
15684 // | 16-bit |  1   |    5     |     10      |
15685 // +--------+------+----------+-------------+
15686 // | 32-bit |  1   |    8     |     23      |
15687 // +--------+------+----------+-------------+
15688 //
15689 // 16-bit floats:
15690 //
15691 // 0   000 00   00 0000 0001 (0x0001: 2e-24:         minimum positive denormalized)
15692 // 0   000 00   11 1111 1111 (0x03ff: 2e-14 - 2e-24: maximum positive denormalized)
15693 // 0   000 01   00 0000 0000 (0x0400: 2e-14:         minimum positive normalized)
15694 // 0   111 10   11 1111 1111 (0x7bff: 65504:         maximum positive normalized)
15695 //
15696 // 0   000 00   00 0000 0000 (0x0000: +0)
15697 // 0   111 11   00 0000 0000 (0x7c00: +Inf)
15698 // 0   000 00   11 1111 0000 (0x03f0: +Denorm)
15699 // 0   000 01   00 0000 0001 (0x0401: +Norm)
15700 // 0   111 11   00 0000 1111 (0x7c0f: +SNaN)
15701 // 0   111 11   11 1111 0000 (0x7ff0: +QNaN)
15702 // Generate and return 16-bit floats and their corresponding 32-bit values.
15703 //
15704 // The first 14 number pairs are manually picked, while the rest are randomly generated.
15705 // Expected count to be at least 14 (numPicks).
15706 vector<deFloat16> getFloat16a (de::Random& rnd, deUint32 count)
15707 {
15708         vector<deFloat16>       float16;
15709
15710         float16.reserve(count);
15711
15712         // Zero
15713         float16.push_back(deUint16(0x0000));
15714         float16.push_back(deUint16(0x8000));
15715         // Infinity
15716         float16.push_back(deUint16(0x7c00));
15717         float16.push_back(deUint16(0xfc00));
15718         // Normalized
15719         float16.push_back(deUint16(0x0401));
15720         float16.push_back(deUint16(0x8401));
15721         // Some normal number
15722         float16.push_back(deUint16(0x14cb));
15723         float16.push_back(deUint16(0x94cb));
15724         // Min/max positive normal
15725         float16.push_back(deUint16(0x0400));
15726         float16.push_back(deUint16(0x7bff));
15727         // Min/max negative normal
15728         float16.push_back(deUint16(0x8400));
15729         float16.push_back(deUint16(0xfbff));
15730         // PI
15731         float16.push_back(deUint16(0x4248)); // 3.140625
15732         float16.push_back(deUint16(0xb248)); // -3.140625
15733         // PI/2
15734         float16.push_back(deUint16(0x3e48)); // 1.5703125
15735         float16.push_back(deUint16(0xbe48)); // -1.5703125
15736         float16.push_back(deUint16(0x3c00)); // 1.0
15737         float16.push_back(deUint16(0x3800)); // 0.5
15738         // Some useful constants
15739         float16.push_back(tcu::Float16(-2.5f).bits());
15740         float16.push_back(tcu::Float16(-1.0f).bits());
15741         float16.push_back(tcu::Float16( 0.4f).bits());
15742         float16.push_back(tcu::Float16( 2.5f).bits());
15743
15744         const deUint32          numPicks        = static_cast<deUint32>(float16.size());
15745
15746         DE_ASSERT(count >= numPicks);
15747         count -= numPicks;
15748
15749         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15750         {
15751                 int                     sign            = (rnd.getUint16() % 2 == 0) ? +1 : -1;
15752                 int                     exponent        = (rnd.getUint16() % 29) - 14 + 1;
15753                 deUint16        mantissa        = static_cast<deUint16>(2 * (rnd.getUint16() % 512));
15754
15755                 // Exclude power of -14 to avoid denorms
15756                 DE_ASSERT(de::inRange(exponent, -13, 15));
15757
15758                 float16.push_back(tcu::Float16::constructBits(sign, exponent, mantissa).bits());
15759         }
15760
15761         return float16;
15762 }
15763
15764 static inline vector<deFloat16> getInputData1 (deUint32 seed, size_t count, size_t argNo)
15765 {
15766         DE_UNREF(argNo);
15767
15768         de::Random      rnd(seed);
15769
15770         return getFloat16a(rnd, static_cast<deUint32>(count));
15771 }
15772
15773 static inline vector<deFloat16> getInputData2 (deUint32 seed, size_t count, size_t argNo)
15774 {
15775         de::Random      rnd             (seed);
15776         size_t          newCount = static_cast<size_t>(deSqrt(double(count)));
15777
15778         DE_ASSERT(newCount * newCount == count);
15779
15780         vector<deFloat16>       float16 = getFloat16a(rnd, static_cast<deUint32>(newCount));
15781
15782         return squarize(float16, static_cast<deUint32>(argNo));
15783 }
15784
15785 static inline vector<deFloat16> getInputData3 (deUint32 seed, size_t count, size_t argNo)
15786 {
15787         if (argNo == 0 || argNo == 1)
15788                 return getInputData2(seed, count, argNo);
15789         else
15790                 return getInputData1(seed<<argNo, count, argNo);
15791 }
15792
15793 vector<deFloat16> getInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15794 {
15795         DE_UNREF(stride);
15796
15797         vector<deFloat16>       result;
15798
15799         switch (argCount)
15800         {
15801                 case 1:result = getInputData1(seed, count, argNo); break;
15802                 case 2:result = getInputData2(seed, count, argNo); break;
15803                 case 3:result = getInputData3(seed, count, argNo); break;
15804                 default: TCU_THROW(InternalError, "Invalid argument count specified");
15805         }
15806
15807         if (compCount == 3)
15808         {
15809                 const size_t            newCount = (3 * count) / 4;
15810                 vector<deFloat16>       newResult;
15811
15812                 newResult.reserve(result.size());
15813
15814                 for (size_t ndx = 0; ndx < newCount; ++ndx)
15815                 {
15816                         newResult.push_back(result[ndx]);
15817
15818                         if (ndx % 3 == 2)
15819                                 newResult.push_back(0);
15820                 }
15821
15822                 result = newResult;
15823         }
15824
15825         DE_ASSERT(result.size() == count);
15826
15827         return result;
15828 }
15829
15830 // Generator for functions requiring data in range [1, inf]
15831 vector<deFloat16> getInputDataAC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15832 {
15833         vector<deFloat16>       result;
15834
15835         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15836
15837         // Filter out values below 1.0 from upper half of numbers
15838         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15839         {
15840                 const float f = tcu::Float16(result[idx]).asFloat();
15841
15842                 if (f < 1.0f)
15843                         result[idx] = tcu::Float16(1.0f - f).bits();
15844         }
15845
15846         return result;
15847 }
15848
15849 // Generator for functions requiring data in range [-1, 1]
15850 vector<deFloat16> getInputDataA (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15851 {
15852         vector<deFloat16>       result;
15853
15854         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15855
15856         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15857         {
15858                 const float f = tcu::Float16(result[idx]).asFloat();
15859
15860                 if (!de::inRange(f, -1.0f, 1.0f))
15861                         result[idx] = tcu::Float16(deFloatFrac(f)).bits();
15862         }
15863
15864         return result;
15865 }
15866
15867 // Generator for functions requiring data in range [-pi, pi]
15868 vector<deFloat16> getInputDataPI (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15869 {
15870         vector<deFloat16>       result;
15871
15872         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15873
15874         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15875         {
15876                 const float f = tcu::Float16(result[idx]).asFloat();
15877
15878                 if (!de::inRange(f, -DE_PI, DE_PI))
15879                         result[idx] = tcu::Float16(fmodf(f, DE_PI)).bits();
15880         }
15881
15882         return result;
15883 }
15884
15885 // Generator for functions requiring data in range [0, inf]
15886 vector<deFloat16> getInputDataP (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15887 {
15888         vector<deFloat16>       result;
15889
15890         result = getInputData(seed, count, compCount, stride, argCount, argNo);
15891
15892         if (argNo == 0)
15893         {
15894                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15895                         result[idx] &= static_cast<deFloat16>(~0x8000);
15896         }
15897
15898         return result;
15899 }
15900
15901 vector<deFloat16> getInputDataV (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15902 {
15903         DE_UNREF(stride);
15904         DE_UNREF(argCount);
15905
15906         vector<deFloat16>       result;
15907
15908         if (argNo == 0)
15909                 result = getInputData2(seed, count, argNo);
15910         else
15911         {
15912                 const size_t            alignedCount    = (compCount == 3) ? 4 : compCount;
15913                 const size_t            newCountX               = static_cast<size_t>(deSqrt(double(count * alignedCount)));
15914                 const size_t            newCountY               = count / newCountX;
15915                 de::Random                      rnd                             (seed);
15916                 vector<deFloat16>       float16                 = getFloat16a(rnd, static_cast<deUint32>(newCountX));
15917
15918                 DE_ASSERT(newCountX * newCountX == alignedCount * count);
15919
15920                 for (size_t numIdx = 0; numIdx < newCountX; ++numIdx)
15921                 {
15922                         const vector<deFloat16> tmp(newCountY, float16[numIdx]);
15923
15924                         result.insert(result.end(), tmp.begin(), tmp.end());
15925                 }
15926         }
15927
15928         DE_ASSERT(result.size() == count);
15929
15930         return result;
15931 }
15932
15933 vector<deFloat16> getInputDataM (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15934 {
15935         DE_UNREF(compCount);
15936         DE_UNREF(stride);
15937         DE_UNREF(argCount);
15938
15939         de::Random                      rnd             (seed << argNo);
15940         vector<deFloat16>       result;
15941
15942         result = getFloat16a(rnd, static_cast<deUint32>(count));
15943
15944         DE_ASSERT(result.size() == count);
15945
15946         return result;
15947 }
15948
15949 vector<deFloat16> getInputDataD (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15950 {
15951         DE_UNREF(compCount);
15952         DE_UNREF(argCount);
15953
15954         de::Random                      rnd             (seed << argNo);
15955         vector<deFloat16>       result;
15956
15957         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15958         {
15959                 int num = (rnd.getUint16() % 16) - 8;
15960
15961                 result.push_back(tcu::Float16(float(num)).bits());
15962         }
15963
15964         result[0 * stride] = deUint16(0x7c00); // +Inf
15965         result[1 * stride] = deUint16(0xfc00); // -Inf
15966
15967         DE_ASSERT(result.size() == count);
15968
15969         return result;
15970 }
15971
15972 // Generator for smoothstep function
15973 vector<deFloat16> getInputDataSS (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
15974 {
15975         vector<deFloat16>       result;
15976
15977         result = getInputDataD(seed, count, compCount, stride, argCount, argNo);
15978
15979         if (argNo == 0)
15980         {
15981                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15982                 {
15983                         const float f = tcu::Float16(result[idx]).asFloat();
15984
15985                         if (f > 4.0f)
15986                                 result[idx] = tcu::Float16(-f).bits();
15987                 }
15988         }
15989
15990         if (argNo == 1)
15991         {
15992                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
15993                 {
15994                         const float f = tcu::Float16(result[idx]).asFloat();
15995
15996                         if (f < 4.0f)
15997                                 result[idx] = tcu::Float16(-f).bits();
15998                 }
15999         }
16000
16001         return result;
16002 }
16003
16004 // Generates normalized vectors for arguments 0 and 1
16005 vector<deFloat16> getInputDataN (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16006 {
16007         DE_UNREF(compCount);
16008         DE_UNREF(argCount);
16009
16010         de::Random                      rnd             (seed << argNo);
16011         vector<deFloat16>       result;
16012
16013         if (argNo == 0 || argNo == 1)
16014         {
16015                 // The input parameters for the incident vector I and the surface normal N must already be normalized
16016                 for (size_t numIdx = 0; numIdx < count; numIdx += stride)
16017                 {
16018                         vector <float>  unnormolized;
16019                         float                   sum                             = 0;
16020
16021                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16022                                 unnormolized.push_back(float((rnd.getUint16() % 16) - 8));
16023
16024                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16025                                 sum += unnormolized[compIdx] * unnormolized[compIdx];
16026
16027                         sum = deFloatSqrt(sum);
16028                         if (sum == 0.0f)
16029                                 unnormolized[0] = sum = 1.0f;
16030
16031                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16032                                 result.push_back(tcu::Float16(unnormolized[compIdx] / sum).bits());
16033
16034                         for (size_t compIdx = compCount; compIdx < stride; ++compIdx)
16035                                 result.push_back(0);
16036                 }
16037         }
16038         else
16039         {
16040                 // Input parameter eta
16041                 for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16042                 {
16043                         int num = (rnd.getUint16() % 16) - 8;
16044
16045                         result.push_back(tcu::Float16(float(num)).bits());
16046                 }
16047         }
16048
16049         DE_ASSERT(result.size() == count);
16050
16051         return result;
16052 }
16053
16054 // Data generator for complex matrix functions like determinant and inverse
16055 vector<deFloat16> getInputDataC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16056 {
16057         DE_UNREF(compCount);
16058         DE_UNREF(stride);
16059         DE_UNREF(argCount);
16060
16061         de::Random                      rnd             (seed << argNo);
16062         vector<deFloat16>       result;
16063
16064         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16065         {
16066                 int num = (rnd.getUint16() % 16) - 8;
16067
16068                 result.push_back(tcu::Float16(float(num)).bits());
16069         }
16070
16071         DE_ASSERT(result.size() == count);
16072
16073         return result;
16074 }
16075
16076 struct Math16TestType
16077 {
16078         const char*             typePrefix;
16079         const size_t    typeComponents;
16080         const size_t    typeArrayStride;
16081         const size_t    typeStructStride;
16082 };
16083
16084 enum Math16DataTypes
16085 {
16086         NONE    = 0,
16087         SCALAR  = 1,
16088         VEC2    = 2,
16089         VEC3    = 3,
16090         VEC4    = 4,
16091         MAT2X2,
16092         MAT2X3,
16093         MAT2X4,
16094         MAT3X2,
16095         MAT3X3,
16096         MAT3X4,
16097         MAT4X2,
16098         MAT4X3,
16099         MAT4X4,
16100         MATH16_TYPE_LAST
16101 };
16102
16103 struct Math16ArgFragments
16104 {
16105         const char*     bodies;
16106         const char*     variables;
16107         const char*     decorations;
16108         const char*     funcVariables;
16109 };
16110
16111 typedef vector<deFloat16> Math16GetInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo);
16112
16113 struct Math16TestFunc
16114 {
16115         const char*                                     funcName;
16116         const char*                                     funcSuffix;
16117         size_t                                          funcArgsCount;
16118         size_t                                          typeResult;
16119         size_t                                          typeArg0;
16120         size_t                                          typeArg1;
16121         size_t                                          typeArg2;
16122         Math16GetInputData*                     getInputDataFunc;
16123         VerifyIOFunc                            verifyFunc;
16124 };
16125
16126 template<class SpecResource>
16127 void createFloat16ArithmeticFuncTest (tcu::TestContext& testCtx, tcu::TestCaseGroup& testGroup, const size_t testTypeIdx, const Math16TestFunc& testFunc)
16128 {
16129         const int                                       testSpecificSeed                        = deStringHash(testGroup.getName());
16130         const int                                       seed                                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
16131         const size_t                            numDataPointsByAxis                     = 32;
16132         const size_t                            numDataPoints                           = numDataPointsByAxis * numDataPointsByAxis;
16133         const char*                                     componentType                           = "f16";
16134         const Math16TestType            testTypes[MATH16_TYPE_LAST]     =
16135         {
16136                 { "",           0,       0,                                              0,                                             },
16137                 { "",           1,       1 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16138                 { "v2",         2,       2 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16139                 { "v3",         3,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16140                 { "v4",         4,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16141                 { "m2x2",       0,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16142                 { "m2x3",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16143                 { "m2x4",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16144                 { "m3x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16145                 { "m3x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16146                 { "m3x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16147                 { "m4x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16148                 { "m4x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16149                 { "m4x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16150         };
16151
16152         DE_ASSERT(testTypeIdx == testTypes[testTypeIdx].typeComponents);
16153
16154
16155         const StringTemplate preMain
16156         (
16157                 "     %c_i32_ndp  = OpConstant %i32 ${num_data_points}\n"
16158
16159                 "        %f16     = OpTypeFloat 16\n"
16160                 "        %v2f16   = OpTypeVector %f16 2\n"
16161                 "        %v3f16   = OpTypeVector %f16 3\n"
16162                 "        %v4f16   = OpTypeVector %f16 4\n"
16163                 "        %m2x2f16 = OpTypeMatrix %v2f16 2\n"
16164                 "        %m2x3f16 = OpTypeMatrix %v3f16 2\n"
16165                 "        %m2x4f16 = OpTypeMatrix %v4f16 2\n"
16166                 "        %m3x2f16 = OpTypeMatrix %v2f16 3\n"
16167                 "        %m3x3f16 = OpTypeMatrix %v3f16 3\n"
16168                 "        %m3x4f16 = OpTypeMatrix %v4f16 3\n"
16169                 "        %m4x2f16 = OpTypeMatrix %v2f16 4\n"
16170                 "        %m4x3f16 = OpTypeMatrix %v3f16 4\n"
16171                 "        %m4x4f16 = OpTypeMatrix %v4f16 4\n"
16172
16173                 "     %up_f16     = OpTypePointer Uniform %f16    \n"
16174                 "     %up_v2f16   = OpTypePointer Uniform %v2f16  \n"
16175                 "     %up_v3f16   = OpTypePointer Uniform %v3f16  \n"
16176                 "     %up_v4f16   = OpTypePointer Uniform %v4f16  \n"
16177                 "     %up_m2x2f16 = OpTypePointer Uniform %m2x2f16\n"
16178                 "     %up_m2x3f16 = OpTypePointer Uniform %m2x3f16\n"
16179                 "     %up_m2x4f16 = OpTypePointer Uniform %m2x4f16\n"
16180                 "     %up_m3x2f16 = OpTypePointer Uniform %m3x2f16\n"
16181                 "     %up_m3x3f16 = OpTypePointer Uniform %m3x3f16\n"
16182                 "     %up_m3x4f16 = OpTypePointer Uniform %m3x4f16\n"
16183                 "     %up_m4x2f16 = OpTypePointer Uniform %m4x2f16\n"
16184                 "     %up_m4x3f16 = OpTypePointer Uniform %m4x3f16\n"
16185                 "     %up_m4x4f16 = OpTypePointer Uniform %m4x4f16\n"
16186
16187                 "     %ra_f16     = OpTypeArray %f16     %c_i32_ndp\n"
16188                 "     %ra_v2f16   = OpTypeArray %v2f16   %c_i32_ndp\n"
16189                 "     %ra_v3f16   = OpTypeArray %v3f16   %c_i32_ndp\n"
16190                 "     %ra_v4f16   = OpTypeArray %v4f16   %c_i32_ndp\n"
16191                 "     %ra_m2x2f16 = OpTypeArray %m2x2f16 %c_i32_ndp\n"
16192                 "     %ra_m2x3f16 = OpTypeArray %m2x3f16 %c_i32_ndp\n"
16193                 "     %ra_m2x4f16 = OpTypeArray %m2x4f16 %c_i32_ndp\n"
16194                 "     %ra_m3x2f16 = OpTypeArray %m3x2f16 %c_i32_ndp\n"
16195                 "     %ra_m3x3f16 = OpTypeArray %m3x3f16 %c_i32_ndp\n"
16196                 "     %ra_m3x4f16 = OpTypeArray %m3x4f16 %c_i32_ndp\n"
16197                 "     %ra_m4x2f16 = OpTypeArray %m4x2f16 %c_i32_ndp\n"
16198                 "     %ra_m4x3f16 = OpTypeArray %m4x3f16 %c_i32_ndp\n"
16199                 "     %ra_m4x4f16 = OpTypeArray %m4x4f16 %c_i32_ndp\n"
16200
16201                 "   %SSBO_f16     = OpTypeStruct %ra_f16    \n"
16202                 "   %SSBO_v2f16   = OpTypeStruct %ra_v2f16  \n"
16203                 "   %SSBO_v3f16   = OpTypeStruct %ra_v3f16  \n"
16204                 "   %SSBO_v4f16   = OpTypeStruct %ra_v4f16  \n"
16205                 "   %SSBO_m2x2f16 = OpTypeStruct %ra_m2x2f16\n"
16206                 "   %SSBO_m2x3f16 = OpTypeStruct %ra_m2x3f16\n"
16207                 "   %SSBO_m2x4f16 = OpTypeStruct %ra_m2x4f16\n"
16208                 "   %SSBO_m3x2f16 = OpTypeStruct %ra_m3x2f16\n"
16209                 "   %SSBO_m3x3f16 = OpTypeStruct %ra_m3x3f16\n"
16210                 "   %SSBO_m3x4f16 = OpTypeStruct %ra_m3x4f16\n"
16211                 "   %SSBO_m4x2f16 = OpTypeStruct %ra_m4x2f16\n"
16212                 "   %SSBO_m4x3f16 = OpTypeStruct %ra_m4x3f16\n"
16213                 "   %SSBO_m4x4f16 = OpTypeStruct %ra_m4x4f16\n"
16214
16215                 "%up_SSBO_f16     = OpTypePointer Uniform %SSBO_f16    \n"
16216                 "%up_SSBO_v2f16   = OpTypePointer Uniform %SSBO_v2f16  \n"
16217                 "%up_SSBO_v3f16   = OpTypePointer Uniform %SSBO_v3f16  \n"
16218                 "%up_SSBO_v4f16   = OpTypePointer Uniform %SSBO_v4f16  \n"
16219                 "%up_SSBO_m2x2f16 = OpTypePointer Uniform %SSBO_m2x2f16\n"
16220                 "%up_SSBO_m2x3f16 = OpTypePointer Uniform %SSBO_m2x3f16\n"
16221                 "%up_SSBO_m2x4f16 = OpTypePointer Uniform %SSBO_m2x4f16\n"
16222                 "%up_SSBO_m3x2f16 = OpTypePointer Uniform %SSBO_m3x2f16\n"
16223                 "%up_SSBO_m3x3f16 = OpTypePointer Uniform %SSBO_m3x3f16\n"
16224                 "%up_SSBO_m3x4f16 = OpTypePointer Uniform %SSBO_m3x4f16\n"
16225                 "%up_SSBO_m4x2f16 = OpTypePointer Uniform %SSBO_m4x2f16\n"
16226                 "%up_SSBO_m4x3f16 = OpTypePointer Uniform %SSBO_m4x3f16\n"
16227                 "%up_SSBO_m4x4f16 = OpTypePointer Uniform %SSBO_m4x4f16\n"
16228
16229                 "       %fp_v2i32 = OpTypePointer Function %v2i32\n"
16230                 "       %fp_v3i32 = OpTypePointer Function %v3i32\n"
16231                 "       %fp_v4i32 = OpTypePointer Function %v4i32\n"
16232                 "${arg_vars}"
16233         );
16234
16235         const StringTemplate decoration
16236         (
16237                 "OpDecorate %ra_f16     ArrayStride 2 \n"
16238                 "OpDecorate %ra_v2f16   ArrayStride 4 \n"
16239                 "OpDecorate %ra_v3f16   ArrayStride 8 \n"
16240                 "OpDecorate %ra_v4f16   ArrayStride 8 \n"
16241                 "OpDecorate %ra_m2x2f16 ArrayStride 8 \n"
16242                 "OpDecorate %ra_m2x3f16 ArrayStride 16\n"
16243                 "OpDecorate %ra_m2x4f16 ArrayStride 16\n"
16244                 "OpDecorate %ra_m3x2f16 ArrayStride 16\n"
16245                 "OpDecorate %ra_m3x3f16 ArrayStride 32\n"
16246                 "OpDecorate %ra_m3x4f16 ArrayStride 32\n"
16247                 "OpDecorate %ra_m4x2f16 ArrayStride 16\n"
16248                 "OpDecorate %ra_m4x3f16 ArrayStride 32\n"
16249                 "OpDecorate %ra_m4x4f16 ArrayStride 32\n"
16250
16251                 "OpMemberDecorate %SSBO_f16     0 Offset 0\n"
16252                 "OpMemberDecorate %SSBO_v2f16   0 Offset 0\n"
16253                 "OpMemberDecorate %SSBO_v3f16   0 Offset 0\n"
16254                 "OpMemberDecorate %SSBO_v4f16   0 Offset 0\n"
16255                 "OpMemberDecorate %SSBO_m2x2f16 0 Offset 0\n"
16256                 "OpMemberDecorate %SSBO_m2x3f16 0 Offset 0\n"
16257                 "OpMemberDecorate %SSBO_m2x4f16 0 Offset 0\n"
16258                 "OpMemberDecorate %SSBO_m3x2f16 0 Offset 0\n"
16259                 "OpMemberDecorate %SSBO_m3x3f16 0 Offset 0\n"
16260                 "OpMemberDecorate %SSBO_m3x4f16 0 Offset 0\n"
16261                 "OpMemberDecorate %SSBO_m4x2f16 0 Offset 0\n"
16262                 "OpMemberDecorate %SSBO_m4x3f16 0 Offset 0\n"
16263                 "OpMemberDecorate %SSBO_m4x4f16 0 Offset 0\n"
16264
16265                 "OpDecorate %SSBO_f16     BufferBlock\n"
16266                 "OpDecorate %SSBO_v2f16   BufferBlock\n"
16267                 "OpDecorate %SSBO_v3f16   BufferBlock\n"
16268                 "OpDecorate %SSBO_v4f16   BufferBlock\n"
16269                 "OpDecorate %SSBO_m2x2f16 BufferBlock\n"
16270                 "OpDecorate %SSBO_m2x3f16 BufferBlock\n"
16271                 "OpDecorate %SSBO_m2x4f16 BufferBlock\n"
16272                 "OpDecorate %SSBO_m3x2f16 BufferBlock\n"
16273                 "OpDecorate %SSBO_m3x3f16 BufferBlock\n"
16274                 "OpDecorate %SSBO_m3x4f16 BufferBlock\n"
16275                 "OpDecorate %SSBO_m4x2f16 BufferBlock\n"
16276                 "OpDecorate %SSBO_m4x3f16 BufferBlock\n"
16277                 "OpDecorate %SSBO_m4x4f16 BufferBlock\n"
16278
16279                 "OpMemberDecorate %SSBO_m2x2f16 0 ColMajor\n"
16280                 "OpMemberDecorate %SSBO_m2x3f16 0 ColMajor\n"
16281                 "OpMemberDecorate %SSBO_m2x4f16 0 ColMajor\n"
16282                 "OpMemberDecorate %SSBO_m3x2f16 0 ColMajor\n"
16283                 "OpMemberDecorate %SSBO_m3x3f16 0 ColMajor\n"
16284                 "OpMemberDecorate %SSBO_m3x4f16 0 ColMajor\n"
16285                 "OpMemberDecorate %SSBO_m4x2f16 0 ColMajor\n"
16286                 "OpMemberDecorate %SSBO_m4x3f16 0 ColMajor\n"
16287                 "OpMemberDecorate %SSBO_m4x4f16 0 ColMajor\n"
16288
16289                 "OpMemberDecorate %SSBO_m2x2f16 0 MatrixStride 4\n"
16290                 "OpMemberDecorate %SSBO_m2x3f16 0 MatrixStride 8\n"
16291                 "OpMemberDecorate %SSBO_m2x4f16 0 MatrixStride 8\n"
16292                 "OpMemberDecorate %SSBO_m3x2f16 0 MatrixStride 4\n"
16293                 "OpMemberDecorate %SSBO_m3x3f16 0 MatrixStride 8\n"
16294                 "OpMemberDecorate %SSBO_m3x4f16 0 MatrixStride 8\n"
16295                 "OpMemberDecorate %SSBO_m4x2f16 0 MatrixStride 4\n"
16296                 "OpMemberDecorate %SSBO_m4x3f16 0 MatrixStride 8\n"
16297                 "OpMemberDecorate %SSBO_m4x4f16 0 MatrixStride 8\n"
16298
16299                 "${arg_decorations}"
16300         );
16301
16302         const StringTemplate testFun
16303         (
16304                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
16305                 "    %param = OpFunctionParameter %v4f32\n"
16306                 "    %entry = OpLabel\n"
16307
16308                 "        %i = OpVariable %fp_i32 Function\n"
16309                 "${arg_infunc_vars}"
16310                 "             OpStore %i %c_i32_0\n"
16311                 "             OpBranch %loop\n"
16312
16313                 "     %loop = OpLabel\n"
16314                 "    %i_cmp = OpLoad %i32 %i\n"
16315                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
16316                 "             OpLoopMerge %merge %next None\n"
16317                 "             OpBranchConditional %lt %write %merge\n"
16318
16319                 "    %write = OpLabel\n"
16320                 "      %ndx = OpLoad %i32 %i\n"
16321
16322                 "${arg_func_call}"
16323
16324                 "             OpBranch %next\n"
16325
16326                 "     %next = OpLabel\n"
16327                 "    %i_cur = OpLoad %i32 %i\n"
16328                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
16329                 "             OpStore %i %i_new\n"
16330                 "             OpBranch %loop\n"
16331
16332                 "    %merge = OpLabel\n"
16333                 "             OpReturnValue %param\n"
16334                 "             OpFunctionEnd\n"
16335         );
16336
16337         const Math16ArgFragments        argFragment1    =
16338         {
16339                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16340                 " %val_src0 = OpLoad %${t0} %src0\n"
16341                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0\n"
16342                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16343                 "             OpStore %dst %val_dst\n",
16344                 "",
16345                 "",
16346                 "",
16347         };
16348
16349         const Math16ArgFragments        argFragment2    =
16350         {
16351                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16352                 " %val_src0 = OpLoad %${t0} %src0\n"
16353                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16354                 " %val_src1 = OpLoad %${t1} %src1\n"
16355                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1\n"
16356                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16357                 "             OpStore %dst %val_dst\n",
16358                 "",
16359                 "",
16360                 "",
16361         };
16362
16363         const Math16ArgFragments        argFragment3    =
16364         {
16365                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16366                 " %val_src0 = OpLoad %${t0} %src0\n"
16367                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16368                 " %val_src1 = OpLoad %${t1} %src1\n"
16369                 "     %src2 = OpAccessChain %up_${t2} %ssbo_src2 %c_i32_0 %ndx\n"
16370                 " %val_src2 = OpLoad %${t2} %src2\n"
16371                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1 %val_src2\n"
16372                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16373                 "             OpStore %dst %val_dst\n",
16374                 "",
16375                 "",
16376                 "",
16377         };
16378
16379         const Math16ArgFragments        argFragmentLdExp        =
16380         {
16381                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16382                 " %val_src0 = OpLoad %${t0} %src0\n"
16383                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16384                 " %val_src1 = OpLoad %${t1} %src1\n"
16385                 "%val_src1i = OpConvertFToS %${dr}i32 %val_src1\n"
16386                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1i\n"
16387                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16388                 "             OpStore %dst %val_dst\n",
16389
16390                 "",
16391
16392                 "",
16393
16394                 "",
16395         };
16396
16397         const Math16ArgFragments        argFragmentModfFrac     =
16398         {
16399                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16400                 " %val_src0 = OpLoad %${t0} %src0\n"
16401                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16402                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16403                 "             OpStore %dst %val_dst\n",
16404
16405                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16406
16407                 "",
16408
16409                 "      %tmp = OpVariable %fp_tmp Function\n",
16410         };
16411
16412         const Math16ArgFragments        argFragmentModfInt      =
16413         {
16414                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16415                 " %val_src0 = OpLoad %${t0} %src0\n"
16416                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16417                 "     %tmp0 = OpAccessChain %fp_tmp %tmp\n"
16418                 "  %val_dst = OpLoad %${tr} %tmp0\n"
16419                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16420                 "             OpStore %dst %val_dst\n",
16421
16422                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16423
16424                 "",
16425
16426                 "      %tmp = OpVariable %fp_tmp Function\n",
16427         };
16428
16429         const Math16ArgFragments        argFragmentModfStruct   =
16430         {
16431                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16432                 " %val_src0 = OpLoad %${t0} %src0\n"
16433                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16434                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16435                 "             OpStore %tmp_ptr_s %val_tmp\n"
16436                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_${struct_member}\n"
16437                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16438                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16439                 "             OpStore %dst %val_dst\n",
16440
16441                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16442                 "   %st_tmp = OpTypeStruct %${tr} %${tr}\n"
16443                 "   %fp_tmp = OpTypePointer Function %st_tmp\n"
16444                 "   %c_frac = OpConstant %i32 0\n"
16445                 "    %c_int = OpConstant %i32 1\n",
16446
16447                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16448                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16449
16450                 "      %tmp = OpVariable %fp_tmp Function\n",
16451         };
16452
16453         const Math16ArgFragments        argFragmentFrexpStructS =
16454         {
16455                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16456                 " %val_src0 = OpLoad %${t0} %src0\n"
16457                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16458                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16459                 "             OpStore %tmp_ptr_s %val_tmp\n"
16460                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_i32_0\n"
16461                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16462                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16463                 "             OpStore %dst %val_dst\n",
16464
16465                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16466                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16467                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16468
16469                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16470                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16471
16472                 "      %tmp = OpVariable %fp_tmp Function\n",
16473         };
16474
16475         const Math16ArgFragments        argFragmentFrexpStructE =
16476         {
16477                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16478                 " %val_src0 = OpLoad %${t0} %src0\n"
16479                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16480                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16481                 "             OpStore %tmp_ptr_s %val_tmp\n"
16482                 "%tmp_ptr_l = OpAccessChain %fp_${dr}i32 %tmp %c_i32_1\n"
16483                 "%val_dst_i = OpLoad %${dr}i32 %tmp_ptr_l\n"
16484                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16485                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16486                 "             OpStore %dst %val_dst\n",
16487
16488                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16489                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16490
16491                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16492                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16493
16494                 "      %tmp = OpVariable %fp_tmp Function\n",
16495         };
16496
16497         const Math16ArgFragments        argFragmentFrexpS               =
16498         {
16499                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16500                 " %val_src0 = OpLoad %${t0} %src0\n"
16501                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16502                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16503                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16504                 "             OpStore %dst %val_dst\n",
16505
16506                 "",
16507
16508                 "",
16509
16510                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16511         };
16512
16513         const Math16ArgFragments        argFragmentFrexpE               =
16514         {
16515                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16516                 " %val_src0 = OpLoad %${t0} %src0\n"
16517                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16518                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16519                 "%val_dst_i = OpLoad %${dr}i32 %out_exp\n"
16520                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16521                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16522                 "             OpStore %dst %val_dst\n",
16523
16524                 "",
16525
16526                 "",
16527
16528                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16529         };
16530
16531         const Math16TestType&           testType                                = testTypes[testTypeIdx];
16532         const string                            funcNameString                  = string(testFunc.funcName) + string(testFunc.funcSuffix);
16533         const string                            testName                                = de::toLower(funcNameString);
16534         const Math16ArgFragments*       argFragments                    = DE_NULL;
16535         const size_t                            typeStructStride                = testType.typeStructStride;
16536         const bool                                      extInst                                 = !(testFunc.funcName[0] == 'O' && testFunc.funcName[1] == 'p');
16537         const size_t                            numFloatsPerArg0Type    = testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16);
16538         const size_t                            iterations                              = numDataPoints / numFloatsPerArg0Type;
16539         const size_t                            numFloatsPerResultType  = testTypes[testFunc.typeResult].typeArrayStride / sizeof(deFloat16);
16540         const vector<deFloat16>         float16DummyOutput              (iterations * numFloatsPerResultType, 0);
16541         VulkanFeatures                          features;
16542         SpecResource                            specResource;
16543         map<string, string>                     specs;
16544         map<string, string>                     fragments;
16545         vector<string>                          extensions;
16546         string                                          funcCall;
16547         string                                          funcVariables;
16548         string                                          variables;
16549         string                                          declarations;
16550         string                                          decorations;
16551
16552         switch (testFunc.funcArgsCount)
16553         {
16554                 case 1:
16555                 {
16556                         argFragments = &argFragment1;
16557
16558                         if (funcNameString == "ModfFrac")               argFragments = &argFragmentModfFrac;
16559                         if (funcNameString == "ModfInt")                argFragments = &argFragmentModfInt;
16560                         if (funcNameString == "ModfStructFrac") argFragments = &argFragmentModfStruct;
16561                         if (funcNameString == "ModfStructInt")  argFragments = &argFragmentModfStruct;
16562                         if (funcNameString == "FrexpS")                 argFragments = &argFragmentFrexpS;
16563                         if (funcNameString == "FrexpE")                 argFragments = &argFragmentFrexpE;
16564                         if (funcNameString == "FrexpStructS")   argFragments = &argFragmentFrexpStructS;
16565                         if (funcNameString == "FrexpStructE")   argFragments = &argFragmentFrexpStructE;
16566
16567                         break;
16568                 }
16569                 case 2:
16570                 {
16571                         argFragments = &argFragment2;
16572
16573                         if (funcNameString == "Ldexp")                  argFragments = &argFragmentLdExp;
16574
16575                         break;
16576                 }
16577                 case 3:
16578                 {
16579                         argFragments = &argFragment3;
16580
16581                         break;
16582                 }
16583                 default:
16584                 {
16585                         TCU_THROW(InternalError, "Invalid number of arguments");
16586                 }
16587         }
16588
16589         if (testFunc.funcArgsCount == 1)
16590         {
16591                 variables +=
16592                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16593                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16594
16595                 decorations +=
16596                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16597                         "OpDecorate %ssbo_src0 Binding 0\n"
16598                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16599                         "OpDecorate %ssbo_dst Binding 1\n";
16600         }
16601         else if (testFunc.funcArgsCount == 2)
16602         {
16603                 variables +=
16604                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16605                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16606                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16607
16608                 decorations +=
16609                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16610                         "OpDecorate %ssbo_src0 Binding 0\n"
16611                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16612                         "OpDecorate %ssbo_src1 Binding 1\n"
16613                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16614                         "OpDecorate %ssbo_dst Binding 2\n";
16615         }
16616         else if (testFunc.funcArgsCount == 3)
16617         {
16618                 variables +=
16619                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16620                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16621                         " %ssbo_src2 = OpVariable %up_SSBO_${t2} Uniform\n"
16622                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16623
16624                 decorations +=
16625                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16626                         "OpDecorate %ssbo_src0 Binding 0\n"
16627                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16628                         "OpDecorate %ssbo_src1 Binding 1\n"
16629                         "OpDecorate %ssbo_src2 DescriptorSet 0\n"
16630                         "OpDecorate %ssbo_src2 Binding 2\n"
16631                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16632                         "OpDecorate %ssbo_dst Binding 3\n";
16633         }
16634         else
16635         {
16636                 TCU_THROW(InternalError, "Invalid number of function arguments");
16637         }
16638
16639         variables       += argFragments->variables;
16640         decorations     += argFragments->decorations;
16641
16642         specs["dr"]                                     = testTypes[testFunc.typeResult].typePrefix;
16643         specs["d0"]                                     = testTypes[testFunc.typeArg0].typePrefix;
16644         specs["d1"]                                     = testTypes[testFunc.typeArg1].typePrefix;
16645         specs["d2"]                                     = testTypes[testFunc.typeArg2].typePrefix;
16646         specs["tr"]                                     = string(testTypes[testFunc.typeResult].typePrefix) + componentType;
16647         specs["t0"]                                     = string(testTypes[testFunc.typeArg0].typePrefix) + componentType;
16648         specs["t1"]                                     = string(testTypes[testFunc.typeArg1].typePrefix) + componentType;
16649         specs["t2"]                                     = string(testTypes[testFunc.typeArg2].typePrefix) + componentType;
16650         specs["struct_stride"]          = de::toString(typeStructStride);
16651         specs["op"]                                     = extInst ? "OpExtInst" : testFunc.funcName;
16652         specs["ext_inst"]                       = extInst ? string("%ext_import ") + testFunc.funcName : "";
16653         specs["struct_member"]          = de::toLower(testFunc.funcSuffix);
16654
16655         variables                                       = StringTemplate(variables).specialize(specs);
16656         decorations                                     = StringTemplate(decorations).specialize(specs);
16657         funcVariables                           = StringTemplate(argFragments->funcVariables).specialize(specs);
16658         funcCall                                        = StringTemplate(argFragments->bodies).specialize(specs);
16659
16660         specs["num_data_points"]        = de::toString(iterations);
16661         specs["arg_vars"]                       = variables;
16662         specs["arg_decorations"]        = decorations;
16663         specs["arg_infunc_vars"]        = funcVariables;
16664         specs["arg_func_call"]          = funcCall;
16665
16666         fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"\n%ext_import = OpExtInstImport \"GLSL.std.450\"";
16667         fragments["capability"]         = "OpCapability Matrix\nOpCapability StorageUniformBufferBlock16";
16668         fragments["decoration"]         = decoration.specialize(specs);
16669         fragments["pre_main"]           = preMain.specialize(specs);
16670         fragments["testfun"]            = testFun.specialize(specs);
16671
16672         for (size_t inputArgNdx = 0; inputArgNdx < testFunc.funcArgsCount; ++inputArgNdx)
16673         {
16674                 const size_t                    numFloatsPerItem        = (inputArgNdx == 0) ? testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16)
16675                                                                                                         : (inputArgNdx == 1) ? testTypes[testFunc.typeArg1].typeArrayStride / sizeof(deFloat16)
16676                                                                                                         : (inputArgNdx == 2) ? testTypes[testFunc.typeArg2].typeArrayStride / sizeof(deFloat16)
16677                                                                                                         : -1;
16678                 const vector<deFloat16> inputData                       = testFunc.getInputDataFunc(seed, numFloatsPerItem * iterations, testTypeIdx, numFloatsPerItem, testFunc.funcArgsCount, inputArgNdx);
16679
16680                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16681         }
16682
16683         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16DummyOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16684         specResource.verifyIO = testFunc.verifyFunc;
16685
16686         extensions.push_back("VK_KHR_16bit_storage");
16687         extensions.push_back("VK_KHR_shader_float16_int8");
16688
16689         features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
16690         features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
16691
16692         finalizeTestsCreation(specResource, fragments, testCtx, testGroup, testName, features, extensions, IVec3(1, 1, 1));
16693 }
16694
16695 template<size_t C, class SpecResource>
16696 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16697 {
16698         DE_STATIC_ASSERT(C >= 1 && C <= 4);
16699
16700         const std::string                               testGroupName   (string("arithmetic_") + de::toString(C));
16701         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16702         const Math16TestFunc                    testFuncs[]             =
16703         {
16704                 {       "OpFNegate",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16OpFNegate>                                       },
16705                 {       "Round",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Round>                                           },
16706                 {       "RoundEven",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16RoundEven>                                       },
16707                 {       "Trunc",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Trunc>                                           },
16708                 {       "FAbs",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FAbs>                                            },
16709                 {       "FSign",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FSign>                                           },
16710                 {       "Floor",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Floor>                                           },
16711                 {       "Ceil",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Ceil>                                            },
16712                 {       "Fract",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Fract>                                           },
16713                 {       "Radians",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Radians>                                         },
16714                 {       "Degrees",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Degrees>                                         },
16715                 {       "Sin",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sin>                                                     },
16716                 {       "Cos",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cos>                                                     },
16717                 {       "Tan",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tan>                                                     },
16718                 {       "Asin",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asin>                                            },
16719                 {       "Acos",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acos>                                            },
16720                 {       "Atan",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atan>                                            },
16721                 {       "Sinh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sinh>                                            },
16722                 {       "Cosh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cosh>                                            },
16723                 {       "Tanh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tanh>                                            },
16724                 {       "Asinh",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asinh>                                           },
16725                 {       "Acosh",                                "",                     1,      C,              C,              0,              0, &getInputDataAC,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acosh>                                           },
16726                 {       "Atanh",                                "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atanh>                                           },
16727                 {       "Exp",                                  "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp>                                                     },
16728                 {       "Log",                                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log>                                                     },
16729                 {       "Exp2",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp2>                                            },
16730                 {       "Log2",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log2>                                            },
16731                 {       "Sqrt",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sqrt>                                            },
16732                 {       "InverseSqrt",                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16InverseSqrt>                                     },
16733                 {       "Modf",                                 "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16734                 {       "Modf",                                 "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16735                 {       "ModfStruct",                   "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16736                 {       "ModfStruct",                   "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16737                 {       "Frexp",                                "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16738                 {       "Frexp",                                "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16739                 {       "FrexpStruct",                  "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16740                 {       "FrexpStruct",                  "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16741                 {       "OpFAdd",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFAdd>                                          },
16742                 {       "OpFSub",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFSub>                                          },
16743                 {       "OpFMul",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFMul>                                          },
16744                 {       "OpFDiv",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFDiv>                                          },
16745                 {       "Atan2",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Atan2>                                           },
16746                 {       "Pow",                                  "",                     2,      C,              C,              C,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Pow>                                                     },
16747                 {       "FMin",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMin>                                            },
16748                 {       "FMax",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMax>                                            },
16749                 {       "Step",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Step>                                            },
16750                 {       "Ldexp",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Ldexp>                                           },
16751                 {       "FClamp",                               "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FClamp>                                          },
16752                 {       "FMix",                                 "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FMix>                                            },
16753                 {       "SmoothStep",                   "",                     3,      C,              C,              C,              C, &getInputDataSS,     compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16SmoothStep>                                      },
16754                 {       "Fma",                                  "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16Fma>                                                     },
16755                 {       "Length",                               "",                     1,      1,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  0,  0, fp16Length>                                          },
16756                 {       "Distance",                             "",                     2,      1,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Distance>                                        },
16757                 {       "Cross",                                "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Cross>                                           },
16758                 {       "Normalize",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Normalize>                                       },
16759                 {       "FaceForward",                  "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FaceForward>                                     },
16760                 {       "Reflect",                              "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Reflect>                                         },
16761                 {       "Refract",                              "",                     3,      C,              C,              C,              1, &getInputDataN,      compareFP16ArithmeticFunc<  C,  C,  C,  1, fp16Refract>                                         },
16762                 {       "OpDot",                                "",                     2,      1,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Dot>                                                     },
16763                 {       "OpVectorTimesScalar",  "",                     2,      C,              C,              1,              0, &getInputDataV,      compareFP16ArithmeticFunc<  C,  C,  1,  0, fp16VectorTimesScalar>                       },
16764         };
16765
16766         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16767         {
16768                 const Math16TestFunc&   testFunc                = testFuncs[testFuncIdx];
16769                 const string                    funcNameString  = testFunc.funcName;
16770
16771                 if ((C != 3) && funcNameString == "Cross")
16772                         continue;
16773
16774                 if ((C < 2) && funcNameString == "OpDot")
16775                         continue;
16776
16777                 if ((C < 2) && funcNameString == "OpVectorTimesScalar")
16778                         continue;
16779
16780                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), C, testFunc);
16781         }
16782
16783         return testGroup.release();
16784 }
16785
16786 template<class SpecResource>
16787 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16788 {
16789         const std::string                               testGroupName   ("arithmetic");
16790         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16791         const Math16TestFunc                    testFuncs[]             =
16792         {
16793                 {       "OpTranspose",                  "2x2",          1,      MAT2X2, MAT2X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Transpose<2,2> >                         },
16794                 {       "OpTranspose",                  "3x2",          1,      MAT2X3, MAT3X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<3,2> >                         },
16795                 {       "OpTranspose",                  "4x2",          1,      MAT2X4, MAT4X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<4,2> >                         },
16796                 {       "OpTranspose",                  "2x3",          1,      MAT3X2, MAT2X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,3> >                         },
16797                 {       "OpTranspose",                  "3x3",          1,      MAT3X3, MAT3X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,3> >                         },
16798                 {       "OpTranspose",                  "4x3",          1,      MAT3X4, MAT4X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,3> >                         },
16799                 {       "OpTranspose",                  "2x4",          1,      MAT4X2, MAT2X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,4> >                         },
16800                 {       "OpTranspose",                  "3x4",          1,      MAT4X3, MAT3X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,4> >                         },
16801                 {       "OpTranspose",                  "4x4",          1,      MAT4X4, MAT4X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,4> >                         },
16802                 {       "OpMatrixTimesScalar",  "2x2",          2,      MAT2X2, MAT2X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  1,  0, fp16MatrixTimesScalar<2,2> >         },
16803                 {       "OpMatrixTimesScalar",  "2x3",          2,      MAT2X3, MAT2X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,3> >         },
16804                 {       "OpMatrixTimesScalar",  "2x4",          2,      MAT2X4, MAT2X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,4> >         },
16805                 {       "OpMatrixTimesScalar",  "3x2",          2,      MAT3X2, MAT3X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<3,2> >         },
16806                 {       "OpMatrixTimesScalar",  "3x3",          2,      MAT3X3, MAT3X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,3> >         },
16807                 {       "OpMatrixTimesScalar",  "3x4",          2,      MAT3X4, MAT3X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,4> >         },
16808                 {       "OpMatrixTimesScalar",  "4x2",          2,      MAT4X2, MAT4X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<4,2> >         },
16809                 {       "OpMatrixTimesScalar",  "4x3",          2,      MAT4X3, MAT4X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,3> >         },
16810                 {       "OpMatrixTimesScalar",  "4x4",          2,      MAT4X4, MAT4X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,4> >         },
16811                 {       "OpVectorTimesMatrix",  "2x2",          2,      VEC2,   VEC2,   MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  2,  4,  0, fp16VectorTimesMatrix<2,2> >         },
16812                 {       "OpVectorTimesMatrix",  "2x3",          2,      VEC2,   VEC3,   MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  3,  8,  0, fp16VectorTimesMatrix<2,3> >         },
16813                 {       "OpVectorTimesMatrix",  "2x4",          2,      VEC2,   VEC4,   MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  8,  0, fp16VectorTimesMatrix<2,4> >         },
16814                 {       "OpVectorTimesMatrix",  "3x2",          2,      VEC3,   VEC2,   MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  2,  8,  0, fp16VectorTimesMatrix<3,2> >         },
16815                 {       "OpVectorTimesMatrix",  "3x3",          2,      VEC3,   VEC3,   MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  3, 16,  0, fp16VectorTimesMatrix<3,3> >         },
16816                 {       "OpVectorTimesMatrix",  "3x4",          2,      VEC3,   VEC4,   MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  4, 16,  0, fp16VectorTimesMatrix<3,4> >         },
16817                 {       "OpVectorTimesMatrix",  "4x2",          2,      VEC4,   VEC2,   MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  8,  0, fp16VectorTimesMatrix<4,2> >         },
16818                 {       "OpVectorTimesMatrix",  "4x3",          2,      VEC4,   VEC3,   MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  3, 16,  0, fp16VectorTimesMatrix<4,3> >         },
16819                 {       "OpVectorTimesMatrix",  "4x4",          2,      VEC4,   VEC4,   MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4, 16,  0, fp16VectorTimesMatrix<4,4> >         },
16820                 {       "OpMatrixTimesVector",  "2x2",          2,      VEC2,   MAT2X2, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  2,  0, fp16MatrixTimesVector<2,2> >         },
16821                 {       "OpMatrixTimesVector",  "2x3",          2,      VEC3,   MAT2X3, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  8,  2,  0, fp16MatrixTimesVector<2,3> >         },
16822                 {       "OpMatrixTimesVector",  "2x4",          2,      VEC4,   MAT2X4, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  2,  0, fp16MatrixTimesVector<2,4> >         },
16823                 {       "OpMatrixTimesVector",  "3x2",          2,      VEC2,   MAT3X2, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  3,  0, fp16MatrixTimesVector<3,2> >         },
16824                 {       "OpMatrixTimesVector",  "3x3",          2,      VEC3,   MAT3X3, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  3,  0, fp16MatrixTimesVector<3,3> >         },
16825                 {       "OpMatrixTimesVector",  "3x4",          2,      VEC4,   MAT3X4, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  3,  0, fp16MatrixTimesVector<3,4> >         },
16826                 {       "OpMatrixTimesVector",  "4x2",          2,      VEC2,   MAT4X2, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  4,  0, fp16MatrixTimesVector<4,2> >         },
16827                 {       "OpMatrixTimesVector",  "4x3",          2,      VEC3,   MAT4X3, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  4,  0, fp16MatrixTimesVector<4,3> >         },
16828                 {       "OpMatrixTimesVector",  "4x4",          2,      VEC4,   MAT4X4, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  4,  0, fp16MatrixTimesVector<4,4> >         },
16829                 {       "OpMatrixTimesMatrix",  "2x2_2x2",      2,      MAT2X2, MAT2X2, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  4,  0, fp16MatrixTimesMatrix<2,2,2,2> >     },
16830                 {       "OpMatrixTimesMatrix",  "2x2_3x2",      2,      MAT3X2, MAT2X2, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,3,2> >     },
16831                 {       "OpMatrixTimesMatrix",  "2x2_4x2",      2,      MAT4X2, MAT2X2, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,4,2> >     },
16832                 {       "OpMatrixTimesMatrix",  "2x3_2x2",      2,      MAT2X3, MAT2X3, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,3,2,2> >     },
16833                 {       "OpMatrixTimesMatrix",  "2x3_3x2",      2,      MAT3X3, MAT2X3, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,3,2> >     },
16834                 {       "OpMatrixTimesMatrix",  "2x3_4x2",      2,      MAT4X3, MAT2X3, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,4,2> >     },
16835                 {       "OpMatrixTimesMatrix",  "2x4_2x2",      2,      MAT2X4, MAT2X4, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,4,2,2> >     },
16836                 {       "OpMatrixTimesMatrix",  "2x4_3x2",      2,      MAT3X4, MAT2X4, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,3,2> >     },
16837                 {       "OpMatrixTimesMatrix",  "2x4_4x2",      2,      MAT4X4, MAT2X4, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,4,2> >     },
16838                 {       "OpMatrixTimesMatrix",  "3x2_2x3",      2,      MAT2X2, MAT3X2, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<3,2,2,3> >     },
16839                 {       "OpMatrixTimesMatrix",  "3x2_3x3",      2,      MAT3X2, MAT3X2, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,3,3> >     },
16840                 {       "OpMatrixTimesMatrix",  "3x2_4x3",      2,      MAT4X2, MAT3X2, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,4,3> >     },
16841                 {       "OpMatrixTimesMatrix",  "3x3_2x3",      2,      MAT2X3, MAT3X3, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,3,2,3> >     },
16842                 {       "OpMatrixTimesMatrix",  "3x3_3x3",      2,      MAT3X3, MAT3X3, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,3,3> >     },
16843                 {       "OpMatrixTimesMatrix",  "3x3_4x3",      2,      MAT4X3, MAT3X3, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,4,3> >     },
16844                 {       "OpMatrixTimesMatrix",  "3x4_2x3",      2,      MAT2X4, MAT3X4, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,4,2,3> >     },
16845                 {       "OpMatrixTimesMatrix",  "3x4_3x3",      2,      MAT3X4, MAT3X4, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,3,3> >     },
16846                 {       "OpMatrixTimesMatrix",  "3x4_4x3",      2,      MAT4X4, MAT3X4, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,4,3> >     },
16847                 {       "OpMatrixTimesMatrix",  "4x2_2x4",      2,      MAT2X2, MAT4X2, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<4,2,2,4> >     },
16848                 {       "OpMatrixTimesMatrix",  "4x2_3x4",      2,      MAT3X2, MAT4X2, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,3,4> >     },
16849                 {       "OpMatrixTimesMatrix",  "4x2_4x4",      2,      MAT4X2, MAT4X2, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,4,4> >     },
16850                 {       "OpMatrixTimesMatrix",  "4x3_2x4",      2,      MAT2X3, MAT4X3, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,3,2,4> >     },
16851                 {       "OpMatrixTimesMatrix",  "4x3_3x4",      2,      MAT3X3, MAT4X3, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,3,4> >     },
16852                 {       "OpMatrixTimesMatrix",  "4x3_4x4",      2,      MAT4X3, MAT4X3, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,4,4> >     },
16853                 {       "OpMatrixTimesMatrix",  "4x4_2x4",      2,      MAT2X4, MAT4X4, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,4,2,4> >     },
16854                 {       "OpMatrixTimesMatrix",  "4x4_3x4",      2,      MAT3X4, MAT4X4, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,3,4> >     },
16855                 {       "OpMatrixTimesMatrix",  "4x4_4x4",      2,      MAT4X4, MAT4X4, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,4,4> >     },
16856                 {       "OpOuterProduct",               "2x2",          2,      MAT2X2, VEC2,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  2,  0, fp16OuterProduct<2,2> >                      },
16857                 {       "OpOuterProduct",               "2x3",          2,      MAT2X3, VEC3,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  3,  2,  0, fp16OuterProduct<2,3> >                      },
16858                 {       "OpOuterProduct",               "2x4",          2,      MAT2X4, VEC4,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  2,  0, fp16OuterProduct<2,4> >                      },
16859                 {       "OpOuterProduct",               "3x2",          2,      MAT3X2, VEC2,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  3,  0, fp16OuterProduct<3,2> >                      },
16860                 {       "OpOuterProduct",               "3x3",          2,      MAT3X3, VEC3,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  3,  0, fp16OuterProduct<3,3> >                      },
16861                 {       "OpOuterProduct",               "3x4",          2,      MAT3X4, VEC4,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  3,  0, fp16OuterProduct<3,4> >                      },
16862                 {       "OpOuterProduct",               "4x2",          2,      MAT4X2, VEC2,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  4,  0, fp16OuterProduct<4,2> >                      },
16863                 {       "OpOuterProduct",               "4x3",          2,      MAT4X3, VEC3,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  4,  0, fp16OuterProduct<4,3> >                      },
16864                 {       "OpOuterProduct",               "4x4",          2,      MAT4X4, VEC4,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  4,  0, fp16OuterProduct<4,4> >                      },
16865                 {       "Determinant",                  "2x2",          1,      SCALAR, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1,  4,  0,  0, fp16Determinant<2> >                         },
16866                 {       "Determinant",                  "3x3",          1,      SCALAR, MAT3X3, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<3> >                         },
16867                 {       "Determinant",                  "4x4",          1,      SCALAR, MAT4X4, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<4> >                         },
16868                 {       "MatrixInverse",                "2x2",          1,      MAT2X2, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Inverse<2> >                                     },
16869         };
16870
16871         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16872         {
16873                 const Math16TestFunc&   testFunc        = testFuncs[testFuncIdx];
16874
16875                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), 0, testFunc);
16876         }
16877
16878         return testGroup.release();
16879 }
16880
16881 const string getNumberTypeName (const NumberType type)
16882 {
16883         if (type == NUMBERTYPE_INT32)
16884         {
16885                 return "int";
16886         }
16887         else if (type == NUMBERTYPE_UINT32)
16888         {
16889                 return "uint";
16890         }
16891         else if (type == NUMBERTYPE_FLOAT32)
16892         {
16893                 return "float";
16894         }
16895         else
16896         {
16897                 DE_ASSERT(false);
16898                 return "";
16899         }
16900 }
16901
16902 deInt32 getInt(de::Random& rnd)
16903 {
16904         return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
16905 }
16906
16907 const string repeatString (const string& str, int times)
16908 {
16909         string filler;
16910         for (int i = 0; i < times; ++i)
16911         {
16912                 filler += str;
16913         }
16914         return filler;
16915 }
16916
16917 const string getRandomConstantString (const NumberType type, de::Random& rnd)
16918 {
16919         if (type == NUMBERTYPE_INT32)
16920         {
16921                 return numberToString<deInt32>(getInt(rnd));
16922         }
16923         else if (type == NUMBERTYPE_UINT32)
16924         {
16925                 return numberToString<deUint32>(rnd.getUint32());
16926         }
16927         else if (type == NUMBERTYPE_FLOAT32)
16928         {
16929                 return numberToString<float>(rnd.getFloat());
16930         }
16931         else
16932         {
16933                 DE_ASSERT(false);
16934                 return "";
16935         }
16936 }
16937
16938 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16939 {
16940         map<string, string> params;
16941
16942         // Vec2 to Vec4
16943         for (int width = 2; width <= 4; ++width)
16944         {
16945                 const string randomConst = numberToString(getInt(rnd));
16946                 const string widthStr = numberToString(width);
16947                 const string composite_type = "${customType}vec" + widthStr;
16948                 const int index = rnd.getInt(0, width-1);
16949
16950                 params["type"]                  = "vec";
16951                 params["name"]                  = params["type"] + "_" + widthStr;
16952                 params["compositeDecl"]         = composite_type + " = OpTypeVector ${customType} " + widthStr +"\n";
16953                 params["compositeType"]         = composite_type;
16954                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16955                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct " + composite_type + repeatString(" %filler", width) + "\n";
16956                 params["indexes"]               = numberToString(index);
16957                 testCases.push_back(params);
16958         }
16959 }
16960
16961 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16962 {
16963         const int limit = 10;
16964         map<string, string> params;
16965
16966         for (int width = 2; width <= limit; ++width)
16967         {
16968                 string randomConst = numberToString(getInt(rnd));
16969                 string widthStr = numberToString(width);
16970                 int index = rnd.getInt(0, width-1);
16971
16972                 params["type"]                  = "array";
16973                 params["name"]                  = params["type"] + "_" + widthStr;
16974                 params["compositeDecl"]         = string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
16975                                                                                         +        "%composite = OpTypeArray ${customType} %arraywidth\n";
16976                 params["compositeType"]         = "%composite";
16977                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16978                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
16979                 params["indexes"]               = numberToString(index);
16980                 testCases.push_back(params);
16981         }
16982 }
16983
16984 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
16985 {
16986         const int limit = 10;
16987         map<string, string> params;
16988
16989         for (int width = 2; width <= limit; ++width)
16990         {
16991                 string randomConst = numberToString(getInt(rnd));
16992                 int index = rnd.getInt(0, width-1);
16993
16994                 params["type"]                  = "struct";
16995                 params["name"]                  = params["type"] + "_" + numberToString(width);
16996                 params["compositeDecl"]         = "%composite = OpTypeStruct" + repeatString(" ${customType}", width) + "\n";
16997                 params["compositeType"]         = "%composite";
16998                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
16999                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
17000                 params["indexes"]               = numberToString(index);
17001                 testCases.push_back(params);
17002         }
17003 }
17004
17005 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17006 {
17007         map<string, string> params;
17008
17009         // Vec2 to Vec4
17010         for (int width = 2; width <= 4; ++width)
17011         {
17012                 string widthStr = numberToString(width);
17013
17014                 for (int column = 2 ; column <= 4; ++column)
17015                 {
17016                         int index_0 = rnd.getInt(0, column-1);
17017                         int index_1 = rnd.getInt(0, width-1);
17018                         string columnStr = numberToString(column);
17019
17020                         params["type"]          = "matrix";
17021                         params["name"]          = params["type"] + "_" + widthStr + "x" + columnStr;
17022                         params["compositeDecl"] = string("%vectype   = OpTypeVector ${customType} " + widthStr + "\n")
17023                                                                                                 +        "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
17024                         params["compositeType"] = "%composite";
17025
17026                         params["filler"]        = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n"
17027                                                                                                 +        "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
17028
17029                         params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
17030                         params["indexes"]       = numberToString(index_0) + " " + numberToString(index_1);
17031                         testCases.push_back(params);
17032                 }
17033         }
17034 }
17035
17036 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17037 {
17038         createVectorCompositeCases(testCases, rnd, type);
17039         createArrayCompositeCases(testCases, rnd, type);
17040         createStructCompositeCases(testCases, rnd, type);
17041         // Matrix only supports float types
17042         if (type == NUMBERTYPE_FLOAT32)
17043         {
17044                 createMatrixCompositeCases(testCases, rnd, type);
17045         }
17046 }
17047
17048 const string getAssemblyTypeDeclaration (const NumberType type)
17049 {
17050         switch (type)
17051         {
17052                 case NUMBERTYPE_INT32:          return "OpTypeInt 32 1";
17053                 case NUMBERTYPE_UINT32:         return "OpTypeInt 32 0";
17054                 case NUMBERTYPE_FLOAT32:        return "OpTypeFloat 32";
17055                 default:                        DE_ASSERT(false); return "";
17056         }
17057 }
17058
17059 const string getAssemblyTypeName (const NumberType type)
17060 {
17061         switch (type)
17062         {
17063                 case NUMBERTYPE_INT32:          return "%i32";
17064                 case NUMBERTYPE_UINT32:         return "%u32";
17065                 case NUMBERTYPE_FLOAT32:        return "%f32";
17066                 default:                        DE_ASSERT(false); return "";
17067         }
17068 }
17069
17070 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
17071 {
17072         map<string, string>     parameters(params);
17073
17074         const string customType = getAssemblyTypeName(type);
17075         map<string, string> substCustomType;
17076         substCustomType["customType"] = customType;
17077         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17078         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17079         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17080         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17081         parameters["customType"] = customType;
17082         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17083
17084         if (parameters.at("compositeType") != "%u32vec3")
17085         {
17086                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17087         }
17088
17089         return StringTemplate(
17090                 "OpCapability Shader\n"
17091                 "OpCapability Matrix\n"
17092                 "OpMemoryModel Logical GLSL450\n"
17093                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17094                 "OpExecutionMode %main LocalSize 1 1 1\n"
17095
17096                 "OpSource GLSL 430\n"
17097                 "OpName %main           \"main\"\n"
17098                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17099
17100                 // Decorators
17101                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17102                 "OpDecorate %buf BufferBlock\n"
17103                 "OpDecorate %indata DescriptorSet 0\n"
17104                 "OpDecorate %indata Binding 0\n"
17105                 "OpDecorate %outdata DescriptorSet 0\n"
17106                 "OpDecorate %outdata Binding 1\n"
17107                 "OpDecorate %customarr ArrayStride 4\n"
17108                 "${compositeDecorator}"
17109                 "OpMemberDecorate %buf 0 Offset 0\n"
17110
17111                 // General types
17112                 "%void      = OpTypeVoid\n"
17113                 "%voidf     = OpTypeFunction %void\n"
17114                 "%u32       = OpTypeInt 32 0\n"
17115                 "%i32       = OpTypeInt 32 1\n"
17116                 "%f32       = OpTypeFloat 32\n"
17117
17118                 // Composite declaration
17119                 "${compositeDecl}"
17120
17121                 // Constants
17122                 "${filler}"
17123
17124                 "${u32vec3Decl:opt}"
17125                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17126
17127                 // Inherited from custom
17128                 "%customptr = OpTypePointer Uniform ${customType}\n"
17129                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17130                 "%buf       = OpTypeStruct %customarr\n"
17131                 "%bufptr    = OpTypePointer Uniform %buf\n"
17132
17133                 "%indata    = OpVariable %bufptr Uniform\n"
17134                 "%outdata   = OpVariable %bufptr Uniform\n"
17135
17136                 "%id        = OpVariable %uvec3ptr Input\n"
17137                 "%zero      = OpConstant %i32 0\n"
17138
17139                 "%main      = OpFunction %void None %voidf\n"
17140                 "%label     = OpLabel\n"
17141                 "%idval     = OpLoad %u32vec3 %id\n"
17142                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17143
17144                 "%inloc     = OpAccessChain %customptr %indata %zero %x\n"
17145                 "%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
17146                 // Read the input value
17147                 "%inval     = OpLoad ${customType} %inloc\n"
17148                 // Create the composite and fill it
17149                 "${compositeConstruct}"
17150                 // Insert the input value to a place
17151                 "%instance2 = OpCompositeInsert ${compositeType} %inval %instance ${indexes}\n"
17152                 // Read back the value from the position
17153                 "%out_val   = OpCompositeExtract ${customType} %instance2 ${indexes}\n"
17154                 // Store it in the output position
17155                 "             OpStore %outloc %out_val\n"
17156                 "             OpReturn\n"
17157                 "             OpFunctionEnd\n"
17158         ).specialize(parameters);
17159 }
17160
17161 template<typename T>
17162 BufferSp createCompositeBuffer(T number)
17163 {
17164         return BufferSp(new Buffer<T>(vector<T>(1, number)));
17165 }
17166
17167 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
17168 {
17169         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
17170         de::Random                                              rnd             (deStringHash(group->getName()));
17171
17172         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17173         {
17174                 NumberType                                              numberType              = NumberType(type);
17175                 const string                                    typeName                = getNumberTypeName(numberType);
17176                 const string                                    description             = "Test the OpCompositeInsert instruction with " + typeName + "s";
17177                 de::MovePtr<tcu::TestCaseGroup> subGroup                (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17178                 vector<map<string, string> >    testCases;
17179
17180                 createCompositeCases(testCases, rnd, numberType);
17181
17182                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17183                 {
17184                         ComputeShaderSpec       spec;
17185
17186                         spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
17187
17188                         switch (numberType)
17189                         {
17190                                 case NUMBERTYPE_INT32:
17191                                 {
17192                                         deInt32 number = getInt(rnd);
17193                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17194                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17195                                         break;
17196                                 }
17197                                 case NUMBERTYPE_UINT32:
17198                                 {
17199                                         deUint32 number = rnd.getUint32();
17200                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17201                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17202                                         break;
17203                                 }
17204                                 case NUMBERTYPE_FLOAT32:
17205                                 {
17206                                         float number = rnd.getFloat();
17207                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17208                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17209                                         break;
17210                                 }
17211                                 default:
17212                                         DE_ASSERT(false);
17213                         }
17214
17215                         spec.numWorkGroups = IVec3(1, 1, 1);
17216                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
17217                 }
17218                 group->addChild(subGroup.release());
17219         }
17220         return group.release();
17221 }
17222
17223 struct AssemblyStructInfo
17224 {
17225         AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
17226         : components    (comp)
17227         , index                 (idx)
17228         {}
17229
17230         deUint32 components;
17231         deUint32 index;
17232 };
17233
17234 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
17235 {
17236         // Create the full index string
17237         string                          fullIndex       = numberToString(structInfo.index) + " " + params.at("indexes");
17238         // Convert it to list of indexes
17239         vector<string>          indexes         = de::splitString(fullIndex, ' ');
17240
17241         map<string, string>     parameters      (params);
17242         parameters["structType"]        = repeatString(" ${compositeType}", structInfo.components);
17243         parameters["structConstruct"]   = repeatString(" %instance", structInfo.components);
17244         parameters["insertIndexes"]     = fullIndex;
17245
17246         // In matrix cases the last two index is the CompositeExtract indexes
17247         const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
17248
17249         // Construct the extractIndex
17250         for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
17251         {
17252                 parameters["extractIndexes"] += " " + *index;
17253         }
17254
17255         // Remove the last 1 or 2 element depends on matrix case or not
17256         indexes.erase(indexes.end() - extractIndexes, indexes.end());
17257
17258         deUint32 id = 0;
17259         // Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
17260         for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
17261         {
17262                 string indexId = "%index_" + numberToString(id++);
17263                 parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
17264                 parameters["accessChainIndexes"] += " " + indexId;
17265         }
17266
17267         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17268
17269         const string customType = getAssemblyTypeName(type);
17270         map<string, string> substCustomType;
17271         substCustomType["customType"] = customType;
17272         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17273         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17274         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17275         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17276         parameters["customType"] = customType;
17277
17278         const string compositeType = parameters.at("compositeType");
17279         map<string, string> substCompositeType;
17280         substCompositeType["compositeType"] = compositeType;
17281         parameters["structType"] = StringTemplate(parameters.at("structType")).specialize(substCompositeType);
17282         if (compositeType != "%u32vec3")
17283         {
17284                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17285         }
17286
17287         return StringTemplate(
17288                 "OpCapability Shader\n"
17289                 "OpCapability Matrix\n"
17290                 "OpMemoryModel Logical GLSL450\n"
17291                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17292                 "OpExecutionMode %main LocalSize 1 1 1\n"
17293
17294                 "OpSource GLSL 430\n"
17295                 "OpName %main           \"main\"\n"
17296                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17297                 // Decorators
17298                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17299                 "OpDecorate %buf BufferBlock\n"
17300                 "OpDecorate %indata DescriptorSet 0\n"
17301                 "OpDecorate %indata Binding 0\n"
17302                 "OpDecorate %outdata DescriptorSet 0\n"
17303                 "OpDecorate %outdata Binding 1\n"
17304                 "OpDecorate %customarr ArrayStride 4\n"
17305                 "${compositeDecorator}"
17306                 "OpMemberDecorate %buf 0 Offset 0\n"
17307                 // General types
17308                 "%void      = OpTypeVoid\n"
17309                 "%voidf     = OpTypeFunction %void\n"
17310                 "%i32       = OpTypeInt 32 1\n"
17311                 "%u32       = OpTypeInt 32 0\n"
17312                 "%f32       = OpTypeFloat 32\n"
17313                 // Custom types
17314                 "${compositeDecl}"
17315                 // %u32vec3 if not already declared in ${compositeDecl}
17316                 "${u32vec3Decl:opt}"
17317                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17318                 // Inherited from composite
17319                 "%composite_p = OpTypePointer Function ${compositeType}\n"
17320                 "%struct_t  = OpTypeStruct${structType}\n"
17321                 "%struct_p  = OpTypePointer Function %struct_t\n"
17322                 // Constants
17323                 "${filler}"
17324                 "${accessChainConstDeclaration}"
17325                 // Inherited from custom
17326                 "%customptr = OpTypePointer Uniform ${customType}\n"
17327                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17328                 "%buf       = OpTypeStruct %customarr\n"
17329                 "%bufptr    = OpTypePointer Uniform %buf\n"
17330                 "%indata    = OpVariable %bufptr Uniform\n"
17331                 "%outdata   = OpVariable %bufptr Uniform\n"
17332
17333                 "%id        = OpVariable %uvec3ptr Input\n"
17334                 "%zero      = OpConstant %u32 0\n"
17335                 "%main      = OpFunction %void None %voidf\n"
17336                 "%label     = OpLabel\n"
17337                 "%struct_v  = OpVariable %struct_p Function\n"
17338                 "%idval     = OpLoad %u32vec3 %id\n"
17339                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17340                 // Create the input/output type
17341                 "%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
17342                 "%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
17343                 // Read the input value
17344                 "%inval     = OpLoad ${customType} %inloc\n"
17345                 // Create the composite and fill it
17346                 "${compositeConstruct}"
17347                 // Create the struct and fill it with the composite
17348                 "%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
17349                 // Insert the value
17350                 "%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
17351                 // Store the object
17352                 "             OpStore %struct_v %comp_obj\n"
17353                 // Get deepest possible composite pointer
17354                 "%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
17355                 "%read_obj  = OpLoad ${compositeType} %inner_ptr\n"
17356                 // Read back the stored value
17357                 "%read_val  = OpCompositeExtract ${customType} %read_obj${extractIndexes}\n"
17358                 "             OpStore %outloc %read_val\n"
17359                 "             OpReturn\n"
17360                 "             OpFunctionEnd\n"
17361         ).specialize(parameters);
17362 }
17363
17364 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
17365 {
17366         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
17367         de::Random                                              rnd                             (deStringHash(group->getName()));
17368
17369         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17370         {
17371                 NumberType                                              numberType      = NumberType(type);
17372                 const string                                    typeName        = getNumberTypeName(numberType);
17373                 const string                                    description     = "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
17374                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17375
17376                 vector<map<string, string> >    testCases;
17377                 createCompositeCases(testCases, rnd, numberType);
17378
17379                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17380                 {
17381                         ComputeShaderSpec       spec;
17382
17383                         // Number of components inside of a struct
17384                         deUint32 structComponents = rnd.getInt(2, 8);
17385                         // Component index value
17386                         deUint32 structIndex = rnd.getInt(0, structComponents - 1);
17387                         AssemblyStructInfo structInfo(structComponents, structIndex);
17388
17389                         spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
17390
17391                         switch (numberType)
17392                         {
17393                                 case NUMBERTYPE_INT32:
17394                                 {
17395                                         deInt32 number = getInt(rnd);
17396                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17397                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17398                                         break;
17399                                 }
17400                                 case NUMBERTYPE_UINT32:
17401                                 {
17402                                         deUint32 number = rnd.getUint32();
17403                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17404                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17405                                         break;
17406                                 }
17407                                 case NUMBERTYPE_FLOAT32:
17408                                 {
17409                                         float number = rnd.getFloat();
17410                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17411                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17412                                         break;
17413                                 }
17414                                 default:
17415                                         DE_ASSERT(false);
17416                         }
17417                         spec.numWorkGroups = IVec3(1, 1, 1);
17418                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
17419                 }
17420                 group->addChild(subGroup.release());
17421         }
17422         return group.release();
17423 }
17424
17425 // If the params missing, uninitialized case
17426 const string specializeDefaultOutputShaderTemplate (const NumberType type, const map<string, string>& params = map<string, string>())
17427 {
17428         map<string, string> parameters(params);
17429
17430         parameters["customType"]        = getAssemblyTypeName(type);
17431
17432         // Declare the const value, and use it in the initializer
17433         if (params.find("constValue") != params.end())
17434         {
17435                 parameters["variableInitializer"]       = " %const";
17436         }
17437         // Uninitialized case
17438         else
17439         {
17440                 parameters["commentDecl"]       = ";";
17441         }
17442
17443         return StringTemplate(
17444                 "OpCapability Shader\n"
17445                 "OpMemoryModel Logical GLSL450\n"
17446                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17447                 "OpExecutionMode %main LocalSize 1 1 1\n"
17448                 "OpSource GLSL 430\n"
17449                 "OpName %main           \"main\"\n"
17450                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17451                 // Decorators
17452                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17453                 "OpDecorate %indata DescriptorSet 0\n"
17454                 "OpDecorate %indata Binding 0\n"
17455                 "OpDecorate %outdata DescriptorSet 0\n"
17456                 "OpDecorate %outdata Binding 1\n"
17457                 "OpDecorate %in_arr ArrayStride 4\n"
17458                 "OpDecorate %in_buf BufferBlock\n"
17459                 "OpMemberDecorate %in_buf 0 Offset 0\n"
17460                 // Base types
17461                 "%void       = OpTypeVoid\n"
17462                 "%voidf      = OpTypeFunction %void\n"
17463                 "%u32        = OpTypeInt 32 0\n"
17464                 "%i32        = OpTypeInt 32 1\n"
17465                 "%f32        = OpTypeFloat 32\n"
17466                 "%uvec3      = OpTypeVector %u32 3\n"
17467                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
17468                 "${commentDecl:opt}%const      = OpConstant ${customType} ${constValue:opt}\n"
17469                 // Derived types
17470                 "%in_ptr     = OpTypePointer Uniform ${customType}\n"
17471                 "%in_arr     = OpTypeRuntimeArray ${customType}\n"
17472                 "%in_buf     = OpTypeStruct %in_arr\n"
17473                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
17474                 "%indata     = OpVariable %in_bufptr Uniform\n"
17475                 "%outdata    = OpVariable %in_bufptr Uniform\n"
17476                 "%id         = OpVariable %uvec3ptr Input\n"
17477                 "%var_ptr    = OpTypePointer Function ${customType}\n"
17478                 // Constants
17479                 "%zero       = OpConstant %i32 0\n"
17480                 // Main function
17481                 "%main       = OpFunction %void None %voidf\n"
17482                 "%label      = OpLabel\n"
17483                 "%out_var    = OpVariable %var_ptr Function${variableInitializer:opt}\n"
17484                 "%idval      = OpLoad %uvec3 %id\n"
17485                 "%x          = OpCompositeExtract %u32 %idval 0\n"
17486                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
17487                 "%outloc     = OpAccessChain %in_ptr %outdata %zero %x\n"
17488
17489                 "%outval     = OpLoad ${customType} %out_var\n"
17490                 "              OpStore %outloc %outval\n"
17491                 "              OpReturn\n"
17492                 "              OpFunctionEnd\n"
17493         ).specialize(parameters);
17494 }
17495
17496 bool compareFloats (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
17497 {
17498         DE_ASSERT(outputAllocs.size() != 0);
17499         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17500
17501         // Use custom epsilon because of the float->string conversion
17502         const float     epsilon = 0.00001f;
17503
17504         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17505         {
17506                 vector<deUint8> expectedBytes;
17507                 float                   expected;
17508                 float                   actual;
17509
17510                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17511                 memcpy(&expected, &expectedBytes.front(), expectedBytes.size());
17512                 memcpy(&actual, outputAllocs[outputNdx]->getHostPtr(), expectedBytes.size());
17513
17514                 // Test with epsilon
17515                 if (fabs(expected - actual) > epsilon)
17516                 {
17517                         log << TestLog::Message << "Error: The actual and expected values not matching."
17518                                 << " Expected: " << expected << " Actual: " << actual << " Epsilon: " << epsilon << TestLog::EndMessage;
17519                         return false;
17520                 }
17521         }
17522         return true;
17523 }
17524
17525 // Checks if the driver crash with uninitialized cases
17526 bool passthruVerify (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
17527 {
17528         DE_ASSERT(outputAllocs.size() != 0);
17529         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17530
17531         // Copy and discard the result.
17532         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17533         {
17534                 vector<deUint8> expectedBytes;
17535                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17536
17537                 const size_t    width                   = expectedBytes.size();
17538                 vector<char>    data                    (width);
17539
17540                 memcpy(&data[0], outputAllocs[outputNdx]->getHostPtr(), width);
17541         }
17542         return true;
17543 }
17544
17545 tcu::TestCaseGroup* createShaderDefaultOutputGroup (tcu::TestContext& testCtx)
17546 {
17547         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "shader_default_output", "Test shader default output."));
17548         de::Random                                              rnd             (deStringHash(group->getName()));
17549
17550         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17551         {
17552                 NumberType                                              numberType      = NumberType(type);
17553                 const string                                    typeName        = getNumberTypeName(numberType);
17554                 const string                                    description     = "Test the OpVariable initializer with " + typeName + ".";
17555                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17556
17557                 // 2 similar subcases (initialized and uninitialized)
17558                 for (int subCase = 0; subCase < 2; ++subCase)
17559                 {
17560                         ComputeShaderSpec spec;
17561                         spec.numWorkGroups = IVec3(1, 1, 1);
17562
17563                         map<string, string>                             params;
17564
17565                         switch (numberType)
17566                         {
17567                                 case NUMBERTYPE_INT32:
17568                                 {
17569                                         deInt32 number = getInt(rnd);
17570                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17571                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17572                                         params["constValue"] = numberToString(number);
17573                                         break;
17574                                 }
17575                                 case NUMBERTYPE_UINT32:
17576                                 {
17577                                         deUint32 number = rnd.getUint32();
17578                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17579                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17580                                         params["constValue"] = numberToString(number);
17581                                         break;
17582                                 }
17583                                 case NUMBERTYPE_FLOAT32:
17584                                 {
17585                                         float number = rnd.getFloat();
17586                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17587                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17588                                         spec.verifyIO = &compareFloats;
17589                                         params["constValue"] = numberToString(number);
17590                                         break;
17591                                 }
17592                                 default:
17593                                         DE_ASSERT(false);
17594                         }
17595
17596                         // Initialized subcase
17597                         if (!subCase)
17598                         {
17599                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType, params);
17600                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "initialized", "OpVariable initializer tests.", spec));
17601                         }
17602                         // Uninitialized subcase
17603                         else
17604                         {
17605                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType);
17606                                 spec.verifyIO = &passthruVerify;
17607                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "uninitialized", "OpVariable initializer tests.", spec));
17608                         }
17609                 }
17610                 group->addChild(subGroup.release());
17611         }
17612         return group.release();
17613 }
17614
17615 tcu::TestCaseGroup* createOpNopTests (tcu::TestContext& testCtx)
17616 {
17617         de::MovePtr<tcu::TestCaseGroup> testGroup (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
17618         RGBA                                                    defaultColors[4];
17619         map<string, string>                             opNopFragments;
17620
17621         getDefaultColors(defaultColors);
17622
17623         opNopFragments["testfun"]               =
17624                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17625                 "%param1 = OpFunctionParameter %v4f32\n"
17626                 "%label_testfun = OpLabel\n"
17627                 "OpNop\n"
17628                 "OpNop\n"
17629                 "OpNop\n"
17630                 "OpNop\n"
17631                 "OpNop\n"
17632                 "OpNop\n"
17633                 "OpNop\n"
17634                 "OpNop\n"
17635                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17636                 "%b = OpFAdd %f32 %a %a\n"
17637                 "OpNop\n"
17638                 "%c = OpFSub %f32 %b %a\n"
17639                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17640                 "OpNop\n"
17641                 "OpNop\n"
17642                 "OpReturnValue %ret\n"
17643                 "OpFunctionEnd\n";
17644
17645         createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, testGroup.get());
17646
17647         return testGroup.release();
17648 }
17649
17650 tcu::TestCaseGroup* createOpNameTests (tcu::TestContext& testCtx)
17651 {
17652         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "opname","Test OpName"));
17653         RGBA                                                    defaultColors[4];
17654         map<string, string>                             opNameFragments;
17655
17656         getDefaultColors(defaultColors);
17657
17658         opNameFragments["testfun"] =
17659                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17660                 "%param1     = OpFunctionParameter %v4f32\n"
17661                 "%label_func = OpLabel\n"
17662                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17663                 "%b          = OpFAdd %f32 %a %a\n"
17664                 "%c          = OpFSub %f32 %b %a\n"
17665                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17666                 "OpReturnValue %ret\n"
17667                 "OpFunctionEnd\n";
17668
17669         opNameFragments["debug"] =
17670                 "OpName %BP_main \"not_main\"";
17671
17672         createTestsForAllStages("opname", defaultColors, defaultColors, opNameFragments, testGroup.get());
17673
17674         return testGroup.release();
17675 }
17676
17677 tcu::TestCaseGroup* createFloat16Tests (tcu::TestContext& testCtx)
17678 {
17679         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17680
17681         testGroup->addChild(createOpConstantFloat16Tests(testCtx));
17682         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITH_NAN));
17683         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITHOUT_NAN));
17684         testGroup->addChild(createFloat16FuncSet<GraphicsResources>(testCtx));
17685         testGroup->addChild(createDerivativeTests<256, 1>(testCtx));
17686         testGroup->addChild(createDerivativeTests<256, 2>(testCtx));
17687         testGroup->addChild(createDerivativeTests<256, 4>(testCtx));
17688         testGroup->addChild(createFloat16VectorExtractSet<GraphicsResources>(testCtx));
17689         testGroup->addChild(createFloat16VectorInsertSet<GraphicsResources>(testCtx));
17690         testGroup->addChild(createFloat16VectorShuffleSet<GraphicsResources>(testCtx));
17691         testGroup->addChild(createFloat16CompositeConstructSet<GraphicsResources>(testCtx));
17692         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeExtract"));
17693         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeInsert"));
17694         testGroup->addChild(createFloat16ArithmeticSet<GraphicsResources>(testCtx));
17695         testGroup->addChild(createFloat16ArithmeticSet<1, GraphicsResources>(testCtx));
17696         testGroup->addChild(createFloat16ArithmeticSet<2, GraphicsResources>(testCtx));
17697         testGroup->addChild(createFloat16ArithmeticSet<3, GraphicsResources>(testCtx));
17698         testGroup->addChild(createFloat16ArithmeticSet<4, GraphicsResources>(testCtx));
17699
17700         return testGroup.release();
17701 }
17702
17703 tcu::TestCaseGroup* createFloat16Group (tcu::TestContext& testCtx)
17704 {
17705         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17706
17707         testGroup->addChild(createFloat16OpConstantCompositeGroup(testCtx));
17708         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITH_NAN));
17709         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITHOUT_NAN));
17710         testGroup->addChild(createFloat16FuncSet<ComputeShaderSpec>(testCtx));
17711         testGroup->addChild(createFloat16VectorExtractSet<ComputeShaderSpec>(testCtx));
17712         testGroup->addChild(createFloat16VectorInsertSet<ComputeShaderSpec>(testCtx));
17713         testGroup->addChild(createFloat16VectorShuffleSet<ComputeShaderSpec>(testCtx));
17714         testGroup->addChild(createFloat16CompositeConstructSet<ComputeShaderSpec>(testCtx));
17715         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeExtract"));
17716         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeInsert"));
17717         testGroup->addChild(createFloat16ArithmeticSet<ComputeShaderSpec>(testCtx));
17718         testGroup->addChild(createFloat16ArithmeticSet<1, ComputeShaderSpec>(testCtx));
17719         testGroup->addChild(createFloat16ArithmeticSet<2, ComputeShaderSpec>(testCtx));
17720         testGroup->addChild(createFloat16ArithmeticSet<3, ComputeShaderSpec>(testCtx));
17721         testGroup->addChild(createFloat16ArithmeticSet<4, ComputeShaderSpec>(testCtx));
17722
17723         return testGroup.release();
17724 }
17725
17726 tcu::TestCaseGroup* createBoolMixedBitSizeGroup (tcu::TestContext& testCtx)
17727 {
17728         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "mixed_bitsize", "Tests boolean operands produced from instructions of different bit-sizes"));
17729
17730         de::Random                                              rnd                             (deStringHash(group->getName()));
17731         const int               numElements             = 100;
17732         vector<float>   inputData               (numElements, 0);
17733         vector<float>   outputData              (numElements, 0);
17734         fillRandomScalars(rnd, 0.0f, 100.0f, &inputData[0], 100);
17735
17736         const StringTemplate                    shaderTemplate  (
17737                 "${CAPS}\n"
17738                 "OpMemoryModel Logical GLSL450\n"
17739                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17740                 "OpExecutionMode %main LocalSize 1 1 1\n"
17741                 "OpSource GLSL 430\n"
17742                 "OpName %main           \"main\"\n"
17743                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17744
17745                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17746
17747                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
17748
17749                 "%id        = OpVariable %uvec3ptr Input\n"
17750                 "${CONST}\n"
17751                 "%main      = OpFunction %void None %voidf\n"
17752                 "%label     = OpLabel\n"
17753                 "%idval     = OpLoad %uvec3 %id\n"
17754                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17755                 "%inloc     = OpAccessChain %f32ptr %indata %c0i32 %x\n"
17756
17757                 "${TEST}\n"
17758
17759                 "%outloc    = OpAccessChain %f32ptr %outdata %c0i32 %x\n"
17760                 "             OpStore %outloc %res\n"
17761                 "             OpReturn\n"
17762                 "             OpFunctionEnd\n"
17763         );
17764
17765         // Each test case produces 4 boolean values, and we want each of these values
17766         // to come froma different combination of the available bit-sizes, so compute
17767         // all possible combinations here.
17768         vector<deUint32>        widths;
17769         widths.push_back(32);
17770         widths.push_back(16);
17771         widths.push_back(8);
17772
17773         vector<IVec4>   cases;
17774         for (size_t width0 = 0; width0 < widths.size(); width0++)
17775         {
17776                 for (size_t width1 = 0; width1 < widths.size(); width1++)
17777                 {
17778                         for (size_t width2 = 0; width2 < widths.size(); width2++)
17779                         {
17780                                 for (size_t width3 = 0; width3 < widths.size(); width3++)
17781                                 {
17782                                         cases.push_back(IVec4(widths[width0], widths[width1], widths[width2], widths[width3]));
17783                                 }
17784                         }
17785                 }
17786         }
17787
17788         for (size_t caseNdx = 0; caseNdx < cases.size(); caseNdx++)
17789         {
17790                 /// Skip cases where all bitsizes are the same, we are only interested in testing booleans produced from instructions with different native bit-sizes
17791                 if (cases[caseNdx][0] == cases[caseNdx][1] && cases[caseNdx][0] == cases[caseNdx][2] && cases[caseNdx][0] == cases[caseNdx][3])
17792                         continue;
17793
17794                 map<string, string>     specializations;
17795                 ComputeShaderSpec       spec;
17796
17797                 // Inject appropriate capabilities and reference constants depending
17798                 // on the bit-sizes required by this test case
17799                 bool hasFloat32 = cases[caseNdx][0] == 32 || cases[caseNdx][1] == 32 || cases[caseNdx][2] == 32 || cases[caseNdx][3] == 32;
17800                 bool hasFloat16 = cases[caseNdx][0] == 16 || cases[caseNdx][1] == 16 || cases[caseNdx][2] == 16 || cases[caseNdx][3] == 16;
17801                 bool hasInt8    = cases[caseNdx][0] == 8 || cases[caseNdx][1] == 8 || cases[caseNdx][2] == 8 || cases[caseNdx][3] == 8;
17802
17803                 string capsStr  = "OpCapability Shader\n";
17804                 string constStr =
17805                         "%c0i32     = OpConstant %i32 0\n"
17806                         "%c1f32     = OpConstant %f32 1.0\n"
17807                         "%c0f32     = OpConstant %f32 0.0\n";
17808
17809                 if (hasFloat32)
17810                 {
17811                         constStr        +=
17812                                 "%c10f32    = OpConstant %f32 10.0\n"
17813                                 "%c25f32    = OpConstant %f32 25.0\n"
17814                                 "%c50f32    = OpConstant %f32 50.0\n"
17815                                 "%c90f32    = OpConstant %f32 90.0\n";
17816                 }
17817
17818                 if (hasFloat16)
17819                 {
17820                         capsStr         += "OpCapability Float16\n";
17821                         constStr        +=
17822                                 "%f16       = OpTypeFloat 16\n"
17823                                 "%c10f16    = OpConstant %f16 10.0\n"
17824                                 "%c25f16    = OpConstant %f16 25.0\n"
17825                                 "%c50f16    = OpConstant %f16 50.0\n"
17826                                 "%c90f16    = OpConstant %f16 90.0\n";
17827                 }
17828
17829                 if (hasInt8)
17830                 {
17831                         capsStr         += "OpCapability Int8\n";
17832                         constStr        +=
17833                                 "%i8        = OpTypeInt 8 1\n"
17834                                 "%c10i8     = OpConstant %i8 10\n"
17835                                 "%c25i8     = OpConstant %i8 25\n"
17836                                 "%c50i8     = OpConstant %i8 50\n"
17837                                 "%c90i8     = OpConstant %i8 90\n";
17838                 }
17839
17840                 // Each invocation reads a different float32 value as input. Depending on
17841                 // the bit-sizes required by the particular test case, we also produce
17842                 // float16 and/or and int8 values by converting from the 32-bit float.
17843                 string testStr  = "";
17844                 testStr                 += "%inval32   = OpLoad %f32 %inloc\n";
17845                 if (hasFloat16)
17846                         testStr         += "%inval16   = OpFConvert %f16 %inval32\n";
17847                 if (hasInt8)
17848                         testStr         += "%inval8    = OpConvertFToS %i8 %inval32\n";
17849
17850                 // Because conversions from Float to Int round towards 0 we want our "greater" comparisons to be >=,
17851                 // that way a float32/float16 comparison such as 50.6f >= 50.0f will preserve its result
17852                 // when converted to int8, since FtoS(50.6f) results in 50. For "less" comparisons, it is the
17853                 // other way around, so in this case we want < instead of <=.
17854                 if (cases[caseNdx][0] == 32)
17855                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval32 %c25f32\n";
17856                 else if (cases[caseNdx][0] == 16)
17857                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval16 %c25f16\n";
17858                 else
17859                         testStr         += "%cmp1      = OpSGreaterThanEqual %bool %inval8 %c25i8\n";
17860
17861                 if (cases[caseNdx][1] == 32)
17862                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval32 %c50f32\n";
17863                 else if (cases[caseNdx][1] == 16)
17864                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval16 %c50f16\n";
17865                 else
17866                         testStr         += "%cmp2      = OpSLessThan %bool %inval8 %c50i8\n";
17867
17868                 if (cases[caseNdx][2] == 32)
17869                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval32 %c10f32\n";
17870                 else if (cases[caseNdx][2] == 16)
17871                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval16 %c10f16\n";
17872                 else
17873                         testStr         += "%cmp3      = OpSLessThan %bool %inval8 %c10i8\n";
17874
17875                 if (cases[caseNdx][3] == 32)
17876                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval32 %c90f32\n";
17877                 else if (cases[caseNdx][3] == 16)
17878                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval16 %c90f16\n";
17879                 else
17880                         testStr         += "%cmp4      = OpSGreaterThanEqual %bool %inval8 %c90i8\n";
17881
17882                 testStr                 += "%and1      = OpLogicalAnd %bool %cmp1 %cmp2\n";
17883                 testStr                 += "%or1       = OpLogicalOr %bool %cmp3 %cmp4\n";
17884                 testStr                 += "%or2       = OpLogicalOr %bool %and1 %or1\n";
17885                 testStr                 += "%not1      = OpLogicalNot %bool %or2\n";
17886                 testStr                 += "%res       = OpSelect %f32 %not1 %c1f32 %c0f32\n";
17887
17888                 specializations["CAPS"]         = capsStr;
17889                 specializations["CONST"]        = constStr;
17890                 specializations["TEST"]         = testStr;
17891
17892                 // Compute expected result by evaluating the boolean expression computed in the shader for each input value
17893                 for (size_t ndx = 0; ndx < numElements; ++ndx)
17894                         outputData[ndx] = !((inputData[ndx] >= 25.0f && inputData[ndx] < 50.0f) || (inputData[ndx] < 10.0f || inputData[ndx] >= 90.0f));
17895
17896                 spec.assembly = shaderTemplate.specialize(specializations);
17897                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputData)));
17898                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputData)));
17899                 spec.numWorkGroups = IVec3(numElements, 1, 1);
17900                 if (hasFloat16)
17901                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
17902                 if (hasInt8)
17903                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
17904                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
17905
17906                 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]);
17907                 group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", spec));
17908         }
17909
17910         return group.release();
17911 }
17912
17913 tcu::TestCaseGroup* createBoolGroup (tcu::TestContext& testCtx)
17914 {
17915         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "bool", "Boolean tests"));
17916
17917         testGroup->addChild(createBoolMixedBitSizeGroup(testCtx));
17918
17919         return testGroup.release();
17920 }
17921
17922 tcu::TestCaseGroup* createOpNameAbuseTests (tcu::TestContext& testCtx)
17923 {
17924         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opname_abuse", "OpName abuse tests"));
17925         vector<CaseParameter>                   abuseCases;
17926         RGBA                                                    defaultColors[4];
17927         map<string, string>                             opNameFragments;
17928
17929         getOpNameAbuseCases(abuseCases);
17930         getDefaultColors(defaultColors);
17931
17932         opNameFragments["testfun"] =
17933                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17934                 "%param1     = OpFunctionParameter %v4f32\n"
17935                 "%label_func = OpLabel\n"
17936                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17937                 "%b          = OpFAdd %f32 %a %a\n"
17938                 "%c          = OpFSub %f32 %b %a\n"
17939                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17940                 "OpReturnValue %ret\n"
17941                 "OpFunctionEnd\n";
17942
17943         for (unsigned int i = 0; i < abuseCases.size(); i++)
17944         {
17945                 string casename;
17946                 casename = string("main") + abuseCases[i].name;
17947
17948                 opNameFragments["debug"] =
17949                         "OpName %BP_main \"" + abuseCases[i].param + "\"";
17950
17951                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17952         }
17953
17954         for (unsigned int i = 0; i < abuseCases.size(); i++)
17955         {
17956                 string casename;
17957                 casename = string("b") + abuseCases[i].name;
17958
17959                 opNameFragments["debug"] =
17960                         "OpName %b \"" + abuseCases[i].param + "\"";
17961
17962                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17963         }
17964
17965         {
17966                 opNameFragments["debug"] =
17967                         "OpName %test_code \"name1\"\n"
17968                         "OpName %param1    \"name2\"\n"
17969                         "OpName %a         \"name3\"\n"
17970                         "OpName %b         \"name4\"\n"
17971                         "OpName %c         \"name5\"\n"
17972                         "OpName %ret       \"name6\"\n";
17973
17974                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17975         }
17976
17977         {
17978                 opNameFragments["debug"] =
17979                         "OpName %test_code \"the_same\"\n"
17980                         "OpName %param1    \"the_same\"\n"
17981                         "OpName %a         \"the_same\"\n"
17982                         "OpName %b         \"the_same\"\n"
17983                         "OpName %c         \"the_same\"\n"
17984                         "OpName %ret       \"the_same\"\n";
17985
17986                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17987         }
17988
17989         {
17990                 opNameFragments["debug"] =
17991                         "OpName %BP_main \"to_be\"\n"
17992                         "OpName %BP_main \"or_not\"\n"
17993                         "OpName %BP_main \"to_be\"\n";
17994
17995                 createTestsForAllStages("main_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
17996         }
17997
17998         {
17999                 opNameFragments["debug"] =
18000                         "OpName %b \"to_be\"\n"
18001                         "OpName %b \"or_not\"\n"
18002                         "OpName %b \"to_be\"\n";
18003
18004                 createTestsForAllStages("b_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18005         }
18006
18007         return abuseGroup.release();
18008 }
18009
18010
18011 tcu::TestCaseGroup* createOpMemberNameAbuseTests (tcu::TestContext& testCtx)
18012 {
18013         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opmembername_abuse", "OpName abuse tests"));
18014         vector<CaseParameter>                   abuseCases;
18015         RGBA                                                    defaultColors[4];
18016         map<string, string>                             opMemberNameFragments;
18017
18018         getOpNameAbuseCases(abuseCases);
18019         getDefaultColors(defaultColors);
18020
18021         opMemberNameFragments["pre_main"] =
18022                 "%f3str = OpTypeStruct %f32 %f32 %f32\n";
18023
18024         opMemberNameFragments["testfun"] =
18025                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18026                 "%param1     = OpFunctionParameter %v4f32\n"
18027                 "%label_func = OpLabel\n"
18028                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
18029                 "%b          = OpFAdd %f32 %a %a\n"
18030                 "%c          = OpFSub %f32 %b %a\n"
18031                 "%cstr       = OpCompositeConstruct %f3str %c %c %c\n"
18032                 "%d          = OpCompositeExtract %f32 %cstr 0\n"
18033                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %d %c_i32_0\n"
18034                 "OpReturnValue %ret\n"
18035                 "OpFunctionEnd\n";
18036
18037         for (unsigned int i = 0; i < abuseCases.size(); i++)
18038         {
18039                 string casename;
18040                 casename = string("f3str_x") + abuseCases[i].name;
18041
18042                 opMemberNameFragments["debug"] =
18043                         "OpMemberName %f3str 0 \"" + abuseCases[i].param + "\"";
18044
18045                 createTestsForAllStages(casename, defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18046         }
18047
18048         {
18049                 opMemberNameFragments["debug"] =
18050                         "OpMemberName %f3str 0 \"name1\"\n"
18051                         "OpMemberName %f3str 1 \"name2\"\n"
18052                         "OpMemberName %f3str 2 \"name3\"\n";
18053
18054                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18055         }
18056
18057         {
18058                 opMemberNameFragments["debug"] =
18059                         "OpMemberName %f3str 0 \"the_same\"\n"
18060                         "OpMemberName %f3str 1 \"the_same\"\n"
18061                         "OpMemberName %f3str 2 \"the_same\"\n";
18062
18063                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18064         }
18065
18066         {
18067                 opMemberNameFragments["debug"] =
18068                         "OpMemberName %f3str 0 \"to_be\"\n"
18069                         "OpMemberName %f3str 1 \"or_not\"\n"
18070                         "OpMemberName %f3str 0 \"to_be\"\n"
18071                         "OpMemberName %f3str 2 \"makes_no\"\n"
18072                         "OpMemberName %f3str 0 \"difference\"\n"
18073                         "OpMemberName %f3str 0 \"to_me\"\n";
18074
18075
18076                 createTestsForAllStages("f3str_x_has_multiple_names", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18077         }
18078
18079         return abuseGroup.release();
18080 }
18081
18082 vector<deUint32> getSparseIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18083 {
18084         vector<deUint32>        result;
18085         de::Random                      rnd             (seed);
18086
18087         result.reserve(numDataPoints);
18088
18089         for (deUint32 dataPointNdx = 0; dataPointNdx < numDataPoints; ++dataPointNdx)
18090                 result.push_back(rnd.getUint32());
18091
18092         return result;
18093 }
18094
18095 vector<deUint32> getSparseIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2)
18096 {
18097         vector<deUint32>        result;
18098
18099         result.reserve(inData1.size());
18100
18101         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18102                 result.push_back(inData1[dataPointNdx] + inData2[dataPointNdx]);
18103
18104         return result;
18105 }
18106
18107 template<class SpecResource>
18108 void createSparseIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18109 {
18110         const deUint32                  numDataPoints   = 16;
18111         const std::string               testName                ("sparse_ids");
18112         const deUint32                  seed                    (deStringHash(testName.c_str()));
18113         const vector<deUint32>  inData1                 (getSparseIdsAbuseData(numDataPoints, seed + 1));
18114         const vector<deUint32>  inData2                 (getSparseIdsAbuseData(numDataPoints, seed + 2));
18115         const vector<deUint32>  outData                 (getSparseIdsAbuseResults(inData1, inData2));
18116         const StringTemplate    preMain
18117         (
18118                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18119                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18120                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18121                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18122                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18123                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18124                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18125                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18126         );
18127         const StringTemplate    decoration
18128         (
18129                 "OpDecorate %ra_u32 ArrayStride 4\n"
18130                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18131                 "OpDecorate %SSBO32 BufferBlock\n"
18132                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18133                 "OpDecorate %ssbo_src0 Binding 0\n"
18134                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18135                 "OpDecorate %ssbo_src1 Binding 1\n"
18136                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18137                 "OpDecorate %ssbo_dst Binding 2\n"
18138         );
18139         const StringTemplate    testFun
18140         (
18141                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18142                 "    %param = OpFunctionParameter %v4f32\n"
18143
18144                 "    %entry = OpLabel\n"
18145                 "        %i = OpVariable %fp_i32 Function\n"
18146                 "             OpStore %i %c_i32_0\n"
18147                 "             OpBranch %loop\n"
18148
18149                 "     %loop = OpLabel\n"
18150                 "    %i_cmp = OpLoad %i32 %i\n"
18151                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18152                 "             OpLoopMerge %merge %next None\n"
18153                 "             OpBranchConditional %lt %write %merge\n"
18154
18155                 "    %write = OpLabel\n"
18156                 "      %ndx = OpLoad %i32 %i\n"
18157
18158                 "      %127 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18159                 "      %128 = OpLoad %u32 %127\n"
18160
18161                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18162                 "  %4194000 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18163                 "  %4194001 = OpLoad %u32 %4194000\n"
18164
18165                 "  %2097151 = OpIAdd %u32 %128 %4194001\n"
18166                 "  %2097152 = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18167                 "             OpStore %2097152 %2097151\n"
18168                 "             OpBranch %next\n"
18169
18170                 "     %next = OpLabel\n"
18171                 "    %i_cur = OpLoad %i32 %i\n"
18172                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18173                 "             OpStore %i %i_new\n"
18174                 "             OpBranch %loop\n"
18175
18176                 "    %merge = OpLabel\n"
18177                 "             OpReturnValue %param\n"
18178
18179                 "             OpFunctionEnd\n"
18180         );
18181         SpecResource                    specResource;
18182         map<string, string>             specs;
18183         VulkanFeatures                  features;
18184         map<string, string>             fragments;
18185         vector<string>                  extensions;
18186
18187         specs["num_data_points"]        = de::toString(numDataPoints);
18188
18189         fragments["decoration"]         = decoration.specialize(specs);
18190         fragments["pre_main"]           = preMain.specialize(specs);
18191         fragments["testfun"]            = testFun.specialize(specs);
18192
18193         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18194         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18195         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18196
18197         features.coreFeatures.vertexPipelineStoresAndAtomics    = true;
18198         features.coreFeatures.fragmentStoresAndAtomics                  = true;
18199
18200         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18201 }
18202
18203 vector<deUint32> getLotsIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18204 {
18205         vector<deUint32>        result;
18206         de::Random                      rnd             (seed);
18207
18208         result.reserve(numDataPoints);
18209
18210         // Fixed value
18211         result.push_back(1u);
18212
18213         // Random values
18214         for (deUint32 dataPointNdx = 1; dataPointNdx < numDataPoints; ++dataPointNdx)
18215                 result.push_back(rnd.getUint8());
18216
18217         return result;
18218 }
18219
18220 vector<deUint32> getLotsIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2, const deUint32 count)
18221 {
18222         vector<deUint32>        result;
18223
18224         result.reserve(inData1.size());
18225
18226         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18227                 result.push_back(inData1[dataPointNdx] + count * inData2[dataPointNdx]);
18228
18229         return result;
18230 }
18231
18232 template<class SpecResource>
18233 void createLotsIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18234 {
18235         const deUint32                  numDataPoints   = 16;
18236         const deUint32                  firstNdx                = 100u;
18237         const deUint32                  sequenceCount   = 10000u;
18238         const std::string               testName                ("lots_ids");
18239         const deUint32                  seed                    (deStringHash(testName.c_str()));
18240         const vector<deUint32>  inData1                 (getLotsIdsAbuseData(numDataPoints, seed + 1));
18241         const vector<deUint32>  inData2                 (getLotsIdsAbuseData(numDataPoints, seed + 2));
18242         const vector<deUint32>  outData                 (getLotsIdsAbuseResults(inData1, inData2, sequenceCount));
18243         const StringTemplate preMain
18244         (
18245                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18246                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18247                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18248                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18249                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18250                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18251                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18252                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18253         );
18254         const StringTemplate decoration
18255         (
18256                 "OpDecorate %ra_u32 ArrayStride 4\n"
18257                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18258                 "OpDecorate %SSBO32 BufferBlock\n"
18259                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18260                 "OpDecorate %ssbo_src0 Binding 0\n"
18261                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18262                 "OpDecorate %ssbo_src1 Binding 1\n"
18263                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18264                 "OpDecorate %ssbo_dst Binding 2\n"
18265         );
18266         const StringTemplate testFun
18267         (
18268                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18269                 "    %param = OpFunctionParameter %v4f32\n"
18270
18271                 "    %entry = OpLabel\n"
18272                 "        %i = OpVariable %fp_i32 Function\n"
18273                 "             OpStore %i %c_i32_0\n"
18274                 "             OpBranch %loop\n"
18275
18276                 "     %loop = OpLabel\n"
18277                 "    %i_cmp = OpLoad %i32 %i\n"
18278                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18279                 "             OpLoopMerge %merge %next None\n"
18280                 "             OpBranchConditional %lt %write %merge\n"
18281
18282                 "    %write = OpLabel\n"
18283                 "      %ndx = OpLoad %i32 %i\n"
18284
18285                 "       %90 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18286                 "       %91 = OpLoad %u32 %90\n"
18287
18288                 "       %98 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18289                 "       %${zeroth_id} = OpLoad %u32 %98\n"
18290
18291                 "${seq}\n"
18292
18293                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18294                 "      %dst = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18295                 "             OpStore %dst %${last_id}\n"
18296                 "             OpBranch %next\n"
18297
18298                 "     %next = OpLabel\n"
18299                 "    %i_cur = OpLoad %i32 %i\n"
18300                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18301                 "             OpStore %i %i_new\n"
18302                 "             OpBranch %loop\n"
18303
18304                 "    %merge = OpLabel\n"
18305                 "             OpReturnValue %param\n"
18306
18307                 "             OpFunctionEnd\n"
18308         );
18309         deUint32                                lastId                  = firstNdx;
18310         SpecResource                    specResource;
18311         map<string, string>             specs;
18312         VulkanFeatures                  features;
18313         map<string, string>             fragments;
18314         vector<string>                  extensions;
18315         std::string                             sequence;
18316
18317         for (deUint32 sequenceNdx = 0; sequenceNdx < sequenceCount; ++sequenceNdx)
18318         {
18319                 const deUint32          sequenceId              = sequenceNdx + firstNdx;
18320                 const std::string       sequenceIdStr   = de::toString(sequenceId);
18321
18322                 sequence += "%" + sequenceIdStr + " = OpIAdd %u32 %91 %" + de::toString(sequenceId - 1) + "\n";
18323                 lastId = sequenceId;
18324
18325                 if (sequenceNdx == 0)
18326                         sequence.reserve((10 + sequence.length()) * sequenceCount);
18327         }
18328
18329         specs["num_data_points"]        = de::toString(numDataPoints);
18330         specs["zeroth_id"]                      = de::toString(firstNdx - 1);
18331         specs["last_id"]                        = de::toString(lastId);
18332         specs["seq"]                            = sequence;
18333
18334         fragments["decoration"]         = decoration.specialize(specs);
18335         fragments["pre_main"]           = preMain.specialize(specs);
18336         fragments["testfun"]            = testFun.specialize(specs);
18337
18338         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18339         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18340         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18341
18342         features.coreFeatures.vertexPipelineStoresAndAtomics    = true;
18343         features.coreFeatures.fragmentStoresAndAtomics                  = true;
18344
18345         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18346 }
18347
18348 tcu::TestCaseGroup* createSpirvIdsAbuseTests (tcu::TestContext& testCtx)
18349 {
18350         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18351
18352         createSparseIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18353         createLotsIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18354
18355         return testGroup.release();
18356 }
18357
18358 tcu::TestCaseGroup* createSpirvIdsAbuseGroup (tcu::TestContext& testCtx)
18359 {
18360         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18361
18362         createSparseIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18363         createLotsIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18364
18365         return testGroup.release();
18366 }
18367
18368 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
18369 {
18370         const bool testComputePipeline = true;
18371
18372         de::MovePtr<tcu::TestCaseGroup> instructionTests        (new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
18373         de::MovePtr<tcu::TestCaseGroup> computeTests            (new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
18374         de::MovePtr<tcu::TestCaseGroup> graphicsTests           (new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
18375
18376         computeTests->addChild(createSpivVersionCheckTests(testCtx, testComputePipeline));
18377         computeTests->addChild(createLocalSizeGroup(testCtx));
18378         computeTests->addChild(createOpNopGroup(testCtx));
18379         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITHOUT_NAN));
18380         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITH_NAN));
18381         computeTests->addChild(createOpAtomicGroup(testCtx, false));
18382         computeTests->addChild(createOpAtomicGroup(testCtx, true));                                     // Using new StorageBuffer decoration
18383         computeTests->addChild(createOpAtomicGroup(testCtx, false, 1024, true));        // Return value validation
18384         computeTests->addChild(createOpLineGroup(testCtx));
18385         computeTests->addChild(createOpModuleProcessedGroup(testCtx));
18386         computeTests->addChild(createOpNoLineGroup(testCtx));
18387         computeTests->addChild(createOpConstantNullGroup(testCtx));
18388         computeTests->addChild(createOpConstantCompositeGroup(testCtx));
18389         computeTests->addChild(createOpConstantUsageGroup(testCtx));
18390         computeTests->addChild(createSpecConstantGroup(testCtx));
18391         computeTests->addChild(createOpSourceGroup(testCtx));
18392         computeTests->addChild(createOpSourceExtensionGroup(testCtx));
18393         computeTests->addChild(createDecorationGroupGroup(testCtx));
18394         computeTests->addChild(createOpPhiGroup(testCtx));
18395         computeTests->addChild(createLoopControlGroup(testCtx));
18396         computeTests->addChild(createFunctionControlGroup(testCtx));
18397         computeTests->addChild(createSelectionControlGroup(testCtx));
18398         computeTests->addChild(createBlockOrderGroup(testCtx));
18399         computeTests->addChild(createMultipleShaderGroup(testCtx));
18400         computeTests->addChild(createMemoryAccessGroup(testCtx));
18401         computeTests->addChild(createOpCopyMemoryGroup(testCtx));
18402         computeTests->addChild(createOpCopyObjectGroup(testCtx));
18403         computeTests->addChild(createNoContractionGroup(testCtx));
18404         computeTests->addChild(createOpUndefGroup(testCtx));
18405         computeTests->addChild(createOpUnreachableGroup(testCtx));
18406         computeTests->addChild(createOpQuantizeToF16Group(testCtx));
18407         computeTests->addChild(createOpFRemGroup(testCtx));
18408         computeTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18409         computeTests->addChild(createOpSRemComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18410         computeTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18411         computeTests->addChild(createOpSModComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18412         computeTests->addChild(createConvertComputeTests(testCtx, "OpSConvert", "sconvert"));
18413         computeTests->addChild(createConvertComputeTests(testCtx, "OpUConvert", "uconvert"));
18414         computeTests->addChild(createConvertComputeTests(testCtx, "OpFConvert", "fconvert"));
18415         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertSToF", "convertstof"));
18416         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToS", "convertftos"));
18417         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertUToF", "convertutof"));
18418         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToU", "convertftou"));
18419         computeTests->addChild(createOpCompositeInsertGroup(testCtx));
18420         computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
18421         computeTests->addChild(createShaderDefaultOutputGroup(testCtx));
18422         computeTests->addChild(createOpNMinGroup(testCtx));
18423         computeTests->addChild(createOpNMaxGroup(testCtx));
18424         computeTests->addChild(createOpNClampGroup(testCtx));
18425         {
18426                 de::MovePtr<tcu::TestCaseGroup> computeAndroidTests     (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18427
18428                 computeAndroidTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18429                 computeAndroidTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18430
18431                 computeTests->addChild(computeAndroidTests.release());
18432         }
18433
18434         computeTests->addChild(create8BitStorageComputeGroup(testCtx));
18435         computeTests->addChild(create16BitStorageComputeGroup(testCtx));
18436         computeTests->addChild(createFloatControlsComputeGroup(testCtx));
18437         computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
18438         computeTests->addChild(createCompositeInsertComputeGroup(testCtx));
18439         computeTests->addChild(createVariableInitComputeGroup(testCtx));
18440         computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
18441         computeTests->addChild(createIndexingComputeGroup(testCtx));
18442         computeTests->addChild(createVariablePointersComputeGroup(testCtx));
18443         computeTests->addChild(createPhysicalPointersComputeGroup(testCtx));
18444         computeTests->addChild(createImageSamplerComputeGroup(testCtx));
18445         computeTests->addChild(createOpNameGroup(testCtx));
18446         computeTests->addChild(createOpMemberNameGroup(testCtx));
18447         computeTests->addChild(createPointerParameterComputeGroup(testCtx));
18448         computeTests->addChild(createFloat16Group(testCtx));
18449         computeTests->addChild(createBoolGroup(testCtx));
18450         computeTests->addChild(createWorkgroupMemoryComputeGroup(testCtx));
18451         computeTests->addChild(createSpirvIdsAbuseGroup(testCtx));
18452         computeTests->addChild(createSignedIntCompareGroup(testCtx));
18453
18454         graphicsTests->addChild(createCrossStageInterfaceTests(testCtx));
18455         graphicsTests->addChild(createSpivVersionCheckTests(testCtx, !testComputePipeline));
18456         graphicsTests->addChild(createOpNopTests(testCtx));
18457         graphicsTests->addChild(createOpSourceTests(testCtx));
18458         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
18459         graphicsTests->addChild(createOpModuleProcessedTests(testCtx));
18460         graphicsTests->addChild(createOpLineTests(testCtx));
18461         graphicsTests->addChild(createOpNoLineTests(testCtx));
18462         graphicsTests->addChild(createOpConstantNullTests(testCtx));
18463         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
18464         graphicsTests->addChild(createMemoryAccessTests(testCtx));
18465         graphicsTests->addChild(createOpUndefTests(testCtx));
18466         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
18467         graphicsTests->addChild(createModuleTests(testCtx));
18468         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
18469         graphicsTests->addChild(createOpPhiTests(testCtx));
18470         graphicsTests->addChild(createNoContractionTests(testCtx));
18471         graphicsTests->addChild(createOpQuantizeTests(testCtx));
18472         graphicsTests->addChild(createLoopTests(testCtx));
18473         graphicsTests->addChild(createSpecConstantTests(testCtx));
18474         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
18475         graphicsTests->addChild(createBarrierTests(testCtx));
18476         graphicsTests->addChild(createDecorationGroupTests(testCtx));
18477         graphicsTests->addChild(createFRemTests(testCtx));
18478         graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18479         graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18480
18481         {
18482                 de::MovePtr<tcu::TestCaseGroup> graphicsAndroidTests    (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18483
18484                 graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18485                 graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18486
18487                 graphicsTests->addChild(graphicsAndroidTests.release());
18488         }
18489         graphicsTests->addChild(createOpNameTests(testCtx));
18490         graphicsTests->addChild(createOpNameAbuseTests(testCtx));
18491         graphicsTests->addChild(createOpMemberNameAbuseTests(testCtx));
18492
18493         graphicsTests->addChild(create8BitStorageGraphicsGroup(testCtx));
18494         graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
18495         graphicsTests->addChild(createFloatControlsGraphicsGroup(testCtx));
18496         graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
18497         graphicsTests->addChild(createCompositeInsertGraphicsGroup(testCtx));
18498         graphicsTests->addChild(createVariableInitGraphicsGroup(testCtx));
18499         graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
18500         graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
18501         graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
18502         graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
18503         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpSConvert", "sconvert"));
18504         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpUConvert", "uconvert"));
18505         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpFConvert", "fconvert"));
18506         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertSToF", "convertstof"));
18507         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToS", "convertftos"));
18508         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertUToF", "convertutof"));
18509         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToU", "convertftou"));
18510         graphicsTests->addChild(createPointerParameterGraphicsGroup(testCtx));
18511         graphicsTests->addChild(createVaryingNameGraphicsGroup(testCtx));
18512         graphicsTests->addChild(createFloat16Tests(testCtx));
18513         graphicsTests->addChild(createSpirvIdsAbuseTests(testCtx));
18514
18515         instructionTests->addChild(computeTests.release());
18516         instructionTests->addChild(graphicsTests.release());
18517
18518         return instructionTests.release();
18519 }
18520
18521 } // SpirVAssembly
18522 } // vkt