Fix validation VK_KHR_16bit_storage in opphi test
[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 #include "vktSpvAsmPtrAccessChainTests.hpp"
77
78 #include <cmath>
79 #include <limits>
80 #include <map>
81 #include <string>
82 #include <sstream>
83 #include <utility>
84 #include <stack>
85
86 namespace vkt
87 {
88 namespace SpirVAssembly
89 {
90
91 namespace
92 {
93
94 using namespace vk;
95 using std::map;
96 using std::string;
97 using std::vector;
98 using tcu::IVec3;
99 using tcu::IVec4;
100 using tcu::RGBA;
101 using tcu::TestLog;
102 using tcu::TestStatus;
103 using tcu::Vec4;
104 using de::UniquePtr;
105 using tcu::StringTemplate;
106 using tcu::Vec4;
107
108 const bool TEST_WITH_NAN        = true;
109 const bool TEST_WITHOUT_NAN     = false;
110
111 template<typename T>
112 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, int offset = 0)
113 {
114         T* const typedPtr = (T*)dst;
115         for (int ndx = 0; ndx < numValues; ndx++)
116                 typedPtr[offset + ndx] = de::randomScalar<T>(rnd, minValue, maxValue);
117 }
118
119 // Filter is a function that returns true if a value should pass, false otherwise.
120 template<typename T, typename FilterT>
121 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, FilterT filter, int offset = 0)
122 {
123         T* const typedPtr = (T*)dst;
124         T value;
125         for (int ndx = 0; ndx < numValues; ndx++)
126         {
127                 do
128                         value = de::randomScalar<T>(rnd, minValue, maxValue);
129                 while (!filter(value));
130
131                 typedPtr[offset + ndx] = value;
132         }
133 }
134
135 // Gets a 64-bit integer with a more logarithmic distribution
136 deInt64 randomInt64LogDistributed (de::Random& rnd)
137 {
138         deInt64 val = rnd.getUint64();
139         val &= (1ull << rnd.getInt(1, 63)) - 1;
140         if (rnd.getBool())
141                 val = -val;
142         return val;
143 }
144
145 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues)
146 {
147         for (int ndx = 0; ndx < numValues; ndx++)
148                 dst[ndx] = randomInt64LogDistributed(rnd);
149 }
150
151 template<typename FilterT>
152 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues, FilterT filter)
153 {
154         for (int ndx = 0; ndx < numValues; ndx++)
155         {
156                 deInt64 value;
157                 do {
158                         value = randomInt64LogDistributed(rnd);
159                 } while (!filter(value));
160                 dst[ndx] = value;
161         }
162 }
163
164 inline bool filterNonNegative (const deInt64 value)
165 {
166         return value >= 0;
167 }
168
169 inline bool filterPositive (const deInt64 value)
170 {
171         return value > 0;
172 }
173
174 inline bool filterNotZero (const deInt64 value)
175 {
176         return value != 0;
177 }
178
179 static void floorAll (vector<float>& values)
180 {
181         for (size_t i = 0; i < values.size(); i++)
182                 values[i] = deFloatFloor(values[i]);
183 }
184
185 static void floorAll (vector<Vec4>& values)
186 {
187         for (size_t i = 0; i < values.size(); i++)
188                 values[i] = floor(values[i]);
189 }
190
191 struct CaseParameter
192 {
193         const char*             name;
194         string                  param;
195
196         CaseParameter   (const char* case_, const string& param_) : name(case_), param(param_) {}
197 };
198
199 // Assembly code used for testing LocalSize, OpNop, OpConstant{Null|Composite}, Op[No]Line, OpSource[Continued], OpSourceExtension, OpUndef is based on GLSL source code:
200 //
201 // #version 430
202 //
203 // layout(std140, set = 0, binding = 0) readonly buffer Input {
204 //   float elements[];
205 // } input_data;
206 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
207 //   float elements[];
208 // } output_data;
209 //
210 // layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
211 //
212 // void main() {
213 //   uint x = gl_GlobalInvocationID.x;
214 //   output_data.elements[x] = -input_data.elements[x];
215 // }
216
217 static string getAsmForLocalSizeTest(bool useLiteralLocalSize, bool useSpecConstantWorkgroupSize, IVec3 workGroupSize, deUint32 ndx)
218 {
219         std::ostringstream out;
220         out << getComputeAsmShaderPreambleWithoutLocalSize();
221
222         if (useLiteralLocalSize)
223         {
224                 out << "OpExecutionMode %main LocalSize "
225                         << workGroupSize.x() << " " << workGroupSize.y() << " " << workGroupSize.z() << "\n";
226         }
227
228         out << "OpSource GLSL 430\n"
229                 "OpName %main           \"main\"\n"
230                 "OpName %id             \"gl_GlobalInvocationID\"\n"
231                 "OpDecorate %id BuiltIn GlobalInvocationId\n";
232
233         if (useSpecConstantWorkgroupSize)
234         {
235                 out << "OpDecorate %spec_0 SpecId 100\n"
236                         << "OpDecorate %spec_1 SpecId 101\n"
237                         << "OpDecorate %spec_2 SpecId 102\n"
238                         << "OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize\n";
239         }
240
241         out << getComputeAsmInputOutputBufferTraits()
242                 << getComputeAsmCommonTypes()
243                 << getComputeAsmInputOutputBuffer()
244                 << "%id        = OpVariable %uvec3ptr Input\n"
245                 << "%zero      = OpConstant %i32 0 \n";
246
247         if (useSpecConstantWorkgroupSize)
248         {
249                 out     << "%spec_0   = OpSpecConstant %u32 "<< workGroupSize.x() << "\n"
250                         << "%spec_1   = OpSpecConstant %u32 "<< workGroupSize.y() << "\n"
251                         << "%spec_2   = OpSpecConstant %u32 "<< workGroupSize.z() << "\n"
252                         << "%gl_WorkGroupSize = OpSpecConstantComposite %uvec3 %spec_0 %spec_1 %spec_2\n";
253         }
254
255         out << "%main      = OpFunction %void None %voidf\n"
256                 << "%label     = OpLabel\n"
257                 << "%idval     = OpLoad %uvec3 %id\n"
258                 << "%ndx         = OpCompositeExtract %u32 %idval " << ndx << "\n"
259
260                         "%inloc     = OpAccessChain %f32ptr %indata %zero %ndx\n"
261                         "%inval     = OpLoad %f32 %inloc\n"
262                         "%neg       = OpFNegate %f32 %inval\n"
263                         "%outloc    = OpAccessChain %f32ptr %outdata %zero %ndx\n"
264                         "             OpStore %outloc %neg\n"
265                         "             OpReturn\n"
266                         "             OpFunctionEnd\n";
267         return out.str();
268 }
269
270 tcu::TestCaseGroup* createLocalSizeGroup (tcu::TestContext& testCtx)
271 {
272         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "localsize", ""));
273         ComputeShaderSpec                               spec;
274         de::Random                                              rnd                             (deStringHash(group->getName()));
275         const deUint32                                  numElements             = 64u;
276         vector<float>                                   positiveFloats  (numElements, 0);
277         vector<float>                                   negativeFloats  (numElements, 0);
278
279         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
280
281         for (size_t ndx = 0; ndx < numElements; ++ndx)
282                 negativeFloats[ndx] = -positiveFloats[ndx];
283
284         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
285         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
286
287         spec.numWorkGroups = IVec3(numElements, 1, 1);
288
289         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, 1), 0u);
290         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize", "", spec));
291
292         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, 1), 0u);
293         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize", "", spec));
294
295         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, 1), 0u);
296         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize", "", spec));
297
298         spec.numWorkGroups = IVec3(1, 1, 1);
299
300         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(numElements, 1, 1), 0u);
301         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_x", "", spec));
302
303         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(numElements, 1, 1), 0u);
304         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_x", "", spec));
305
306         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(numElements, 1, 1), 0u);
307         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_x", "", spec));
308
309         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, numElements, 1), 1u);
310         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_y", "", spec));
311
312         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, numElements, 1), 1u);
313         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_y", "", spec));
314
315         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, numElements, 1), 1u);
316         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_y", "", spec));
317
318         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, numElements), 2u);
319         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_z", "", spec));
320
321         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, numElements), 2u);
322         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_z", "", spec));
323
324         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, numElements), 2u);
325         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_z", "", spec));
326
327         return group.release();
328 }
329
330 tcu::TestCaseGroup* createOpNopGroup (tcu::TestContext& testCtx)
331 {
332         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnop", "Test the OpNop instruction"));
333         ComputeShaderSpec                               spec;
334         de::Random                                              rnd                             (deStringHash(group->getName()));
335         const int                                               numElements             = 100;
336         vector<float>                                   positiveFloats  (numElements, 0);
337         vector<float>                                   negativeFloats  (numElements, 0);
338
339         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
340
341         for (size_t ndx = 0; ndx < numElements; ++ndx)
342                 negativeFloats[ndx] = -positiveFloats[ndx];
343
344         spec.assembly =
345                 string(getComputeAsmShaderPreamble()) +
346
347                 "OpSource GLSL 430\n"
348                 "OpName %main           \"main\"\n"
349                 "OpName %id             \"gl_GlobalInvocationID\"\n"
350
351                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
352
353                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
354
355                 + string(getComputeAsmInputOutputBuffer()) +
356
357                 "%id        = OpVariable %uvec3ptr Input\n"
358                 "%zero      = OpConstant %i32 0\n"
359
360                 "%main      = OpFunction %void None %voidf\n"
361                 "%label     = OpLabel\n"
362                 "%idval     = OpLoad %uvec3 %id\n"
363                 "%x         = OpCompositeExtract %u32 %idval 0\n"
364
365                 "             OpNop\n" // Inside a function body
366
367                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
368                 "%inval     = OpLoad %f32 %inloc\n"
369                 "%neg       = OpFNegate %f32 %inval\n"
370                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
371                 "             OpStore %outloc %neg\n"
372                 "             OpReturn\n"
373                 "             OpFunctionEnd\n";
374         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
375         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
376         spec.numWorkGroups = IVec3(numElements, 1, 1);
377
378         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNop appearing at different places", spec));
379
380         return group.release();
381 }
382
383 tcu::TestCaseGroup* createUnusedVariableComputeTests (tcu::TestContext& testCtx)
384 {
385         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "unused_variables", "Compute shaders with unused variables"));
386         de::Random                                              rnd                             (deStringHash(group->getName()));
387         const int                                               numElements             = 100;
388         vector<float>                                   positiveFloats  (numElements, 0);
389         vector<float>                                   negativeFloats  (numElements, 0);
390
391         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
392
393         for (size_t ndx = 0; ndx < numElements; ++ndx)
394                 negativeFloats[ndx] = -positiveFloats[ndx];
395
396         const VariableLocation                  testLocations[] =
397         {
398                 // Set          Binding
399                 { 0,            5                       },
400                 { 5,            5                       },
401         };
402
403         for (size_t locationNdx = 0; locationNdx < DE_LENGTH_OF_ARRAY(testLocations); ++locationNdx)
404         {
405                 const VariableLocation& location = testLocations[locationNdx];
406
407                 // Unused variable.
408                 {
409                         ComputeShaderSpec                               spec;
410
411                         spec.assembly =
412                                 string(getComputeAsmShaderPreamble()) +
413
414                                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
415
416                                 + getUnusedDecorations(location)
417
418                                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
419
420                                 + getUnusedTypesAndConstants()
421
422                                 + string(getComputeAsmInputOutputBuffer())
423
424                                 + getUnusedBuffer() +
425
426                                 "%id        = OpVariable %uvec3ptr Input\n"
427                                 "%zero      = OpConstant %i32 0\n"
428
429                                 "%main      = OpFunction %void None %voidf\n"
430                                 "%label     = OpLabel\n"
431                                 "%idval     = OpLoad %uvec3 %id\n"
432                                 "%x         = OpCompositeExtract %u32 %idval 0\n"
433
434                                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
435                                 "%inval     = OpLoad %f32 %inloc\n"
436                                 "%neg       = OpFNegate %f32 %inval\n"
437                                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
438                                 "             OpStore %outloc %neg\n"
439                                 "             OpReturn\n"
440                                 "             OpFunctionEnd\n";
441                         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
442                         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
443                         spec.numWorkGroups = IVec3(numElements, 1, 1);
444
445                         std::string testName            = "variable_" + location.toString();
446                         std::string testDescription     = "Unused variable test with " + location.toDescription();
447
448                         group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), testDescription.c_str(), spec));
449                 }
450
451                 // Unused function.
452                 {
453                         ComputeShaderSpec                               spec;
454
455                         spec.assembly =
456                                 string(getComputeAsmShaderPreamble("", "", "", getUnusedEntryPoint())) +
457
458                                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
459
460                                 + getUnusedDecorations(location)
461
462                                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
463
464                                 + getUnusedTypesAndConstants() +
465
466                                 "%c_i32_0 = OpConstant %i32 0\n"
467                                 "%c_i32_1 = OpConstant %i32 1\n"
468
469                                 + string(getComputeAsmInputOutputBuffer())
470
471                                 + getUnusedBuffer() +
472
473                                 "%id        = OpVariable %uvec3ptr Input\n"
474                                 "%zero      = OpConstant %i32 0\n"
475
476                                 "%main      = OpFunction %void None %voidf\n"
477                                 "%label     = OpLabel\n"
478                                 "%idval     = OpLoad %uvec3 %id\n"
479                                 "%x         = OpCompositeExtract %u32 %idval 0\n"
480
481                                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
482                                 "%inval     = OpLoad %f32 %inloc\n"
483                                 "%neg       = OpFNegate %f32 %inval\n"
484                                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
485                                 "             OpStore %outloc %neg\n"
486                                 "             OpReturn\n"
487                                 "             OpFunctionEnd\n"
488
489                                 + getUnusedFunctionBody();
490
491                         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
492                         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
493                         spec.numWorkGroups = IVec3(numElements, 1, 1);
494
495                         std::string testName            = "function_" + location.toString();
496                         std::string testDescription     = "Unused function test with " + location.toDescription();
497
498                         group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), testDescription.c_str(), spec));
499                 }
500         }
501
502         return group.release();
503 }
504
505 template<bool nanSupported>
506 bool compareFUnord (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
507 {
508         if (outputAllocs.size() != 1)
509                 return false;
510
511         vector<deUint8> input1Bytes;
512         vector<deUint8> input2Bytes;
513         vector<deUint8> expectedBytes;
514
515         inputs[0].getBytes(input1Bytes);
516         inputs[1].getBytes(input2Bytes);
517         expectedOutputs[0].getBytes(expectedBytes);
518
519         const deInt32* const    expectedOutputAsInt             = reinterpret_cast<const deInt32*>(&expectedBytes.front());
520         const deInt32* const    outputAsInt                             = static_cast<const deInt32*>(outputAllocs[0]->getHostPtr());
521         const float* const              input1AsFloat                   = reinterpret_cast<const float*>(&input1Bytes.front());
522         const float* const              input2AsFloat                   = reinterpret_cast<const float*>(&input2Bytes.front());
523         bool returnValue                                                                = true;
524
525         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(deInt32); ++idx)
526         {
527                 if (!nanSupported && (tcu::Float32(input1AsFloat[idx]).isNaN() || tcu::Float32(input2AsFloat[idx]).isNaN()))
528                         continue;
529
530                 if (outputAsInt[idx] != expectedOutputAsInt[idx])
531                 {
532                         log << TestLog::Message << "ERROR: Sub-case failed. inputs: " << input1AsFloat[idx] << "," << input2AsFloat[idx] << " output: " << outputAsInt[idx]<< " expected output: " << expectedOutputAsInt[idx] << TestLog::EndMessage;
533                         returnValue = false;
534                 }
535         }
536         return returnValue;
537 }
538
539 typedef VkBool32 (*compareFuncType) (float, float);
540
541 struct OpFUnordCase
542 {
543         const char*             name;
544         const char*             opCode;
545         compareFuncType compareFunc;
546
547                                         OpFUnordCase                    (const char* _name, const char* _opCode, compareFuncType _compareFunc)
548                                                 : name                          (_name)
549                                                 , opCode                        (_opCode)
550                                                 , compareFunc           (_compareFunc) {}
551 };
552
553 #define ADD_OPFUNORD_CASE(NAME, OPCODE, OPERATOR) \
554 do { \
555         struct compare_##NAME { static VkBool32 compare(float x, float y) { return (x OPERATOR y) ? VK_TRUE : VK_FALSE; } }; \
556         cases.push_back(OpFUnordCase(#NAME, OPCODE, compare_##NAME::compare)); \
557 } while (deGetFalse())
558
559 tcu::TestCaseGroup* createOpFUnordGroup (tcu::TestContext& testCtx, const bool testWithNan)
560 {
561         const string                                    nan                             = testWithNan ? "_nan" : "";
562         const string                                    groupName               = "opfunord" + nan;
563         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpFUnord* opcodes"));
564         de::Random                                              rnd                             (deStringHash(group->getName()));
565         const int                                               numElements             = 100;
566         vector<OpFUnordCase>                    cases;
567         string                                                  extensions              = testWithNan ? "OpExtension \"SPV_KHR_float_controls\"\n" : "";
568         string                                                  capabilities    = testWithNan ? "OpCapability SignedZeroInfNanPreserve\n" : "";
569         string                                                  exeModes                = testWithNan ? "OpExecutionMode %main SignedZeroInfNanPreserve 32\n" : "";
570         const StringTemplate                    shaderTemplate  (
571                 string(getComputeAsmShaderPreamble(capabilities, extensions, exeModes)) +
572                 "OpSource GLSL 430\n"
573                 "OpName %main           \"main\"\n"
574                 "OpName %id             \"gl_GlobalInvocationID\"\n"
575
576                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
577
578                 "OpDecorate %buf BufferBlock\n"
579                 "OpDecorate %buf2 BufferBlock\n"
580                 "OpDecorate %indata1 DescriptorSet 0\n"
581                 "OpDecorate %indata1 Binding 0\n"
582                 "OpDecorate %indata2 DescriptorSet 0\n"
583                 "OpDecorate %indata2 Binding 1\n"
584                 "OpDecorate %outdata DescriptorSet 0\n"
585                 "OpDecorate %outdata Binding 2\n"
586                 "OpDecorate %f32arr ArrayStride 4\n"
587                 "OpDecorate %i32arr ArrayStride 4\n"
588                 "OpMemberDecorate %buf 0 Offset 0\n"
589                 "OpMemberDecorate %buf2 0 Offset 0\n"
590
591                 + string(getComputeAsmCommonTypes()) +
592
593                 "%buf        = OpTypeStruct %f32arr\n"
594                 "%bufptr     = OpTypePointer Uniform %buf\n"
595                 "%indata1    = OpVariable %bufptr Uniform\n"
596                 "%indata2    = OpVariable %bufptr Uniform\n"
597
598                 "%buf2       = OpTypeStruct %i32arr\n"
599                 "%buf2ptr    = OpTypePointer Uniform %buf2\n"
600                 "%outdata    = OpVariable %buf2ptr Uniform\n"
601
602                 "%id        = OpVariable %uvec3ptr Input\n"
603                 "%zero      = OpConstant %i32 0\n"
604                 "%consti1   = OpConstant %i32 1\n"
605                 "%constf1   = OpConstant %f32 1.0\n"
606
607                 "%main      = OpFunction %void None %voidf\n"
608                 "%label     = OpLabel\n"
609                 "%idval     = OpLoad %uvec3 %id\n"
610                 "%x         = OpCompositeExtract %u32 %idval 0\n"
611
612                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
613                 "%inval1    = OpLoad %f32 %inloc1\n"
614                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
615                 "%inval2    = OpLoad %f32 %inloc2\n"
616                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
617
618                 "%result    = ${OPCODE} %bool %inval1 %inval2\n"
619                 "%int_res   = OpSelect %i32 %result %consti1 %zero\n"
620                 "             OpStore %outloc %int_res\n"
621
622                 "             OpReturn\n"
623                 "             OpFunctionEnd\n");
624
625         ADD_OPFUNORD_CASE(equal, "OpFUnordEqual", ==);
626         ADD_OPFUNORD_CASE(less, "OpFUnordLessThan", <);
627         ADD_OPFUNORD_CASE(lessequal, "OpFUnordLessThanEqual", <=);
628         ADD_OPFUNORD_CASE(greater, "OpFUnordGreaterThan", >);
629         ADD_OPFUNORD_CASE(greaterequal, "OpFUnordGreaterThanEqual", >=);
630         ADD_OPFUNORD_CASE(notequal, "OpFUnordNotEqual", !=);
631
632         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
633         {
634                 map<string, string>                     specializations;
635                 ComputeShaderSpec                       spec;
636                 const float                                     NaN                             = std::numeric_limits<float>::quiet_NaN();
637                 vector<float>                           inputFloats1    (numElements, 0);
638                 vector<float>                           inputFloats2    (numElements, 0);
639                 vector<deInt32>                         expectedInts    (numElements, 0);
640
641                 specializations["OPCODE"]       = cases[caseNdx].opCode;
642                 spec.assembly                           = shaderTemplate.specialize(specializations);
643
644                 fillRandomScalars(rnd, 1.f, 100.f, &inputFloats1[0], numElements);
645                 for (size_t ndx = 0; ndx < numElements; ++ndx)
646                 {
647                         switch (ndx % 6)
648                         {
649                                 case 0:         inputFloats2[ndx] = inputFloats1[ndx] + 1.0f; break;
650                                 case 1:         inputFloats2[ndx] = inputFloats1[ndx] - 1.0f; break;
651                                 case 2:         inputFloats2[ndx] = inputFloats1[ndx]; break;
652                                 case 3:         inputFloats2[ndx] = NaN; break;
653                                 case 4:         inputFloats2[ndx] = inputFloats1[ndx];  inputFloats1[ndx] = NaN; break;
654                                 case 5:         inputFloats2[ndx] = NaN;                                inputFloats1[ndx] = NaN; break;
655                         }
656                         expectedInts[ndx] = tcu::Float32(inputFloats1[ndx]).isNaN() || tcu::Float32(inputFloats2[ndx]).isNaN() || cases[caseNdx].compareFunc(inputFloats1[ndx], inputFloats2[ndx]);
657                 }
658
659                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
660                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
661                 spec.outputs.push_back(BufferSp(new Int32Buffer(expectedInts)));
662                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
663                 spec.verifyIO           = testWithNan ? &compareFUnord<true> : &compareFUnord<false>;
664
665                 if (testWithNan)
666                 {
667                         spec.extensions.push_back("VK_KHR_shader_float_controls");
668                         spec.requestedVulkanFeatures.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat32 = DE_TRUE;
669                 }
670
671                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
672         }
673
674         return group.release();
675 }
676
677 struct OpAtomicCase
678 {
679         const char*             name;
680         const char*             assembly;
681         const char*             retValAssembly;
682         OpAtomicType    opAtomic;
683         deInt32                 numOutputElements;
684
685                                         OpAtomicCase(const char* _name, const char* _assembly, const char* _retValAssembly, OpAtomicType _opAtomic, deInt32 _numOutputElements)
686                                                 : name                          (_name)
687                                                 , assembly                      (_assembly)
688                                                 , retValAssembly        (_retValAssembly)
689                                                 , opAtomic                      (_opAtomic)
690                                                 , numOutputElements     (_numOutputElements) {}
691 };
692
693 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx, bool useStorageBuffer, int numElements = 65535, bool verifyReturnValues = false)
694 {
695         std::string                                             groupName                       ("opatomic");
696         if (useStorageBuffer)
697                 groupName += "_storage_buffer";
698         if (verifyReturnValues)
699                 groupName += "_return_values";
700         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpAtomic* opcodes"));
701         vector<OpAtomicCase>                    cases;
702
703         const StringTemplate                    shaderTemplate  (
704
705                 string("OpCapability Shader\n") +
706                 (useStorageBuffer ? "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n" : "") +
707                 "OpMemoryModel Logical GLSL450\n"
708                 "OpEntryPoint GLCompute %main \"main\" %id\n"
709                 "OpExecutionMode %main LocalSize 1 1 1\n" +
710
711                 "OpSource GLSL 430\n"
712                 "OpName %main           \"main\"\n"
713                 "OpName %id             \"gl_GlobalInvocationID\"\n"
714
715                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
716
717                 "OpDecorate %buf ${BLOCK_DECORATION}\n"
718                 "OpDecorate %indata DescriptorSet 0\n"
719                 "OpDecorate %indata Binding 0\n"
720                 "OpDecorate %i32arr ArrayStride 4\n"
721                 "OpMemberDecorate %buf 0 Offset 0\n"
722
723                 "OpDecorate %sumbuf ${BLOCK_DECORATION}\n"
724                 "OpDecorate %sum DescriptorSet 0\n"
725                 "OpDecorate %sum Binding 1\n"
726                 "OpMemberDecorate %sumbuf 0 Coherent\n"
727                 "OpMemberDecorate %sumbuf 0 Offset 0\n"
728
729                 "${RETVAL_BUF_DECORATE}"
730
731                 + getComputeAsmCommonTypes("${BLOCK_POINTER_TYPE}") +
732
733                 "%buf       = OpTypeStruct %i32arr\n"
734                 "%bufptr    = OpTypePointer ${BLOCK_POINTER_TYPE} %buf\n"
735                 "%indata    = OpVariable %bufptr ${BLOCK_POINTER_TYPE}\n"
736
737                 "%sumbuf    = OpTypeStruct %i32arr\n"
738                 "%sumbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %sumbuf\n"
739                 "%sum       = OpVariable %sumbufptr ${BLOCK_POINTER_TYPE}\n"
740
741                 "${RETVAL_BUF_DECL}"
742
743                 "%id        = OpVariable %uvec3ptr Input\n"
744                 "%minusone  = OpConstant %i32 -1\n"
745                 "%zero      = OpConstant %i32 0\n"
746                 "%one       = OpConstant %u32 1\n"
747                 "%two       = OpConstant %i32 2\n"
748
749                 "%main      = OpFunction %void None %voidf\n"
750                 "%label     = OpLabel\n"
751                 "%idval     = OpLoad %uvec3 %id\n"
752                 "%x         = OpCompositeExtract %u32 %idval 0\n"
753
754                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
755                 "%inval     = OpLoad %i32 %inloc\n"
756
757                 "%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
758                 "${INSTRUCTION}"
759                 "${RETVAL_ASSEMBLY}"
760
761                 "             OpReturn\n"
762                 "             OpFunctionEnd\n");
763
764         #define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS) \
765         do { \
766                 DE_ASSERT((NUM_OUTPUT_ELEMENTS) == 1 || (NUM_OUTPUT_ELEMENTS) == numElements); \
767                 cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS)); \
768         } while (deGetFalse())
769         #define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, 1)
770         #define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, numElements)
771
772         ADD_OPATOMIC_CASE_1(iadd,       "%retv      = OpAtomicIAdd %i32 %outloc %one %zero %inval\n",
773                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IADD );
774         ADD_OPATOMIC_CASE_1(isub,       "%retv      = OpAtomicISub %i32 %outloc %one %zero %inval\n",
775                                                                 "             OpStore %retloc %retv\n", OPATOMIC_ISUB );
776         ADD_OPATOMIC_CASE_1(iinc,       "%retv      = OpAtomicIIncrement %i32 %outloc %one %zero\n",
777                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IINC );
778         ADD_OPATOMIC_CASE_1(idec,       "%retv      = OpAtomicIDecrement %i32 %outloc %one %zero\n",
779                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IDEC );
780         if (!verifyReturnValues)
781         {
782                 ADD_OPATOMIC_CASE_N(load,       "%inval2    = OpAtomicLoad %i32 %inloc %one %zero\n"
783                                                                         "             OpStore %outloc %inval2\n", "", OPATOMIC_LOAD );
784                 ADD_OPATOMIC_CASE_N(store,      "             OpAtomicStore %outloc %one %zero %inval\n", "", OPATOMIC_STORE );
785         }
786
787         ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
788                                                                 "             OpStore %outloc %even\n"
789                                                                 "%retv      = OpAtomicCompareExchange %i32 %outloc %one %zero %zero %minusone %zero\n",
790                                                                 "                         OpStore %retloc %retv\n", OPATOMIC_COMPEX );
791
792
793         #undef ADD_OPATOMIC_CASE
794         #undef ADD_OPATOMIC_CASE_1
795         #undef ADD_OPATOMIC_CASE_N
796
797         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
798         {
799                 map<string, string>                     specializations;
800                 ComputeShaderSpec                       spec;
801                 vector<deInt32>                         inputInts               (numElements, 0);
802                 vector<deInt32>                         expected                (cases[caseNdx].numOutputElements, -1);
803
804                 specializations["INDEX"]                                = (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
805                 specializations["INSTRUCTION"]                  = cases[caseNdx].assembly;
806                 specializations["BLOCK_DECORATION"]             = useStorageBuffer ? "Block" : "BufferBlock";
807                 specializations["BLOCK_POINTER_TYPE"]   = useStorageBuffer ? "StorageBuffer" : "Uniform";
808
809                 if (verifyReturnValues)
810                 {
811                         const StringTemplate blockDecoration    (
812                                 "\n"
813                                 "OpDecorate %retbuf ${BLOCK_DECORATION}\n"
814                                 "OpDecorate %ret DescriptorSet 0\n"
815                                 "OpDecorate %ret Binding 2\n"
816                                 "OpMemberDecorate %retbuf 0 Offset 0\n\n");
817
818                         const StringTemplate blockDeclaration   (
819                                 "\n"
820                                 "%retbuf    = OpTypeStruct %i32arr\n"
821                                 "%retbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %retbuf\n"
822                                 "%ret       = OpVariable %retbufptr ${BLOCK_POINTER_TYPE}\n\n");
823
824                         specializations["RETVAL_ASSEMBLY"] =
825                                 "%retloc    = OpAccessChain %i32ptr %ret %zero %x\n"
826                                 + std::string(cases[caseNdx].retValAssembly);
827
828                         specializations["RETVAL_BUF_DECORATE"]  = blockDecoration.specialize(specializations);
829                         specializations["RETVAL_BUF_DECL"]              = blockDeclaration.specialize(specializations);
830                 }
831                 else
832                 {
833                         specializations["RETVAL_ASSEMBLY"]              = "";
834                         specializations["RETVAL_BUF_DECORATE"]  = "";
835                         specializations["RETVAL_BUF_DECL"]              = "";
836                 }
837
838                 spec.assembly                                                   = shaderTemplate.specialize(specializations);
839
840                 if (useStorageBuffer)
841                         spec.extensions.push_back("VK_KHR_storage_buffer_storage_class");
842
843                 spec.inputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_INPUT)));
844                 spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_EXPECTED)));
845                 if (verifyReturnValues)
846                         spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_ATOMIC_RET)));
847                 spec.numWorkGroups = IVec3(numElements, 1, 1);
848
849                 if (verifyReturnValues)
850                 {
851                         switch (cases[caseNdx].opAtomic)
852                         {
853                                 case OPATOMIC_IADD:
854                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IADD>;
855                                         break;
856                                 case OPATOMIC_ISUB:
857                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_ISUB>;
858                                         break;
859                                 case OPATOMIC_IINC:
860                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IINC>;
861                                         break;
862                                 case OPATOMIC_IDEC:
863                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IDEC>;
864                                         break;
865                                 case OPATOMIC_COMPEX:
866                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_COMPEX>;
867                                         break;
868                                 default:
869                                         DE_FATAL("Unsupported OpAtomic type for return value verification");
870                         }
871                 }
872                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
873         }
874
875         return group.release();
876 }
877
878 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
879 {
880         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
881         ComputeShaderSpec                               spec;
882         de::Random                                              rnd                             (deStringHash(group->getName()));
883         const int                                               numElements             = 100;
884         vector<float>                                   positiveFloats  (numElements, 0);
885         vector<float>                                   negativeFloats  (numElements, 0);
886
887         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
888
889         for (size_t ndx = 0; ndx < numElements; ++ndx)
890                 negativeFloats[ndx] = -positiveFloats[ndx];
891
892         spec.assembly =
893                 string(getComputeAsmShaderPreamble()) +
894
895                 "%fname1 = OpString \"negateInputs.comp\"\n"
896                 "%fname2 = OpString \"negateInputs\"\n"
897
898                 "OpSource GLSL 430\n"
899                 "OpName %main           \"main\"\n"
900                 "OpName %id             \"gl_GlobalInvocationID\"\n"
901
902                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
903
904                 + string(getComputeAsmInputOutputBufferTraits()) +
905
906                 "OpLine %fname1 0 0\n" // At the earliest possible position
907
908                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
909
910                 "OpLine %fname1 0 1\n" // Multiple OpLines in sequence
911                 "OpLine %fname2 1 0\n" // Different filenames
912                 "OpLine %fname1 1000 100000\n"
913
914                 "%id        = OpVariable %uvec3ptr Input\n"
915                 "%zero      = OpConstant %i32 0\n"
916
917                 "OpLine %fname1 1 1\n" // Before a function
918
919                 "%main      = OpFunction %void None %voidf\n"
920                 "%label     = OpLabel\n"
921
922                 "OpLine %fname1 1 1\n" // In a function
923
924                 "%idval     = OpLoad %uvec3 %id\n"
925                 "%x         = OpCompositeExtract %u32 %idval 0\n"
926                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
927                 "%inval     = OpLoad %f32 %inloc\n"
928                 "%neg       = OpFNegate %f32 %inval\n"
929                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
930                 "             OpStore %outloc %neg\n"
931                 "             OpReturn\n"
932                 "             OpFunctionEnd\n";
933         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
934         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
935         spec.numWorkGroups = IVec3(numElements, 1, 1);
936
937         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
938
939         return group.release();
940 }
941
942 bool veryfiBinaryShader (const ProgramBinary& binary)
943 {
944         const size_t    paternCount                     = 3u;
945         bool paternsCheck[paternCount]          =
946         {
947                 false, false, false
948         };
949         const string patersns[paternCount]      =
950         {
951                 "VULKAN CTS",
952                 "Negative values",
953                 "Date: 2017/09/21"
954         };
955         size_t                  paternNdx               = 0u;
956
957         for (size_t ndx = 0u; ndx < binary.getSize(); ++ndx)
958         {
959                 if (false == paternsCheck[paternNdx] &&
960                         patersns[paternNdx][0] == static_cast<char>(binary.getBinary()[ndx]) &&
961                         deMemoryEqual((const char*)&binary.getBinary()[ndx], &patersns[paternNdx][0], patersns[paternNdx].length()))
962                 {
963                         paternsCheck[paternNdx]= true;
964                         paternNdx++;
965                         if (paternNdx == paternCount)
966                                 break;
967                 }
968         }
969
970         for (size_t ndx = 0u; ndx < paternCount; ++ndx)
971         {
972                 if (!paternsCheck[ndx])
973                         return false;
974         }
975
976         return true;
977 }
978
979 tcu::TestCaseGroup* createOpModuleProcessedGroup (tcu::TestContext& testCtx)
980 {
981         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "Test the OpModuleProcessed instruction"));
982         ComputeShaderSpec                               spec;
983         de::Random                                              rnd                             (deStringHash(group->getName()));
984         const int                                               numElements             = 10;
985         vector<float>                                   positiveFloats  (numElements, 0);
986         vector<float>                                   negativeFloats  (numElements, 0);
987
988         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
989
990         for (size_t ndx = 0; ndx < numElements; ++ndx)
991                 negativeFloats[ndx] = -positiveFloats[ndx];
992
993         spec.assembly =
994                 string(getComputeAsmShaderPreamble()) +
995                 "%fname = OpString \"negateInputs.comp\"\n"
996
997                 "OpSource GLSL 430\n"
998                 "OpName %main           \"main\"\n"
999                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1000                 "OpModuleProcessed \"VULKAN CTS\"\n"                                    //OpModuleProcessed;
1001                 "OpModuleProcessed \"Negative values\"\n"
1002                 "OpModuleProcessed \"Date: 2017/09/21\"\n"
1003                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1004
1005                 + string(getComputeAsmInputOutputBufferTraits())
1006
1007                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
1008
1009                 "OpLine %fname 0 1\n"
1010
1011                 "OpLine %fname 1000 1\n"
1012
1013                 "%id        = OpVariable %uvec3ptr Input\n"
1014                 "%zero      = OpConstant %i32 0\n"
1015                 "%main      = OpFunction %void None %voidf\n"
1016
1017                 "%label     = OpLabel\n"
1018                 "%idval     = OpLoad %uvec3 %id\n"
1019                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1020
1021                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
1022                 "%inval     = OpLoad %f32 %inloc\n"
1023                 "%neg       = OpFNegate %f32 %inval\n"
1024                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1025                 "             OpStore %outloc %neg\n"
1026                 "             OpReturn\n"
1027                 "             OpFunctionEnd\n";
1028         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
1029         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
1030         spec.numWorkGroups = IVec3(numElements, 1, 1);
1031         spec.verifyBinary = veryfiBinaryShader;
1032         spec.spirvVersion = SPIRV_VERSION_1_3;
1033
1034         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpModuleProcessed Tests", spec));
1035
1036         return group.release();
1037 }
1038
1039 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
1040 {
1041         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
1042         ComputeShaderSpec                               spec;
1043         de::Random                                              rnd                             (deStringHash(group->getName()));
1044         const int                                               numElements             = 100;
1045         vector<float>                                   positiveFloats  (numElements, 0);
1046         vector<float>                                   negativeFloats  (numElements, 0);
1047
1048         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
1049
1050         for (size_t ndx = 0; ndx < numElements; ++ndx)
1051                 negativeFloats[ndx] = -positiveFloats[ndx];
1052
1053         spec.assembly =
1054                 string(getComputeAsmShaderPreamble()) +
1055
1056                 "%fname = OpString \"negateInputs.comp\"\n"
1057
1058                 "OpSource GLSL 430\n"
1059                 "OpName %main           \"main\"\n"
1060                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1061
1062                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1063
1064                 + string(getComputeAsmInputOutputBufferTraits()) +
1065
1066                 "OpNoLine\n" // At the earliest possible position, without preceding OpLine
1067
1068                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
1069
1070                 "OpLine %fname 0 1\n"
1071                 "OpNoLine\n" // Immediately following a preceding OpLine
1072
1073                 "OpLine %fname 1000 1\n"
1074
1075                 "%id        = OpVariable %uvec3ptr Input\n"
1076                 "%zero      = OpConstant %i32 0\n"
1077
1078                 "OpNoLine\n" // Contents after the previous OpLine
1079
1080                 "%main      = OpFunction %void None %voidf\n"
1081                 "%label     = OpLabel\n"
1082                 "%idval     = OpLoad %uvec3 %id\n"
1083                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1084
1085                 "OpNoLine\n" // Multiple OpNoLine
1086                 "OpNoLine\n"
1087                 "OpNoLine\n"
1088
1089                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
1090                 "%inval     = OpLoad %f32 %inloc\n"
1091                 "%neg       = OpFNegate %f32 %inval\n"
1092                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1093                 "             OpStore %outloc %neg\n"
1094                 "             OpReturn\n"
1095                 "             OpFunctionEnd\n";
1096         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
1097         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
1098         spec.numWorkGroups = IVec3(numElements, 1, 1);
1099
1100         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
1101
1102         return group.release();
1103 }
1104
1105 // Compare instruction for the contraction compute case.
1106 // Returns true if the output is what is expected from the test case.
1107 bool compareNoContractCase(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1108 {
1109         if (outputAllocs.size() != 1)
1110                 return false;
1111
1112         // Only size is needed because we are not comparing the exact values.
1113         size_t byteSize = expectedOutputs[0].getByteSize();
1114
1115         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1116
1117         for(size_t i = 0; i < byteSize / sizeof(float); ++i) {
1118                 if (outputAsFloat[i] != 0.f &&
1119                         outputAsFloat[i] != -ldexp(1, -24)) {
1120                         return false;
1121                 }
1122         }
1123
1124         return true;
1125 }
1126
1127 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
1128 {
1129         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
1130         vector<CaseParameter>                   cases;
1131         const int                                               numElements             = 100;
1132         vector<float>                                   inputFloats1    (numElements, 0);
1133         vector<float>                                   inputFloats2    (numElements, 0);
1134         vector<float>                                   outputFloats    (numElements, 0);
1135         const StringTemplate                    shaderTemplate  (
1136                 string(getComputeAsmShaderPreamble()) +
1137
1138                 "OpName %main           \"main\"\n"
1139                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1140
1141                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1142
1143                 "${DECORATION}\n"
1144
1145                 "OpDecorate %buf BufferBlock\n"
1146                 "OpDecorate %indata1 DescriptorSet 0\n"
1147                 "OpDecorate %indata1 Binding 0\n"
1148                 "OpDecorate %indata2 DescriptorSet 0\n"
1149                 "OpDecorate %indata2 Binding 1\n"
1150                 "OpDecorate %outdata DescriptorSet 0\n"
1151                 "OpDecorate %outdata Binding 2\n"
1152                 "OpDecorate %f32arr ArrayStride 4\n"
1153                 "OpMemberDecorate %buf 0 Offset 0\n"
1154
1155                 + string(getComputeAsmCommonTypes()) +
1156
1157                 "%buf        = OpTypeStruct %f32arr\n"
1158                 "%bufptr     = OpTypePointer Uniform %buf\n"
1159                 "%indata1    = OpVariable %bufptr Uniform\n"
1160                 "%indata2    = OpVariable %bufptr Uniform\n"
1161                 "%outdata    = OpVariable %bufptr Uniform\n"
1162
1163                 "%id         = OpVariable %uvec3ptr Input\n"
1164                 "%zero       = OpConstant %i32 0\n"
1165                 "%c_f_m1     = OpConstant %f32 -1.\n"
1166
1167                 "%main       = OpFunction %void None %voidf\n"
1168                 "%label      = OpLabel\n"
1169                 "%idval      = OpLoad %uvec3 %id\n"
1170                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1171                 "%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
1172                 "%inval1     = OpLoad %f32 %inloc1\n"
1173                 "%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
1174                 "%inval2     = OpLoad %f32 %inloc2\n"
1175                 "%mul        = OpFMul %f32 %inval1 %inval2\n"
1176                 "%add        = OpFAdd %f32 %mul %c_f_m1\n"
1177                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
1178                 "              OpStore %outloc %add\n"
1179                 "              OpReturn\n"
1180                 "              OpFunctionEnd\n");
1181
1182         cases.push_back(CaseParameter("multiplication", "OpDecorate %mul NoContraction"));
1183         cases.push_back(CaseParameter("addition",               "OpDecorate %add NoContraction"));
1184         cases.push_back(CaseParameter("both",                   "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
1185
1186         for (size_t ndx = 0; ndx < numElements; ++ndx)
1187         {
1188                 inputFloats1[ndx]       = 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
1189                 inputFloats2[ndx]       = 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
1190                 // Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
1191                 // conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
1192                 // So the final result will be 0.f or 0x1p-24.
1193                 // If the operation is combined into a precise fused multiply-add, then the result would be
1194                 // 2^-46 (0xa8800000).
1195                 outputFloats[ndx]       = 0.f;
1196         }
1197
1198         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
1199         {
1200                 map<string, string>             specializations;
1201                 ComputeShaderSpec               spec;
1202
1203                 specializations["DECORATION"] = cases[caseNdx].param;
1204                 spec.assembly = shaderTemplate.specialize(specializations);
1205                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1206                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1207                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1208                 spec.numWorkGroups = IVec3(numElements, 1, 1);
1209                 // Check against the two possible answers based on rounding mode.
1210                 spec.verifyIO = &compareNoContractCase;
1211
1212                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
1213         }
1214         return group.release();
1215 }
1216
1217 bool compareFRem(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1218 {
1219         if (outputAllocs.size() != 1)
1220                 return false;
1221
1222         vector<deUint8> expectedBytes;
1223         expectedOutputs[0].getBytes(expectedBytes);
1224
1225         const float*    expectedOutputAsFloat   = reinterpret_cast<const float*>(&expectedBytes.front());
1226         const float*    outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1227
1228         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(float); ++idx)
1229         {
1230                 const float f0 = expectedOutputAsFloat[idx];
1231                 const float f1 = outputAsFloat[idx];
1232                 // \todo relative error needs to be fairly high because FRem may be implemented as
1233                 // (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
1234                 if (deFloatAbs((f1 - f0) / f0) > 0.02)
1235                         return false;
1236         }
1237
1238         return true;
1239 }
1240
1241 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
1242 {
1243         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
1244         ComputeShaderSpec                               spec;
1245         de::Random                                              rnd                             (deStringHash(group->getName()));
1246         const int                                               numElements             = 200;
1247         vector<float>                                   inputFloats1    (numElements, 0);
1248         vector<float>                                   inputFloats2    (numElements, 0);
1249         vector<float>                                   outputFloats    (numElements, 0);
1250
1251         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1252         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
1253
1254         for (size_t ndx = 0; ndx < numElements; ++ndx)
1255         {
1256                 // Guard against divisors near zero.
1257                 if (std::fabs(inputFloats2[ndx]) < 1e-3)
1258                         inputFloats2[ndx] = 8.f;
1259
1260                 // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1261                 outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
1262         }
1263
1264         spec.assembly =
1265                 string(getComputeAsmShaderPreamble()) +
1266
1267                 "OpName %main           \"main\"\n"
1268                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1269
1270                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1271
1272                 "OpDecorate %buf BufferBlock\n"
1273                 "OpDecorate %indata1 DescriptorSet 0\n"
1274                 "OpDecorate %indata1 Binding 0\n"
1275                 "OpDecorate %indata2 DescriptorSet 0\n"
1276                 "OpDecorate %indata2 Binding 1\n"
1277                 "OpDecorate %outdata DescriptorSet 0\n"
1278                 "OpDecorate %outdata Binding 2\n"
1279                 "OpDecorate %f32arr ArrayStride 4\n"
1280                 "OpMemberDecorate %buf 0 Offset 0\n"
1281
1282                 + string(getComputeAsmCommonTypes()) +
1283
1284                 "%buf        = OpTypeStruct %f32arr\n"
1285                 "%bufptr     = OpTypePointer Uniform %buf\n"
1286                 "%indata1    = OpVariable %bufptr Uniform\n"
1287                 "%indata2    = OpVariable %bufptr Uniform\n"
1288                 "%outdata    = OpVariable %bufptr Uniform\n"
1289
1290                 "%id        = OpVariable %uvec3ptr Input\n"
1291                 "%zero      = OpConstant %i32 0\n"
1292
1293                 "%main      = OpFunction %void None %voidf\n"
1294                 "%label     = OpLabel\n"
1295                 "%idval     = OpLoad %uvec3 %id\n"
1296                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1297                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1298                 "%inval1    = OpLoad %f32 %inloc1\n"
1299                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1300                 "%inval2    = OpLoad %f32 %inloc2\n"
1301                 "%rem       = OpFRem %f32 %inval1 %inval2\n"
1302                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1303                 "             OpStore %outloc %rem\n"
1304                 "             OpReturn\n"
1305                 "             OpFunctionEnd\n";
1306
1307         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1308         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1309         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1310         spec.numWorkGroups = IVec3(numElements, 1, 1);
1311         spec.verifyIO = &compareFRem;
1312
1313         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1314
1315         return group.release();
1316 }
1317
1318 bool compareNMin (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1319 {
1320         if (outputAllocs.size() != 1)
1321                 return false;
1322
1323         const BufferSp&                 expectedOutput                  (expectedOutputs[0].getBuffer());
1324         std::vector<deUint8>    data;
1325         expectedOutput->getBytes(data);
1326
1327         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1328         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1329
1330         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1331         {
1332                 const float f0 = expectedOutputAsFloat[idx];
1333                 const float f1 = outputAsFloat[idx];
1334
1335                 // For NMin, we accept NaN as output if both inputs were NaN.
1336                 // Otherwise the NaN is the wrong choise, as on architectures that
1337                 // do not handle NaN, those are huge values.
1338                 if (!(tcu::Float32(f1).isNaN() && tcu::Float32(f0).isNaN()) && deFloatAbs(f1 - f0) > 0.00001f)
1339                         return false;
1340         }
1341
1342         return true;
1343 }
1344
1345 tcu::TestCaseGroup* createOpNMinGroup (tcu::TestContext& testCtx)
1346 {
1347         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnmin", "Test the OpNMin 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 smallest
1365                 outputFloats[ndx] = std::min(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 NMin %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 = &compareNMin;
1436
1437         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1438
1439         return group.release();
1440 }
1441
1442 bool compareNMax (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); ++idx)
1455         {
1456                 const float f0 = expectedOutputAsFloat[idx];
1457                 const float f1 = outputAsFloat[idx];
1458
1459                 // For NMax, NaN is considered acceptable result, since in
1460                 // architectures that do not handle NaNs, those are huge values.
1461                 if (!tcu::Float32(f1).isNaN() && deFloatAbs(f1 - f0) > 0.00001f)
1462                         return false;
1463         }
1464
1465         return true;
1466 }
1467
1468 tcu::TestCaseGroup* createOpNMaxGroup (tcu::TestContext& testCtx)
1469 {
1470         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opnmax", "Test the OpNMax instruction"));
1471         ComputeShaderSpec                               spec;
1472         de::Random                                              rnd                             (deStringHash(group->getName()));
1473         const int                                               numElements             = 200;
1474         vector<float>                                   inputFloats1    (numElements, 0);
1475         vector<float>                                   inputFloats2    (numElements, 0);
1476         vector<float>                                   outputFloats    (numElements, 0);
1477
1478         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1479         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1480
1481         // Make the first case a full-NAN case.
1482         inputFloats1[0] = TCU_NAN;
1483         inputFloats2[0] = TCU_NAN;
1484
1485         for (size_t ndx = 0; ndx < numElements; ++ndx)
1486         {
1487                 // By default, pick the biggest
1488                 outputFloats[ndx] = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1489
1490                 // Make half of the cases NaN cases
1491                 if ((ndx & 1) == 0)
1492                 {
1493                         // Alternate between the NaN operand
1494                         if ((ndx & 2) == 0)
1495                         {
1496                                 outputFloats[ndx] = inputFloats2[ndx];
1497                                 inputFloats1[ndx] = TCU_NAN;
1498                         }
1499                         else
1500                         {
1501                                 outputFloats[ndx] = inputFloats1[ndx];
1502                                 inputFloats2[ndx] = TCU_NAN;
1503                         }
1504                 }
1505         }
1506
1507         spec.assembly =
1508                 "OpCapability Shader\n"
1509                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1510                 "OpMemoryModel Logical GLSL450\n"
1511                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1512                 "OpExecutionMode %main LocalSize 1 1 1\n"
1513
1514                 "OpName %main           \"main\"\n"
1515                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1516
1517                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1518
1519                 "OpDecorate %buf BufferBlock\n"
1520                 "OpDecorate %indata1 DescriptorSet 0\n"
1521                 "OpDecorate %indata1 Binding 0\n"
1522                 "OpDecorate %indata2 DescriptorSet 0\n"
1523                 "OpDecorate %indata2 Binding 1\n"
1524                 "OpDecorate %outdata DescriptorSet 0\n"
1525                 "OpDecorate %outdata Binding 2\n"
1526                 "OpDecorate %f32arr ArrayStride 4\n"
1527                 "OpMemberDecorate %buf 0 Offset 0\n"
1528
1529                 + string(getComputeAsmCommonTypes()) +
1530
1531                 "%buf        = OpTypeStruct %f32arr\n"
1532                 "%bufptr     = OpTypePointer Uniform %buf\n"
1533                 "%indata1    = OpVariable %bufptr Uniform\n"
1534                 "%indata2    = OpVariable %bufptr Uniform\n"
1535                 "%outdata    = OpVariable %bufptr Uniform\n"
1536
1537                 "%id        = OpVariable %uvec3ptr Input\n"
1538                 "%zero      = OpConstant %i32 0\n"
1539
1540                 "%main      = OpFunction %void None %voidf\n"
1541                 "%label     = OpLabel\n"
1542                 "%idval     = OpLoad %uvec3 %id\n"
1543                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1544                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1545                 "%inval1    = OpLoad %f32 %inloc1\n"
1546                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1547                 "%inval2    = OpLoad %f32 %inloc2\n"
1548                 "%rem       = OpExtInst %f32 %std450 NMax %inval1 %inval2\n"
1549                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1550                 "             OpStore %outloc %rem\n"
1551                 "             OpReturn\n"
1552                 "             OpFunctionEnd\n";
1553
1554         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1555         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1556         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1557         spec.numWorkGroups = IVec3(numElements, 1, 1);
1558         spec.verifyIO = &compareNMax;
1559
1560         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1561
1562         return group.release();
1563 }
1564
1565 bool compareNClamp (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1566 {
1567         if (outputAllocs.size() != 1)
1568                 return false;
1569
1570         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1571         std::vector<deUint8>    data;
1572         expectedOutput->getBytes(data);
1573
1574         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1575         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1576
1577         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float) / 2; ++idx)
1578         {
1579                 const float e0 = expectedOutputAsFloat[idx * 2];
1580                 const float e1 = expectedOutputAsFloat[idx * 2 + 1];
1581                 const float res = outputAsFloat[idx];
1582
1583                 // For NClamp, we have two possible outcomes based on
1584                 // whether NaNs are handled or not.
1585                 // If either min or max value is NaN, the result is undefined,
1586                 // so this test doesn't stress those. If the clamped value is
1587                 // NaN, and NaNs are handled, the result is min; if NaNs are not
1588                 // handled, they are big values that result in max.
1589                 // If all three parameters are NaN, the result should be NaN.
1590                 if (!((tcu::Float32(e0).isNaN() && tcu::Float32(res).isNaN()) ||
1591                          (deFloatAbs(e0 - res) < 0.00001f) ||
1592                          (deFloatAbs(e1 - res) < 0.00001f)))
1593                         return false;
1594         }
1595
1596         return true;
1597 }
1598
1599 tcu::TestCaseGroup* createOpNClampGroup (tcu::TestContext& testCtx)
1600 {
1601         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnclamp", "Test the OpNClamp instruction"));
1602         ComputeShaderSpec                               spec;
1603         de::Random                                              rnd                             (deStringHash(group->getName()));
1604         const int                                               numElements             = 200;
1605         vector<float>                                   inputFloats1    (numElements, 0);
1606         vector<float>                                   inputFloats2    (numElements, 0);
1607         vector<float>                                   inputFloats3    (numElements, 0);
1608         vector<float>                                   outputFloats    (numElements * 2, 0);
1609
1610         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1611         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1612         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats3[0], numElements);
1613
1614         for (size_t ndx = 0; ndx < numElements; ++ndx)
1615         {
1616                 // Results are only defined if max value is bigger than min value.
1617                 if (inputFloats2[ndx] > inputFloats3[ndx])
1618                 {
1619                         float t = inputFloats2[ndx];
1620                         inputFloats2[ndx] = inputFloats3[ndx];
1621                         inputFloats3[ndx] = t;
1622                 }
1623
1624                 // By default, do the clamp, setting both possible answers
1625                 float defaultRes = std::min(std::max(inputFloats1[ndx], inputFloats2[ndx]), inputFloats3[ndx]);
1626
1627                 float maxResA = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1628                 float maxResB = maxResA;
1629
1630                 // Alternate between the NaN cases
1631                 if (ndx & 1)
1632                 {
1633                         inputFloats1[ndx] = TCU_NAN;
1634                         // If NaN is handled, the result should be same as the clamp minimum.
1635                         // If NaN is not handled, the result should clamp to the clamp maximum.
1636                         maxResA = inputFloats2[ndx];
1637                         maxResB = inputFloats3[ndx];
1638                 }
1639                 else
1640                 {
1641                         // Not a NaN case - only one legal result.
1642                         maxResA = defaultRes;
1643                         maxResB = defaultRes;
1644                 }
1645
1646                 outputFloats[ndx * 2] = maxResA;
1647                 outputFloats[ndx * 2 + 1] = maxResB;
1648         }
1649
1650         // Make the first case a full-NAN case.
1651         inputFloats1[0] = TCU_NAN;
1652         inputFloats2[0] = TCU_NAN;
1653         inputFloats3[0] = TCU_NAN;
1654         outputFloats[0] = TCU_NAN;
1655         outputFloats[1] = TCU_NAN;
1656
1657         spec.assembly =
1658                 "OpCapability Shader\n"
1659                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1660                 "OpMemoryModel Logical GLSL450\n"
1661                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1662                 "OpExecutionMode %main LocalSize 1 1 1\n"
1663
1664                 "OpName %main           \"main\"\n"
1665                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1666
1667                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1668
1669                 "OpDecorate %buf BufferBlock\n"
1670                 "OpDecorate %indata1 DescriptorSet 0\n"
1671                 "OpDecorate %indata1 Binding 0\n"
1672                 "OpDecorate %indata2 DescriptorSet 0\n"
1673                 "OpDecorate %indata2 Binding 1\n"
1674                 "OpDecorate %indata3 DescriptorSet 0\n"
1675                 "OpDecorate %indata3 Binding 2\n"
1676                 "OpDecorate %outdata DescriptorSet 0\n"
1677                 "OpDecorate %outdata Binding 3\n"
1678                 "OpDecorate %f32arr ArrayStride 4\n"
1679                 "OpMemberDecorate %buf 0 Offset 0\n"
1680
1681                 + string(getComputeAsmCommonTypes()) +
1682
1683                 "%buf        = OpTypeStruct %f32arr\n"
1684                 "%bufptr     = OpTypePointer Uniform %buf\n"
1685                 "%indata1    = OpVariable %bufptr Uniform\n"
1686                 "%indata2    = OpVariable %bufptr Uniform\n"
1687                 "%indata3    = OpVariable %bufptr Uniform\n"
1688                 "%outdata    = OpVariable %bufptr Uniform\n"
1689
1690                 "%id        = OpVariable %uvec3ptr Input\n"
1691                 "%zero      = OpConstant %i32 0\n"
1692
1693                 "%main      = OpFunction %void None %voidf\n"
1694                 "%label     = OpLabel\n"
1695                 "%idval     = OpLoad %uvec3 %id\n"
1696                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1697                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1698                 "%inval1    = OpLoad %f32 %inloc1\n"
1699                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1700                 "%inval2    = OpLoad %f32 %inloc2\n"
1701                 "%inloc3    = OpAccessChain %f32ptr %indata3 %zero %x\n"
1702                 "%inval3    = OpLoad %f32 %inloc3\n"
1703                 "%rem       = OpExtInst %f32 %std450 NClamp %inval1 %inval2 %inval3\n"
1704                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1705                 "             OpStore %outloc %rem\n"
1706                 "             OpReturn\n"
1707                 "             OpFunctionEnd\n";
1708
1709         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1710         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1711         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1712         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1713         spec.numWorkGroups = IVec3(numElements, 1, 1);
1714         spec.verifyIO = &compareNClamp;
1715
1716         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1717
1718         return group.release();
1719 }
1720
1721 tcu::TestCaseGroup* createOpSRemComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1722 {
1723         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem", "Test the OpSRem instruction"));
1724         de::Random                                              rnd                             (deStringHash(group->getName()));
1725         const int                                               numElements             = 200;
1726
1727         const struct CaseParams
1728         {
1729                 const char*             name;
1730                 const char*             failMessage;            // customized status message
1731                 qpTestResult    failResult;                     // override status on failure
1732                 int                             op1Min, op1Max;         // operand ranges
1733                 int                             op2Min, op2Max;
1734         } cases[] =
1735         {
1736                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1737                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1738         };
1739         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1740
1741         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1742         {
1743                 const CaseParams&       params          = cases[caseNdx];
1744                 ComputeShaderSpec       spec;
1745                 vector<deInt32>         inputInts1      (numElements, 0);
1746                 vector<deInt32>         inputInts2      (numElements, 0);
1747                 vector<deInt32>         outputInts      (numElements, 0);
1748
1749                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1750                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1751
1752                 for (int ndx = 0; ndx < numElements; ++ndx)
1753                 {
1754                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1755                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1756                 }
1757
1758                 spec.assembly =
1759                         string(getComputeAsmShaderPreamble()) +
1760
1761                         "OpName %main           \"main\"\n"
1762                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1763
1764                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1765
1766                         "OpDecorate %buf BufferBlock\n"
1767                         "OpDecorate %indata1 DescriptorSet 0\n"
1768                         "OpDecorate %indata1 Binding 0\n"
1769                         "OpDecorate %indata2 DescriptorSet 0\n"
1770                         "OpDecorate %indata2 Binding 1\n"
1771                         "OpDecorate %outdata DescriptorSet 0\n"
1772                         "OpDecorate %outdata Binding 2\n"
1773                         "OpDecorate %i32arr ArrayStride 4\n"
1774                         "OpMemberDecorate %buf 0 Offset 0\n"
1775
1776                         + string(getComputeAsmCommonTypes()) +
1777
1778                         "%buf        = OpTypeStruct %i32arr\n"
1779                         "%bufptr     = OpTypePointer Uniform %buf\n"
1780                         "%indata1    = OpVariable %bufptr Uniform\n"
1781                         "%indata2    = OpVariable %bufptr Uniform\n"
1782                         "%outdata    = OpVariable %bufptr Uniform\n"
1783
1784                         "%id        = OpVariable %uvec3ptr Input\n"
1785                         "%zero      = OpConstant %i32 0\n"
1786
1787                         "%main      = OpFunction %void None %voidf\n"
1788                         "%label     = OpLabel\n"
1789                         "%idval     = OpLoad %uvec3 %id\n"
1790                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1791                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1792                         "%inval1    = OpLoad %i32 %inloc1\n"
1793                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1794                         "%inval2    = OpLoad %i32 %inloc2\n"
1795                         "%rem       = OpSRem %i32 %inval1 %inval2\n"
1796                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1797                         "             OpStore %outloc %rem\n"
1798                         "             OpReturn\n"
1799                         "             OpFunctionEnd\n";
1800
1801                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1802                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1803                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1804                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1805                 spec.failResult                 = params.failResult;
1806                 spec.failMessage                = params.failMessage;
1807
1808                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1809         }
1810
1811         return group.release();
1812 }
1813
1814 tcu::TestCaseGroup* createOpSRemComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1815 {
1816         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem64", "Test the 64-bit OpSRem instruction"));
1817         de::Random                                              rnd                             (deStringHash(group->getName()));
1818         const int                                               numElements             = 200;
1819
1820         const struct CaseParams
1821         {
1822                 const char*             name;
1823                 const char*             failMessage;            // customized status message
1824                 qpTestResult    failResult;                     // override status on failure
1825                 bool                    positive;
1826         } cases[] =
1827         {
1828                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1829                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1830         };
1831         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1832
1833         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1834         {
1835                 const CaseParams&       params          = cases[caseNdx];
1836                 ComputeShaderSpec       spec;
1837                 vector<deInt64>         inputInts1      (numElements, 0);
1838                 vector<deInt64>         inputInts2      (numElements, 0);
1839                 vector<deInt64>         outputInts      (numElements, 0);
1840
1841                 if (params.positive)
1842                 {
1843                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1844                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1845                 }
1846                 else
1847                 {
1848                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1849                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1850                 }
1851
1852                 for (int ndx = 0; ndx < numElements; ++ndx)
1853                 {
1854                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1855                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1856                 }
1857
1858                 spec.assembly =
1859                         "OpCapability Int64\n"
1860
1861                         + string(getComputeAsmShaderPreamble()) +
1862
1863                         "OpName %main           \"main\"\n"
1864                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1865
1866                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1867
1868                         "OpDecorate %buf BufferBlock\n"
1869                         "OpDecorate %indata1 DescriptorSet 0\n"
1870                         "OpDecorate %indata1 Binding 0\n"
1871                         "OpDecorate %indata2 DescriptorSet 0\n"
1872                         "OpDecorate %indata2 Binding 1\n"
1873                         "OpDecorate %outdata DescriptorSet 0\n"
1874                         "OpDecorate %outdata Binding 2\n"
1875                         "OpDecorate %i64arr ArrayStride 8\n"
1876                         "OpMemberDecorate %buf 0 Offset 0\n"
1877
1878                         + string(getComputeAsmCommonTypes())
1879                         + string(getComputeAsmCommonInt64Types()) +
1880
1881                         "%buf        = OpTypeStruct %i64arr\n"
1882                         "%bufptr     = OpTypePointer Uniform %buf\n"
1883                         "%indata1    = OpVariable %bufptr Uniform\n"
1884                         "%indata2    = OpVariable %bufptr Uniform\n"
1885                         "%outdata    = OpVariable %bufptr Uniform\n"
1886
1887                         "%id        = OpVariable %uvec3ptr Input\n"
1888                         "%zero      = OpConstant %i64 0\n"
1889
1890                         "%main      = OpFunction %void None %voidf\n"
1891                         "%label     = OpLabel\n"
1892                         "%idval     = OpLoad %uvec3 %id\n"
1893                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1894                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1895                         "%inval1    = OpLoad %i64 %inloc1\n"
1896                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1897                         "%inval2    = OpLoad %i64 %inloc2\n"
1898                         "%rem       = OpSRem %i64 %inval1 %inval2\n"
1899                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1900                         "             OpStore %outloc %rem\n"
1901                         "             OpReturn\n"
1902                         "             OpFunctionEnd\n";
1903
1904                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1905                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1906                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1907                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1908                 spec.failResult                 = params.failResult;
1909                 spec.failMessage                = params.failMessage;
1910
1911                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
1912
1913                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1914         }
1915
1916         return group.release();
1917 }
1918
1919 tcu::TestCaseGroup* createOpSModComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1920 {
1921         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod", "Test the OpSMod instruction"));
1922         de::Random                                              rnd                             (deStringHash(group->getName()));
1923         const int                                               numElements             = 200;
1924
1925         const struct CaseParams
1926         {
1927                 const char*             name;
1928                 const char*             failMessage;            // customized status message
1929                 qpTestResult    failResult;                     // override status on failure
1930                 int                             op1Min, op1Max;         // operand ranges
1931                 int                             op2Min, op2Max;
1932         } cases[] =
1933         {
1934                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1935                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1936         };
1937         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1938
1939         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1940         {
1941                 const CaseParams&       params          = cases[caseNdx];
1942
1943                 ComputeShaderSpec       spec;
1944                 vector<deInt32>         inputInts1      (numElements, 0);
1945                 vector<deInt32>         inputInts2      (numElements, 0);
1946                 vector<deInt32>         outputInts      (numElements, 0);
1947
1948                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1949                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1950
1951                 for (int ndx = 0; ndx < numElements; ++ndx)
1952                 {
1953                         deInt32 rem = inputInts1[ndx] % inputInts2[ndx];
1954                         if (rem == 0)
1955                         {
1956                                 outputInts[ndx] = 0;
1957                         }
1958                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1959                         {
1960                                 // They have the same sign
1961                                 outputInts[ndx] = rem;
1962                         }
1963                         else
1964                         {
1965                                 // They have opposite sign.  The remainder operation takes the
1966                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1967                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1968                                 // the result has the correct sign and that it is still
1969                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1970                                 //
1971                                 // See also http://mathforum.org/library/drmath/view/52343.html
1972                                 outputInts[ndx] = rem + inputInts2[ndx];
1973                         }
1974                 }
1975
1976                 spec.assembly =
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 %i32arr ArrayStride 4\n"
1992                         "OpMemberDecorate %buf 0 Offset 0\n"
1993
1994                         + string(getComputeAsmCommonTypes()) +
1995
1996                         "%buf        = OpTypeStruct %i32arr\n"
1997                         "%bufptr     = OpTypePointer Uniform %buf\n"
1998                         "%indata1    = OpVariable %bufptr Uniform\n"
1999                         "%indata2    = OpVariable %bufptr Uniform\n"
2000                         "%outdata    = OpVariable %bufptr Uniform\n"
2001
2002                         "%id        = OpVariable %uvec3ptr Input\n"
2003                         "%zero      = OpConstant %i32 0\n"
2004
2005                         "%main      = OpFunction %void None %voidf\n"
2006                         "%label     = OpLabel\n"
2007                         "%idval     = OpLoad %uvec3 %id\n"
2008                         "%x         = OpCompositeExtract %u32 %idval 0\n"
2009                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
2010                         "%inval1    = OpLoad %i32 %inloc1\n"
2011                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
2012                         "%inval2    = OpLoad %i32 %inloc2\n"
2013                         "%rem       = OpSMod %i32 %inval1 %inval2\n"
2014                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2015                         "             OpStore %outloc %rem\n"
2016                         "             OpReturn\n"
2017                         "             OpFunctionEnd\n";
2018
2019                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
2020                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
2021                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
2022                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
2023                 spec.failResult                 = params.failResult;
2024                 spec.failMessage                = params.failMessage;
2025
2026                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2027         }
2028
2029         return group.release();
2030 }
2031
2032 tcu::TestCaseGroup* createOpSModComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
2033 {
2034         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod64", "Test the OpSMod instruction"));
2035         de::Random                                              rnd                             (deStringHash(group->getName()));
2036         const int                                               numElements             = 200;
2037
2038         const struct CaseParams
2039         {
2040                 const char*             name;
2041                 const char*             failMessage;            // customized status message
2042                 qpTestResult    failResult;                     // override status on failure
2043                 bool                    positive;
2044         } cases[] =
2045         {
2046                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
2047                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
2048         };
2049         // If either operand is negative the result is undefined. Some implementations may still return correct values.
2050
2051         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
2052         {
2053                 const CaseParams&       params          = cases[caseNdx];
2054
2055                 ComputeShaderSpec       spec;
2056                 vector<deInt64>         inputInts1      (numElements, 0);
2057                 vector<deInt64>         inputInts2      (numElements, 0);
2058                 vector<deInt64>         outputInts      (numElements, 0);
2059
2060
2061                 if (params.positive)
2062                 {
2063                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
2064                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
2065                 }
2066                 else
2067                 {
2068                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
2069                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
2070                 }
2071
2072                 for (int ndx = 0; ndx < numElements; ++ndx)
2073                 {
2074                         deInt64 rem = inputInts1[ndx] % inputInts2[ndx];
2075                         if (rem == 0)
2076                         {
2077                                 outputInts[ndx] = 0;
2078                         }
2079                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
2080                         {
2081                                 // They have the same sign
2082                                 outputInts[ndx] = rem;
2083                         }
2084                         else
2085                         {
2086                                 // They have opposite sign.  The remainder operation takes the
2087                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
2088                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
2089                                 // the result has the correct sign and that it is still
2090                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
2091                                 //
2092                                 // See also http://mathforum.org/library/drmath/view/52343.html
2093                                 outputInts[ndx] = rem + inputInts2[ndx];
2094                         }
2095                 }
2096
2097                 spec.assembly =
2098                         "OpCapability Int64\n"
2099
2100                         + string(getComputeAsmShaderPreamble()) +
2101
2102                         "OpName %main           \"main\"\n"
2103                         "OpName %id             \"gl_GlobalInvocationID\"\n"
2104
2105                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
2106
2107                         "OpDecorate %buf BufferBlock\n"
2108                         "OpDecorate %indata1 DescriptorSet 0\n"
2109                         "OpDecorate %indata1 Binding 0\n"
2110                         "OpDecorate %indata2 DescriptorSet 0\n"
2111                         "OpDecorate %indata2 Binding 1\n"
2112                         "OpDecorate %outdata DescriptorSet 0\n"
2113                         "OpDecorate %outdata Binding 2\n"
2114                         "OpDecorate %i64arr ArrayStride 8\n"
2115                         "OpMemberDecorate %buf 0 Offset 0\n"
2116
2117                         + string(getComputeAsmCommonTypes())
2118                         + string(getComputeAsmCommonInt64Types()) +
2119
2120                         "%buf        = OpTypeStruct %i64arr\n"
2121                         "%bufptr     = OpTypePointer Uniform %buf\n"
2122                         "%indata1    = OpVariable %bufptr Uniform\n"
2123                         "%indata2    = OpVariable %bufptr Uniform\n"
2124                         "%outdata    = OpVariable %bufptr Uniform\n"
2125
2126                         "%id        = OpVariable %uvec3ptr Input\n"
2127                         "%zero      = OpConstant %i64 0\n"
2128
2129                         "%main      = OpFunction %void None %voidf\n"
2130                         "%label     = OpLabel\n"
2131                         "%idval     = OpLoad %uvec3 %id\n"
2132                         "%x         = OpCompositeExtract %u32 %idval 0\n"
2133                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
2134                         "%inval1    = OpLoad %i64 %inloc1\n"
2135                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
2136                         "%inval2    = OpLoad %i64 %inloc2\n"
2137                         "%rem       = OpSMod %i64 %inval1 %inval2\n"
2138                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
2139                         "             OpStore %outloc %rem\n"
2140                         "             OpReturn\n"
2141                         "             OpFunctionEnd\n";
2142
2143                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
2144                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
2145                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
2146                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
2147                 spec.failResult                 = params.failResult;
2148                 spec.failMessage                = params.failMessage;
2149
2150                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
2151
2152                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2153         }
2154
2155         return group.release();
2156 }
2157
2158 // Copy contents in the input buffer to the output buffer.
2159 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
2160 {
2161         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
2162         de::Random                                              rnd                             (deStringHash(group->getName()));
2163         const int                                               numElements             = 100;
2164
2165         // 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.
2166         ComputeShaderSpec                               spec1;
2167         vector<Vec4>                                    inputFloats1    (numElements);
2168         vector<Vec4>                                    outputFloats1   (numElements);
2169
2170         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
2171
2172         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2173         floorAll(inputFloats1);
2174
2175         for (size_t ndx = 0; ndx < numElements; ++ndx)
2176                 outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
2177
2178         spec1.assembly =
2179                 string(getComputeAsmShaderPreamble()) +
2180
2181                 "OpName %main           \"main\"\n"
2182                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2183
2184                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2185                 "OpDecorate %vec4arr ArrayStride 16\n"
2186
2187                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2188
2189                 "%vec4       = OpTypeVector %f32 4\n"
2190                 "%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
2191                 "%vec4ptr_f  = OpTypePointer Function %vec4\n"
2192                 "%vec4arr    = OpTypeRuntimeArray %vec4\n"
2193                 "%buf        = OpTypeStruct %vec4arr\n"
2194                 "%bufptr     = OpTypePointer Uniform %buf\n"
2195                 "%indata     = OpVariable %bufptr Uniform\n"
2196                 "%outdata    = OpVariable %bufptr Uniform\n"
2197
2198                 "%id         = OpVariable %uvec3ptr Input\n"
2199                 "%zero       = OpConstant %i32 0\n"
2200                 "%c_f_0      = OpConstant %f32 0.\n"
2201                 "%c_f_0_5    = OpConstant %f32 0.5\n"
2202                 "%c_f_1_5    = OpConstant %f32 1.5\n"
2203                 "%c_f_2_5    = OpConstant %f32 2.5\n"
2204                 "%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
2205
2206                 "%main       = OpFunction %void None %voidf\n"
2207                 "%label      = OpLabel\n"
2208                 "%v_vec4     = OpVariable %vec4ptr_f Function\n"
2209                 "%idval      = OpLoad %uvec3 %id\n"
2210                 "%x          = OpCompositeExtract %u32 %idval 0\n"
2211                 "%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
2212                 "%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
2213                 "              OpCopyMemory %v_vec4 %inloc\n"
2214                 "%v_vec4_val = OpLoad %vec4 %v_vec4\n"
2215                 "%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
2216                 "              OpStore %outloc %add\n"
2217                 "              OpReturn\n"
2218                 "              OpFunctionEnd\n";
2219
2220         spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
2221         spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
2222         spec1.numWorkGroups = IVec3(numElements, 1, 1);
2223
2224         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
2225
2226         // The following case copies a float[100] variable from the input buffer to the output buffer.
2227         ComputeShaderSpec                               spec2;
2228         vector<float>                                   inputFloats2    (numElements);
2229         vector<float>                                   outputFloats2   (numElements);
2230
2231         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
2232
2233         for (size_t ndx = 0; ndx < numElements; ++ndx)
2234                 outputFloats2[ndx] = inputFloats2[ndx];
2235
2236         spec2.assembly =
2237                 string(getComputeAsmShaderPreamble()) +
2238
2239                 "OpName %main           \"main\"\n"
2240                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2241
2242                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2243                 "OpDecorate %f32arr100 ArrayStride 4\n"
2244
2245                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2246
2247                 "%hundred        = OpConstant %u32 100\n"
2248                 "%f32arr100      = OpTypeArray %f32 %hundred\n"
2249                 "%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
2250                 "%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
2251                 "%buf            = OpTypeStruct %f32arr100\n"
2252                 "%bufptr         = OpTypePointer Uniform %buf\n"
2253                 "%indata         = OpVariable %bufptr Uniform\n"
2254                 "%outdata        = OpVariable %bufptr Uniform\n"
2255
2256                 "%id             = OpVariable %uvec3ptr Input\n"
2257                 "%zero           = OpConstant %i32 0\n"
2258
2259                 "%main           = OpFunction %void None %voidf\n"
2260                 "%label          = OpLabel\n"
2261                 "%var            = OpVariable %f32arr100ptr_f Function\n"
2262                 "%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
2263                 "%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
2264                 "                  OpCopyMemory %var %inarr\n"
2265                 "                  OpCopyMemory %outarr %var\n"
2266                 "                  OpReturn\n"
2267                 "                  OpFunctionEnd\n";
2268
2269         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2270         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2271         spec2.numWorkGroups = IVec3(1, 1, 1);
2272
2273         group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
2274
2275         // The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
2276         ComputeShaderSpec                               spec3;
2277         vector<float>                                   inputFloats3    (16);
2278         vector<float>                                   outputFloats3   (16);
2279
2280         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
2281
2282         for (size_t ndx = 0; ndx < 16; ++ndx)
2283                 outputFloats3[ndx] = inputFloats3[ndx];
2284
2285         spec3.assembly =
2286                 string(getComputeAsmShaderPreamble()) +
2287
2288                 "OpName %main           \"main\"\n"
2289                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2290
2291                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2292                 //"OpMemberDecorate %buf 0 Offset 0\n"  - exists in getComputeAsmInputOutputBufferTraits
2293                 "OpMemberDecorate %buf 1 Offset 16\n"
2294                 "OpMemberDecorate %buf 2 Offset 32\n"
2295                 "OpMemberDecorate %buf 3 Offset 48\n"
2296
2297                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2298
2299                 "%vec4      = OpTypeVector %f32 4\n"
2300                 "%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
2301                 "%bufptr    = OpTypePointer Uniform %buf\n"
2302                 "%indata    = OpVariable %bufptr Uniform\n"
2303                 "%outdata   = OpVariable %bufptr Uniform\n"
2304                 "%vec4stptr = OpTypePointer Function %buf\n"
2305
2306                 "%id        = OpVariable %uvec3ptr Input\n"
2307                 "%zero      = OpConstant %i32 0\n"
2308
2309                 "%main      = OpFunction %void None %voidf\n"
2310                 "%label     = OpLabel\n"
2311                 "%var       = OpVariable %vec4stptr Function\n"
2312                 "             OpCopyMemory %var %indata\n"
2313                 "             OpCopyMemory %outdata %var\n"
2314                 "             OpReturn\n"
2315                 "             OpFunctionEnd\n";
2316
2317         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2318         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
2319         spec3.numWorkGroups = IVec3(1, 1, 1);
2320
2321         group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
2322
2323         // The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
2324         ComputeShaderSpec                               spec4;
2325         vector<float>                                   inputFloats4    (numElements);
2326         vector<float>                                   outputFloats4   (numElements);
2327
2328         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
2329
2330         for (size_t ndx = 0; ndx < numElements; ++ndx)
2331                 outputFloats4[ndx] = -inputFloats4[ndx];
2332
2333         spec4.assembly =
2334                 string(getComputeAsmShaderPreamble()) +
2335
2336                 "OpName %main           \"main\"\n"
2337                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2338
2339                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2340
2341                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2342
2343                 "%f32ptr_f  = OpTypePointer Function %f32\n"
2344                 "%id        = OpVariable %uvec3ptr Input\n"
2345                 "%zero      = OpConstant %i32 0\n"
2346
2347                 "%main      = OpFunction %void None %voidf\n"
2348                 "%label     = OpLabel\n"
2349                 "%var       = OpVariable %f32ptr_f Function\n"
2350                 "%idval     = OpLoad %uvec3 %id\n"
2351                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2352                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2353                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2354                 "             OpCopyMemory %var %inloc\n"
2355                 "%val       = OpLoad %f32 %var\n"
2356                 "%neg       = OpFNegate %f32 %val\n"
2357                 "             OpStore %outloc %neg\n"
2358                 "             OpReturn\n"
2359                 "             OpFunctionEnd\n";
2360
2361         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2362         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
2363         spec4.numWorkGroups = IVec3(numElements, 1, 1);
2364
2365         group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
2366
2367         return group.release();
2368 }
2369
2370 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
2371 {
2372         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
2373         ComputeShaderSpec                               spec;
2374         de::Random                                              rnd                             (deStringHash(group->getName()));
2375         const int                                               numElements             = 100;
2376         vector<float>                                   inputFloats             (numElements, 0);
2377         vector<float>                                   outputFloats    (numElements, 0);
2378
2379         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2380
2381         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2382         floorAll(inputFloats);
2383
2384         for (size_t ndx = 0; ndx < numElements; ++ndx)
2385                 outputFloats[ndx] = inputFloats[ndx] + 7.5f;
2386
2387         spec.assembly =
2388                 string(getComputeAsmShaderPreamble()) +
2389
2390                 "OpName %main           \"main\"\n"
2391                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2392
2393                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2394
2395                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2396
2397                 "%fmat     = OpTypeMatrix %fvec3 3\n"
2398                 "%three    = OpConstant %u32 3\n"
2399                 "%farr     = OpTypeArray %f32 %three\n"
2400                 "%fst      = OpTypeStruct %f32 %f32\n"
2401
2402                 + string(getComputeAsmInputOutputBuffer()) +
2403
2404                 "%id            = OpVariable %uvec3ptr Input\n"
2405                 "%zero          = OpConstant %i32 0\n"
2406                 "%c_f           = OpConstant %f32 1.5\n"
2407                 "%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
2408                 "%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
2409                 "%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
2410                 "%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
2411
2412                 "%main          = OpFunction %void None %voidf\n"
2413                 "%label         = OpLabel\n"
2414                 "%c_f_copy      = OpCopyObject %f32   %c_f\n"
2415                 "%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
2416                 "%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
2417                 "%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
2418                 "%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
2419                 "%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
2420                 "%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
2421                 "%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
2422                 "%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
2423                 // Add up. 1.5 * 5 = 7.5.
2424                 "%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
2425                 "%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
2426                 "%add3          = OpFAdd %f32 %add2     %farr_elem\n"
2427                 "%add4          = OpFAdd %f32 %add3     %fst_elem\n"
2428
2429                 "%idval         = OpLoad %uvec3 %id\n"
2430                 "%x             = OpCompositeExtract %u32 %idval 0\n"
2431                 "%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
2432                 "%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
2433                 "%inval         = OpLoad %f32 %inloc\n"
2434                 "%add           = OpFAdd %f32 %add4 %inval\n"
2435                 "                 OpStore %outloc %add\n"
2436                 "                 OpReturn\n"
2437                 "                 OpFunctionEnd\n";
2438         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2439         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2440         spec.numWorkGroups = IVec3(numElements, 1, 1);
2441
2442         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
2443
2444         return group.release();
2445 }
2446 // Assembly code used for testing OpUnreachable is based on GLSL source code:
2447 //
2448 // #version 430
2449 //
2450 // layout(std140, set = 0, binding = 0) readonly buffer Input {
2451 //   float elements[];
2452 // } input_data;
2453 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
2454 //   float elements[];
2455 // } output_data;
2456 //
2457 // void not_called_func() {
2458 //   // place OpUnreachable here
2459 // }
2460 //
2461 // uint modulo4(uint val) {
2462 //   switch (val % uint(4)) {
2463 //     case 0:  return 3;
2464 //     case 1:  return 2;
2465 //     case 2:  return 1;
2466 //     case 3:  return 0;
2467 //     default: return 100; // place OpUnreachable here
2468 //   }
2469 // }
2470 //
2471 // uint const5() {
2472 //   return 5;
2473 //   // place OpUnreachable here
2474 // }
2475 //
2476 // void main() {
2477 //   uint x = gl_GlobalInvocationID.x;
2478 //   if (const5() > modulo4(1000)) {
2479 //     output_data.elements[x] = -input_data.elements[x];
2480 //   } else {
2481 //     // place OpUnreachable here
2482 //     output_data.elements[x] = input_data.elements[x];
2483 //   }
2484 // }
2485
2486 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
2487 {
2488         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
2489         ComputeShaderSpec                               spec;
2490         de::Random                                              rnd                             (deStringHash(group->getName()));
2491         const int                                               numElements             = 100;
2492         vector<float>                                   positiveFloats  (numElements, 0);
2493         vector<float>                                   negativeFloats  (numElements, 0);
2494
2495         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2496
2497         for (size_t ndx = 0; ndx < numElements; ++ndx)
2498                 negativeFloats[ndx] = -positiveFloats[ndx];
2499
2500         spec.assembly =
2501                 string(getComputeAsmShaderPreamble()) +
2502
2503                 "OpSource GLSL 430\n"
2504                 "OpName %main            \"main\"\n"
2505                 "OpName %func_not_called_func \"not_called_func(\"\n"
2506                 "OpName %func_modulo4         \"modulo4(u1;\"\n"
2507                 "OpName %func_const5          \"const5(\"\n"
2508                 "OpName %id                   \"gl_GlobalInvocationID\"\n"
2509
2510                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2511
2512                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2513
2514                 "%u32ptr    = OpTypePointer Function %u32\n"
2515                 "%uintfuint = OpTypeFunction %u32 %u32ptr\n"
2516                 "%unitf     = OpTypeFunction %u32\n"
2517
2518                 "%id        = OpVariable %uvec3ptr Input\n"
2519                 "%zero      = OpConstant %u32 0\n"
2520                 "%one       = OpConstant %u32 1\n"
2521                 "%two       = OpConstant %u32 2\n"
2522                 "%three     = OpConstant %u32 3\n"
2523                 "%four      = OpConstant %u32 4\n"
2524                 "%five      = OpConstant %u32 5\n"
2525                 "%hundred   = OpConstant %u32 100\n"
2526                 "%thousand  = OpConstant %u32 1000\n"
2527
2528                 + string(getComputeAsmInputOutputBuffer()) +
2529
2530                 // Main()
2531                 "%main   = OpFunction %void None %voidf\n"
2532                 "%main_entry  = OpLabel\n"
2533                 "%v_thousand  = OpVariable %u32ptr Function %thousand\n"
2534                 "%idval       = OpLoad %uvec3 %id\n"
2535                 "%x           = OpCompositeExtract %u32 %idval 0\n"
2536                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
2537                 "%inval       = OpLoad %f32 %inloc\n"
2538                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
2539                 "%ret_const5  = OpFunctionCall %u32 %func_const5\n"
2540                 "%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
2541                 "%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
2542                 "               OpSelectionMerge %if_end None\n"
2543                 "               OpBranchConditional %cmp_gt %if_true %if_false\n"
2544                 "%if_true     = OpLabel\n"
2545                 "%negate      = OpFNegate %f32 %inval\n"
2546                 "               OpStore %outloc %negate\n"
2547                 "               OpBranch %if_end\n"
2548                 "%if_false    = OpLabel\n"
2549                 "               OpUnreachable\n" // Unreachable else branch for if statement
2550                 "%if_end      = OpLabel\n"
2551                 "               OpReturn\n"
2552                 "               OpFunctionEnd\n"
2553
2554                 // not_called_function()
2555                 "%func_not_called_func  = OpFunction %void None %voidf\n"
2556                 "%not_called_func_entry = OpLabel\n"
2557                 "                         OpUnreachable\n" // Unreachable entry block in not called static function
2558                 "                         OpFunctionEnd\n"
2559
2560                 // modulo4()
2561                 "%func_modulo4  = OpFunction %u32 None %uintfuint\n"
2562                 "%valptr        = OpFunctionParameter %u32ptr\n"
2563                 "%modulo4_entry = OpLabel\n"
2564                 "%val           = OpLoad %u32 %valptr\n"
2565                 "%modulo        = OpUMod %u32 %val %four\n"
2566                 "                 OpSelectionMerge %switch_merge None\n"
2567                 "                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
2568                 "%case0         = OpLabel\n"
2569                 "                 OpReturnValue %three\n"
2570                 "%case1         = OpLabel\n"
2571                 "                 OpReturnValue %two\n"
2572                 "%case2         = OpLabel\n"
2573                 "                 OpReturnValue %one\n"
2574                 "%case3         = OpLabel\n"
2575                 "                 OpReturnValue %zero\n"
2576                 "%default       = OpLabel\n"
2577                 "                 OpUnreachable\n" // Unreachable default case for switch statement
2578                 "%switch_merge  = OpLabel\n"
2579                 "                 OpUnreachable\n" // Unreachable merge block for switch statement
2580                 "                 OpFunctionEnd\n"
2581
2582                 // const5()
2583                 "%func_const5  = OpFunction %u32 None %unitf\n"
2584                 "%const5_entry = OpLabel\n"
2585                 "                OpReturnValue %five\n"
2586                 "%unreachable  = OpLabel\n"
2587                 "                OpUnreachable\n" // Unreachable block in function
2588                 "                OpFunctionEnd\n";
2589         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2590         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2591         spec.numWorkGroups = IVec3(numElements, 1, 1);
2592
2593         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
2594
2595         return group.release();
2596 }
2597
2598 // Assembly code used for testing decoration group is based on GLSL source code:
2599 //
2600 // #version 430
2601 //
2602 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
2603 //   float elements[];
2604 // } input_data0;
2605 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
2606 //   float elements[];
2607 // } input_data1;
2608 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
2609 //   float elements[];
2610 // } input_data2;
2611 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
2612 //   float elements[];
2613 // } input_data3;
2614 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
2615 //   float elements[];
2616 // } input_data4;
2617 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
2618 //   float elements[];
2619 // } output_data;
2620 //
2621 // void main() {
2622 //   uint x = gl_GlobalInvocationID.x;
2623 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
2624 // }
2625 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
2626 {
2627         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
2628         ComputeShaderSpec                               spec;
2629         de::Random                                              rnd                             (deStringHash(group->getName()));
2630         const int                                               numElements             = 100;
2631         vector<float>                                   inputFloats0    (numElements, 0);
2632         vector<float>                                   inputFloats1    (numElements, 0);
2633         vector<float>                                   inputFloats2    (numElements, 0);
2634         vector<float>                                   inputFloats3    (numElements, 0);
2635         vector<float>                                   inputFloats4    (numElements, 0);
2636         vector<float>                                   outputFloats    (numElements, 0);
2637
2638         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
2639         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
2640         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
2641         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
2642         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
2643
2644         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2645         floorAll(inputFloats0);
2646         floorAll(inputFloats1);
2647         floorAll(inputFloats2);
2648         floorAll(inputFloats3);
2649         floorAll(inputFloats4);
2650
2651         for (size_t ndx = 0; ndx < numElements; ++ndx)
2652                 outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
2653
2654         spec.assembly =
2655                 string(getComputeAsmShaderPreamble()) +
2656
2657                 "OpSource GLSL 430\n"
2658                 "OpName %main \"main\"\n"
2659                 "OpName %id \"gl_GlobalInvocationID\"\n"
2660
2661                 // Not using group decoration on variable.
2662                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2663                 // Not using group decoration on type.
2664                 "OpDecorate %f32arr ArrayStride 4\n"
2665
2666                 "OpDecorate %groups BufferBlock\n"
2667                 "OpDecorate %groupm Offset 0\n"
2668                 "%groups = OpDecorationGroup\n"
2669                 "%groupm = OpDecorationGroup\n"
2670
2671                 // Group decoration on multiple structs.
2672                 "OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
2673                 // Group decoration on multiple struct members.
2674                 "OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
2675
2676                 "OpDecorate %group1 DescriptorSet 0\n"
2677                 "OpDecorate %group3 DescriptorSet 0\n"
2678                 "OpDecorate %group3 NonWritable\n"
2679                 "OpDecorate %group3 Restrict\n"
2680                 "%group0 = OpDecorationGroup\n"
2681                 "%group1 = OpDecorationGroup\n"
2682                 "%group3 = OpDecorationGroup\n"
2683
2684                 // Applying the same decoration group multiple times.
2685                 "OpGroupDecorate %group1 %outdata\n"
2686                 "OpGroupDecorate %group1 %outdata\n"
2687                 "OpGroupDecorate %group1 %outdata\n"
2688                 "OpDecorate %outdata DescriptorSet 0\n"
2689                 "OpDecorate %outdata Binding 5\n"
2690                 // Applying decoration group containing nothing.
2691                 "OpGroupDecorate %group0 %indata0\n"
2692                 "OpDecorate %indata0 DescriptorSet 0\n"
2693                 "OpDecorate %indata0 Binding 0\n"
2694                 // Applying decoration group containing one decoration.
2695                 "OpGroupDecorate %group1 %indata1\n"
2696                 "OpDecorate %indata1 Binding 1\n"
2697                 // Applying decoration group containing multiple decorations.
2698                 "OpGroupDecorate %group3 %indata2 %indata3\n"
2699                 "OpDecorate %indata2 Binding 2\n"
2700                 "OpDecorate %indata3 Binding 3\n"
2701                 // Applying multiple decoration groups (with overlapping).
2702                 "OpGroupDecorate %group0 %indata4\n"
2703                 "OpGroupDecorate %group1 %indata4\n"
2704                 "OpGroupDecorate %group3 %indata4\n"
2705                 "OpDecorate %indata4 Binding 4\n"
2706
2707                 + string(getComputeAsmCommonTypes()) +
2708
2709                 "%id   = OpVariable %uvec3ptr Input\n"
2710                 "%zero = OpConstant %i32 0\n"
2711
2712                 "%outbuf    = OpTypeStruct %f32arr\n"
2713                 "%outbufptr = OpTypePointer Uniform %outbuf\n"
2714                 "%outdata   = OpVariable %outbufptr Uniform\n"
2715                 "%inbuf0    = OpTypeStruct %f32arr\n"
2716                 "%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
2717                 "%indata0   = OpVariable %inbuf0ptr Uniform\n"
2718                 "%inbuf1    = OpTypeStruct %f32arr\n"
2719                 "%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
2720                 "%indata1   = OpVariable %inbuf1ptr Uniform\n"
2721                 "%inbuf2    = OpTypeStruct %f32arr\n"
2722                 "%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
2723                 "%indata2   = OpVariable %inbuf2ptr Uniform\n"
2724                 "%inbuf3    = OpTypeStruct %f32arr\n"
2725                 "%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
2726                 "%indata3   = OpVariable %inbuf3ptr Uniform\n"
2727                 "%inbuf4    = OpTypeStruct %f32arr\n"
2728                 "%inbufptr  = OpTypePointer Uniform %inbuf4\n"
2729                 "%indata4   = OpVariable %inbufptr Uniform\n"
2730
2731                 "%main   = OpFunction %void None %voidf\n"
2732                 "%label  = OpLabel\n"
2733                 "%idval  = OpLoad %uvec3 %id\n"
2734                 "%x      = OpCompositeExtract %u32 %idval 0\n"
2735                 "%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
2736                 "%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
2737                 "%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
2738                 "%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
2739                 "%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
2740                 "%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
2741                 "%inval0 = OpLoad %f32 %inloc0\n"
2742                 "%inval1 = OpLoad %f32 %inloc1\n"
2743                 "%inval2 = OpLoad %f32 %inloc2\n"
2744                 "%inval3 = OpLoad %f32 %inloc3\n"
2745                 "%inval4 = OpLoad %f32 %inloc4\n"
2746                 "%add0   = OpFAdd %f32 %inval0 %inval1\n"
2747                 "%add1   = OpFAdd %f32 %add0 %inval2\n"
2748                 "%add2   = OpFAdd %f32 %add1 %inval3\n"
2749                 "%add    = OpFAdd %f32 %add2 %inval4\n"
2750                 "          OpStore %outloc %add\n"
2751                 "          OpReturn\n"
2752                 "          OpFunctionEnd\n";
2753         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
2754         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
2755         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2756         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2757         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2758         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2759         spec.numWorkGroups = IVec3(numElements, 1, 1);
2760
2761         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
2762
2763         return group.release();
2764 }
2765
2766 struct SpecConstantTwoIntCase
2767 {
2768         const char*             caseName;
2769         const char*             scDefinition0;
2770         const char*             scDefinition1;
2771         const char*             scResultType;
2772         const char*             scOperation;
2773         deInt32                 scActualValue0;
2774         deInt32                 scActualValue1;
2775         const char*             resultOperation;
2776         vector<deInt32> expectedOutput;
2777         deInt32                 scActualValueLength;
2778
2779                                         SpecConstantTwoIntCase (const char* name,
2780                                                                                         const char* definition0,
2781                                                                                         const char* definition1,
2782                                                                                         const char* resultType,
2783                                                                                         const char* operation,
2784                                                                                         deInt32 value0,
2785                                                                                         deInt32 value1,
2786                                                                                         const char* resultOp,
2787                                                                                         const vector<deInt32>& output,
2788                                                                                         const deInt32   valueLength = sizeof(deInt32))
2789                                                 : caseName                              (name)
2790                                                 , scDefinition0                 (definition0)
2791                                                 , scDefinition1                 (definition1)
2792                                                 , scResultType                  (resultType)
2793                                                 , scOperation                   (operation)
2794                                                 , scActualValue0                (value0)
2795                                                 , scActualValue1                (value1)
2796                                                 , resultOperation               (resultOp)
2797                                                 , expectedOutput                (output)
2798                                                 , scActualValueLength   (valueLength)
2799                                                 {}
2800 };
2801
2802 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
2803 {
2804         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
2805         vector<SpecConstantTwoIntCase>  cases;
2806         de::Random                                              rnd                             (deStringHash(group->getName()));
2807         const int                                               numElements             = 100;
2808         const deInt32                                   p1AsFloat16             = 0x3c00; // +1(fp16) == 0 01111 0000000000 == 0011 1100 0000 0000
2809         vector<deInt32>                                 inputInts               (numElements, 0);
2810         vector<deInt32>                                 outputInts1             (numElements, 0);
2811         vector<deInt32>                                 outputInts2             (numElements, 0);
2812         vector<deInt32>                                 outputInts3             (numElements, 0);
2813         vector<deInt32>                                 outputInts4             (numElements, 0);
2814         const StringTemplate                    shaderTemplate  (
2815                 "${CAPABILITIES:opt}"
2816                 + string(getComputeAsmShaderPreamble()) +
2817
2818                 "OpName %main           \"main\"\n"
2819                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2820
2821                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2822                 "OpDecorate %sc_0  SpecId 0\n"
2823                 "OpDecorate %sc_1  SpecId 1\n"
2824                 "OpDecorate %i32arr ArrayStride 4\n"
2825
2826                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2827
2828                 "${OPTYPE_DEFINITIONS:opt}"
2829                 "%buf     = OpTypeStruct %i32arr\n"
2830                 "%bufptr  = OpTypePointer Uniform %buf\n"
2831                 "%indata    = OpVariable %bufptr Uniform\n"
2832                 "%outdata   = OpVariable %bufptr Uniform\n"
2833
2834                 "%id        = OpVariable %uvec3ptr Input\n"
2835                 "%zero      = OpConstant %i32 0\n"
2836
2837                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
2838                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
2839                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2840
2841                 "%main      = OpFunction %void None %voidf\n"
2842                 "%label     = OpLabel\n"
2843                 "${TYPE_CONVERT:opt}"
2844                 "%idval     = OpLoad %uvec3 %id\n"
2845                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2846                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2847                 "%inval     = OpLoad %i32 %inloc\n"
2848                 "%final     = ${GEN_RESULT}\n"
2849                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2850                 "             OpStore %outloc %final\n"
2851                 "             OpReturn\n"
2852                 "             OpFunctionEnd\n");
2853
2854         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2855
2856         for (size_t ndx = 0; ndx < numElements; ++ndx)
2857         {
2858                 outputInts1[ndx] = inputInts[ndx] + 42;
2859                 outputInts2[ndx] = inputInts[ndx];
2860                 outputInts3[ndx] = inputInts[ndx] - 11200;
2861                 outputInts4[ndx] = inputInts[ndx] + 1;
2862         }
2863
2864         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
2865         const char addSc32ToInput[]             = "OpIAdd %i32 %inval %sc_final32";
2866         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
2867         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
2868
2869         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
2870         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
2871         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
2872         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
2873         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
2874         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2875         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2876         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
2877         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
2878         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
2879         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
2880         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2881         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2882         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
2883         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
2884         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
2885         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2886         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
2887         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
2888         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
2889         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2890         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
2891         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
2892         cases.push_back(SpecConstantTwoIntCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                     42,             24,             selectTrueUsingSc,      outputInts2));
2893         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2894         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2895         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2896         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2897         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
2898         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
2899         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
2900         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
2901         cases.push_back(SpecConstantTwoIntCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                           -11200, 0,              addSc32ToInput,         outputInts3));
2902         // -969998336 stored as 32-bit two's complement is the binary representation of -11200 as IEEE-754 Float
2903         cases.push_back(SpecConstantTwoIntCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                           -969998336, 0,  addSc32ToInput,         outputInts3));
2904         cases.push_back(SpecConstantTwoIntCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                           p1AsFloat16, 0, addSc32ToInput,         outputInts4, sizeof(deFloat16)));
2905
2906         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2907         {
2908                 map<string, string>             specializations;
2909                 ComputeShaderSpec               spec;
2910
2911                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
2912                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
2913                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
2914                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
2915                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
2916
2917                 // Special SPIR-V code for SConvert-case
2918                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
2919                 {
2920                         spec.requestedVulkanFeatures.coreFeatures.shaderInt16   = VK_TRUE;
2921                         specializations["CAPABILITIES"]                                                 = "OpCapability Int16\n";                                                       // Adds 16-bit integer capability
2922                         specializations["OPTYPE_DEFINITIONS"]                                   = "%i16 = OpTypeInt 16 1\n";                                            // Adds 16-bit integer type
2923                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpSConvert %i32 %sc_final\n";          // Converts 16-bit integer to 32-bit integer
2924                 }
2925
2926                 // Special SPIR-V code for FConvert-case
2927                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
2928                 {
2929                         spec.requestedVulkanFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
2930                         specializations["CAPABILITIES"]                                                 = "OpCapability Float64\n";                                                     // Adds 64-bit float capability
2931                         specializations["OPTYPE_DEFINITIONS"]                                   = "%f64 = OpTypeFloat 64\n";                                            // Adds 64-bit float type
2932                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 64-bit float to 32-bit integer
2933                 }
2934
2935                 // Special SPIR-V code for FConvert-case for 16-bit floats
2936                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
2937                 {
2938                         spec.extensions.push_back("VK_KHR_shader_float16_int8");
2939                         spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
2940                         specializations["CAPABILITIES"]                 = "OpCapability Float16\n";                                                     // Adds 16-bit float capability
2941                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                                            // Adds 16-bit float type
2942                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 16-bit float to 32-bit integer
2943                 }
2944
2945                 spec.assembly = shaderTemplate.specialize(specializations);
2946                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2947                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2948                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2949                 spec.specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
2950                 spec.specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
2951
2952                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec));
2953         }
2954
2955         ComputeShaderSpec                               spec;
2956
2957         spec.assembly =
2958                 string(getComputeAsmShaderPreamble()) +
2959
2960                 "OpName %main           \"main\"\n"
2961                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2962
2963                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2964                 "OpDecorate %sc_0  SpecId 0\n"
2965                 "OpDecorate %sc_1  SpecId 1\n"
2966                 "OpDecorate %sc_2  SpecId 2\n"
2967                 "OpDecorate %i32arr ArrayStride 4\n"
2968
2969                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2970
2971                 "%ivec3       = OpTypeVector %i32 3\n"
2972                 "%buf         = OpTypeStruct %i32arr\n"
2973                 "%bufptr      = OpTypePointer Uniform %buf\n"
2974                 "%indata      = OpVariable %bufptr Uniform\n"
2975                 "%outdata     = OpVariable %bufptr Uniform\n"
2976
2977                 "%id          = OpVariable %uvec3ptr Input\n"
2978                 "%zero        = OpConstant %i32 0\n"
2979                 "%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
2980                 "%vec3_undef  = OpUndef %ivec3\n"
2981
2982                 "%sc_0        = OpSpecConstant %i32 0\n"
2983                 "%sc_1        = OpSpecConstant %i32 0\n"
2984                 "%sc_2        = OpSpecConstant %i32 0\n"
2985                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"                                                 // (sc_0, 0, 0)
2986                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"                                                 // (0, sc_1, 0)
2987                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"                                                 // (0, 0, sc_2)
2988                 "%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
2989                 "%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
2990                 "%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
2991                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
2992                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
2993                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
2994                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
2995                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
2996                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
2997                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"                                                              // (sc_2 - sc_0) * sc_1
2998
2999                 "%main      = OpFunction %void None %voidf\n"
3000                 "%label     = OpLabel\n"
3001                 "%idval     = OpLoad %uvec3 %id\n"
3002                 "%x         = OpCompositeExtract %u32 %idval 0\n"
3003                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
3004                 "%inval     = OpLoad %i32 %inloc\n"
3005                 "%final     = OpIAdd %i32 %inval %sc_final\n"
3006                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
3007                 "             OpStore %outloc %final\n"
3008                 "             OpReturn\n"
3009                 "             OpFunctionEnd\n";
3010         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
3011         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
3012         spec.numWorkGroups = IVec3(numElements, 1, 1);
3013         spec.specConstants.append<deInt32>(123);
3014         spec.specConstants.append<deInt32>(56);
3015         spec.specConstants.append<deInt32>(-77);
3016
3017         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
3018
3019         return group.release();
3020 }
3021
3022 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
3023 {
3024         ComputeShaderSpec       specInt;
3025         ComputeShaderSpec       specFloat;
3026         ComputeShaderSpec       specFloat16;
3027         ComputeShaderSpec       specVec3;
3028         ComputeShaderSpec       specMat4;
3029         ComputeShaderSpec       specArray;
3030         ComputeShaderSpec       specStruct;
3031         de::Random                      rnd                             (deStringHash(group->getName()));
3032         const int                       numElements             = 100;
3033         vector<float>           inputFloats             (numElements, 0);
3034         vector<float>           outputFloats    (numElements, 0);
3035         vector<deFloat16>       inputFloats16   (numElements, 0);
3036         vector<deFloat16>       outputFloats16  (numElements, 0);
3037
3038         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3039
3040         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3041         floorAll(inputFloats);
3042
3043         for (size_t ndx = 0; ndx < numElements; ++ndx)
3044         {
3045                 // Just check if the value is positive or not
3046                 outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
3047         }
3048
3049         for (size_t ndx = 0; ndx < numElements; ++ndx)
3050         {
3051                 inputFloats16[ndx] = tcu::Float16(inputFloats[ndx]).bits();
3052                 outputFloats16[ndx] = tcu::Float16(outputFloats[ndx]).bits();
3053         }
3054
3055         // All of the tests are of the form:
3056         //
3057         // testtype r
3058         //
3059         // if (inputdata > 0)
3060         //   r = 1
3061         // else
3062         //   r = -1
3063         //
3064         // return (float)r
3065
3066         specFloat.assembly =
3067                 string(getComputeAsmShaderPreamble()) +
3068
3069                 "OpSource GLSL 430\n"
3070                 "OpName %main \"main\"\n"
3071                 "OpName %id \"gl_GlobalInvocationID\"\n"
3072
3073                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3074
3075                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3076
3077                 "%id = OpVariable %uvec3ptr Input\n"
3078                 "%zero       = OpConstant %i32 0\n"
3079                 "%float_0    = OpConstant %f32 0.0\n"
3080                 "%float_1    = OpConstant %f32 1.0\n"
3081                 "%float_n1   = OpConstant %f32 -1.0\n"
3082
3083                 "%main     = OpFunction %void None %voidf\n"
3084                 "%entry    = OpLabel\n"
3085                 "%idval    = OpLoad %uvec3 %id\n"
3086                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3087                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3088                 "%inval    = OpLoad %f32 %inloc\n"
3089
3090                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3091                 "            OpSelectionMerge %cm None\n"
3092                 "            OpBranchConditional %comp %tb %fb\n"
3093                 "%tb       = OpLabel\n"
3094                 "            OpBranch %cm\n"
3095                 "%fb       = OpLabel\n"
3096                 "            OpBranch %cm\n"
3097                 "%cm       = OpLabel\n"
3098                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
3099
3100                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3101                 "            OpStore %outloc %res\n"
3102                 "            OpReturn\n"
3103
3104                 "            OpFunctionEnd\n";
3105         specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3106         specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3107         specFloat.numWorkGroups = IVec3(numElements, 1, 1);
3108
3109         specFloat16.assembly =
3110                 "OpCapability Shader\n"
3111                 "OpCapability StorageUniformBufferBlock16\n"
3112                 "OpExtension \"SPV_KHR_16bit_storage\"\n"
3113                 "OpMemoryModel Logical GLSL450\n"
3114                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3115                 "OpExecutionMode %main LocalSize 1 1 1\n"
3116
3117                 "OpSource GLSL 430\n"
3118                 "OpName %main \"main\"\n"
3119                 "OpName %id \"gl_GlobalInvocationID\"\n"
3120
3121                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3122
3123                 "OpDecorate %buf BufferBlock\n"
3124                 "OpDecorate %indata DescriptorSet 0\n"
3125                 "OpDecorate %indata Binding 0\n"
3126                 "OpDecorate %outdata DescriptorSet 0\n"
3127                 "OpDecorate %outdata Binding 1\n"
3128                 "OpDecorate %f16arr ArrayStride 2\n"
3129                 "OpMemberDecorate %buf 0 Offset 0\n"
3130
3131                 "%f16      = OpTypeFloat 16\n"
3132                 "%f16ptr   = OpTypePointer Uniform %f16\n"
3133                 "%f16arr   = OpTypeRuntimeArray %f16\n"
3134
3135                 + string(getComputeAsmCommonTypes()) +
3136
3137                 "%buf      = OpTypeStruct %f16arr\n"
3138                 "%bufptr   = OpTypePointer Uniform %buf\n"
3139                 "%indata   = OpVariable %bufptr Uniform\n"
3140                 "%outdata  = OpVariable %bufptr Uniform\n"
3141
3142                 "%id       = OpVariable %uvec3ptr Input\n"
3143                 "%zero     = OpConstant %i32 0\n"
3144                 "%float_0  = OpConstant %f32 0.0\n"
3145                 "%float_1  = OpConstant %f32 1.0\n"
3146                 "%float_n1 = OpConstant %f32 -1.0\n"
3147
3148                 "%main     = OpFunction %void None %voidf\n"
3149                 "%entry    = OpLabel\n"
3150                 "%idval    = OpLoad %uvec3 %id\n"
3151                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3152                 "%inloc    = OpAccessChain %f16ptr %indata %zero %x\n"
3153                 "%inval    = OpLoad %f16 %inloc\n"
3154                 "%f32_inval = OpFConvert %f32 %inval\n"
3155
3156                 "%comp     = OpFOrdGreaterThan %bool %f32_inval %float_0\n"
3157                 "            OpSelectionMerge %cm None\n"
3158                 "            OpBranchConditional %comp %tb %fb\n"
3159                 "%tb       = OpLabel\n"
3160                 "            OpBranch %cm\n"
3161                 "%fb       = OpLabel\n"
3162                 "            OpBranch %cm\n"
3163                 "%cm       = OpLabel\n"
3164                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
3165                 "%f16_res  = OpFConvert %f16 %res\n"
3166
3167                 "%outloc   = OpAccessChain %f16ptr %outdata %zero %x\n"
3168                 "            OpStore %outloc %f16_res\n"
3169                 "            OpReturn\n"
3170
3171                 "            OpFunctionEnd\n";
3172         specFloat16.inputs.push_back(BufferSp(new Float16Buffer(inputFloats16)));
3173         specFloat16.outputs.push_back(BufferSp(new Float16Buffer(outputFloats16)));
3174         specFloat16.numWorkGroups = IVec3(numElements, 1, 1);
3175         specFloat16.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
3176         specFloat16.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
3177
3178         specMat4.assembly =
3179                 string(getComputeAsmShaderPreamble()) +
3180
3181                 "OpSource GLSL 430\n"
3182                 "OpName %main \"main\"\n"
3183                 "OpName %id \"gl_GlobalInvocationID\"\n"
3184
3185                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3186
3187                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3188
3189                 "%id = OpVariable %uvec3ptr Input\n"
3190                 "%v4f32      = OpTypeVector %f32 4\n"
3191                 "%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
3192                 "%zero       = OpConstant %i32 0\n"
3193                 "%float_0    = OpConstant %f32 0.0\n"
3194                 "%float_1    = OpConstant %f32 1.0\n"
3195                 "%float_n1   = OpConstant %f32 -1.0\n"
3196                 "%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
3197                 "%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
3198                 "%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
3199                 "%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
3200                 "%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
3201                 "%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
3202                 "%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
3203                 "%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
3204                 "%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
3205                 "%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
3206
3207                 "%main     = OpFunction %void None %voidf\n"
3208                 "%entry    = OpLabel\n"
3209                 "%idval    = OpLoad %uvec3 %id\n"
3210                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3211                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3212                 "%inval    = OpLoad %f32 %inloc\n"
3213
3214                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3215                 "            OpSelectionMerge %cm None\n"
3216                 "            OpBranchConditional %comp %tb %fb\n"
3217                 "%tb       = OpLabel\n"
3218                 "            OpBranch %cm\n"
3219                 "%fb       = OpLabel\n"
3220                 "            OpBranch %cm\n"
3221                 "%cm       = OpLabel\n"
3222                 "%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
3223                 "%res      = OpCompositeExtract %f32 %mres 2 2\n"
3224
3225                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3226                 "            OpStore %outloc %res\n"
3227                 "            OpReturn\n"
3228
3229                 "            OpFunctionEnd\n";
3230         specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3231         specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3232         specMat4.numWorkGroups = IVec3(numElements, 1, 1);
3233
3234         specVec3.assembly =
3235                 string(getComputeAsmShaderPreamble()) +
3236
3237                 "OpSource GLSL 430\n"
3238                 "OpName %main \"main\"\n"
3239                 "OpName %id \"gl_GlobalInvocationID\"\n"
3240
3241                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3242
3243                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3244
3245                 "%id = OpVariable %uvec3ptr Input\n"
3246                 "%zero       = OpConstant %i32 0\n"
3247                 "%float_0    = OpConstant %f32 0.0\n"
3248                 "%float_1    = OpConstant %f32 1.0\n"
3249                 "%float_n1   = OpConstant %f32 -1.0\n"
3250                 "%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
3251                 "%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
3252
3253                 "%main     = OpFunction %void None %voidf\n"
3254                 "%entry    = OpLabel\n"
3255                 "%idval    = OpLoad %uvec3 %id\n"
3256                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3257                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3258                 "%inval    = OpLoad %f32 %inloc\n"
3259
3260                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3261                 "            OpSelectionMerge %cm None\n"
3262                 "            OpBranchConditional %comp %tb %fb\n"
3263                 "%tb       = OpLabel\n"
3264                 "            OpBranch %cm\n"
3265                 "%fb       = OpLabel\n"
3266                 "            OpBranch %cm\n"
3267                 "%cm       = OpLabel\n"
3268                 "%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
3269                 "%res      = OpCompositeExtract %f32 %vres 2\n"
3270
3271                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3272                 "            OpStore %outloc %res\n"
3273                 "            OpReturn\n"
3274
3275                 "            OpFunctionEnd\n";
3276         specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3277         specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3278         specVec3.numWorkGroups = IVec3(numElements, 1, 1);
3279
3280         specInt.assembly =
3281                 string(getComputeAsmShaderPreamble()) +
3282
3283                 "OpSource GLSL 430\n"
3284                 "OpName %main \"main\"\n"
3285                 "OpName %id \"gl_GlobalInvocationID\"\n"
3286
3287                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3288
3289                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3290
3291                 "%id = OpVariable %uvec3ptr Input\n"
3292                 "%zero       = OpConstant %i32 0\n"
3293                 "%float_0    = OpConstant %f32 0.0\n"
3294                 "%i1         = OpConstant %i32 1\n"
3295                 "%i2         = OpConstant %i32 -1\n"
3296
3297                 "%main     = OpFunction %void None %voidf\n"
3298                 "%entry    = OpLabel\n"
3299                 "%idval    = OpLoad %uvec3 %id\n"
3300                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3301                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3302                 "%inval    = OpLoad %f32 %inloc\n"
3303
3304                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3305                 "            OpSelectionMerge %cm None\n"
3306                 "            OpBranchConditional %comp %tb %fb\n"
3307                 "%tb       = OpLabel\n"
3308                 "            OpBranch %cm\n"
3309                 "%fb       = OpLabel\n"
3310                 "            OpBranch %cm\n"
3311                 "%cm       = OpLabel\n"
3312                 "%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
3313                 "%res      = OpConvertSToF %f32 %ires\n"
3314
3315                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3316                 "            OpStore %outloc %res\n"
3317                 "            OpReturn\n"
3318
3319                 "            OpFunctionEnd\n";
3320         specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3321         specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3322         specInt.numWorkGroups = IVec3(numElements, 1, 1);
3323
3324         specArray.assembly =
3325                 string(getComputeAsmShaderPreamble()) +
3326
3327                 "OpSource GLSL 430\n"
3328                 "OpName %main \"main\"\n"
3329                 "OpName %id \"gl_GlobalInvocationID\"\n"
3330
3331                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3332
3333                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3334
3335                 "%id = OpVariable %uvec3ptr Input\n"
3336                 "%zero       = OpConstant %i32 0\n"
3337                 "%u7         = OpConstant %u32 7\n"
3338                 "%float_0    = OpConstant %f32 0.0\n"
3339                 "%float_1    = OpConstant %f32 1.0\n"
3340                 "%float_n1   = OpConstant %f32 -1.0\n"
3341                 "%f32a7      = OpTypeArray %f32 %u7\n"
3342                 "%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
3343                 "%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
3344                 "%main     = OpFunction %void None %voidf\n"
3345                 "%entry    = OpLabel\n"
3346                 "%idval    = OpLoad %uvec3 %id\n"
3347                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3348                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3349                 "%inval    = OpLoad %f32 %inloc\n"
3350
3351                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3352                 "            OpSelectionMerge %cm None\n"
3353                 "            OpBranchConditional %comp %tb %fb\n"
3354                 "%tb       = OpLabel\n"
3355                 "            OpBranch %cm\n"
3356                 "%fb       = OpLabel\n"
3357                 "            OpBranch %cm\n"
3358                 "%cm       = OpLabel\n"
3359                 "%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
3360                 "%res      = OpCompositeExtract %f32 %ares 5\n"
3361
3362                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3363                 "            OpStore %outloc %res\n"
3364                 "            OpReturn\n"
3365
3366                 "            OpFunctionEnd\n";
3367         specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3368         specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3369         specArray.numWorkGroups = IVec3(numElements, 1, 1);
3370
3371         specStruct.assembly =
3372                 string(getComputeAsmShaderPreamble()) +
3373
3374                 "OpSource GLSL 430\n"
3375                 "OpName %main \"main\"\n"
3376                 "OpName %id \"gl_GlobalInvocationID\"\n"
3377
3378                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3379
3380                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3381
3382                 "%id = OpVariable %uvec3ptr Input\n"
3383                 "%zero       = OpConstant %i32 0\n"
3384                 "%float_0    = OpConstant %f32 0.0\n"
3385                 "%float_1    = OpConstant %f32 1.0\n"
3386                 "%float_n1   = OpConstant %f32 -1.0\n"
3387
3388                 "%v2f32      = OpTypeVector %f32 2\n"
3389                 "%Data2      = OpTypeStruct %f32 %v2f32\n"
3390                 "%Data       = OpTypeStruct %Data2 %f32\n"
3391
3392                 "%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
3393                 "%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
3394                 "%s1         = OpConstantComposite %Data %in1b %float_1\n"
3395                 "%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
3396                 "%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
3397                 "%s2         = OpConstantComposite %Data %in2b %float_n1\n"
3398
3399                 "%main     = OpFunction %void None %voidf\n"
3400                 "%entry    = OpLabel\n"
3401                 "%idval    = OpLoad %uvec3 %id\n"
3402                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3403                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3404                 "%inval    = OpLoad %f32 %inloc\n"
3405
3406                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3407                 "            OpSelectionMerge %cm None\n"
3408                 "            OpBranchConditional %comp %tb %fb\n"
3409                 "%tb       = OpLabel\n"
3410                 "            OpBranch %cm\n"
3411                 "%fb       = OpLabel\n"
3412                 "            OpBranch %cm\n"
3413                 "%cm       = OpLabel\n"
3414                 "%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
3415                 "%res      = OpCompositeExtract %f32 %sres 0 0\n"
3416
3417                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3418                 "            OpStore %outloc %res\n"
3419                 "            OpReturn\n"
3420
3421                 "            OpFunctionEnd\n";
3422         specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3423         specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3424         specStruct.numWorkGroups = IVec3(numElements, 1, 1);
3425
3426         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
3427         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
3428         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float16", "OpPhi with 16bit float variables", specFloat16));
3429         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
3430         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
3431         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
3432         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
3433 }
3434
3435 string generateConstantDefinitions (int count)
3436 {
3437         std::ostringstream      r;
3438         for (int i = 0; i < count; i++)
3439                 r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
3440         r << "\n";
3441         return r.str();
3442 }
3443
3444 string generateSwitchCases (int count)
3445 {
3446         std::ostringstream      r;
3447         for (int i = 0; i < count; i++)
3448                 r << " " << i << " %case" << i;
3449         r << "\n";
3450         return r.str();
3451 }
3452
3453 string generateSwitchTargets (int count)
3454 {
3455         std::ostringstream      r;
3456         for (int i = 0; i < count; i++)
3457                 r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3458         r << "\n";
3459         return r.str();
3460 }
3461
3462 string generateOpPhiParams (int count)
3463 {
3464         std::ostringstream      r;
3465         for (int i = 0; i < count; i++)
3466                 r << " %cf" << (i * 10 + 5) << " %case" << i;
3467         r << "\n";
3468         return r.str();
3469 }
3470
3471 string generateIntWidth (int value)
3472 {
3473         std::ostringstream      r;
3474         r << value;
3475         return r.str();
3476 }
3477
3478 // Expand input string by injecting "ABC" between the input
3479 // string characters. The acc/add/treshold parameters are used
3480 // to skip some of the injections to make the result less
3481 // uniform (and a lot shorter).
3482 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3483 {
3484         std::ostringstream      res;
3485         const char*                     p = s.c_str();
3486
3487         while (*p)
3488         {
3489                 res << *p;
3490                 acc += add;
3491                 if (acc > treshold)
3492                 {
3493                         acc -= treshold;
3494                         res << "ABC";
3495                 }
3496                 p++;
3497         }
3498         return res.str();
3499 }
3500
3501 // Calculate expected result based on the code string
3502 float calcOpPhiCase5 (float val, const string& s)
3503 {
3504         const char*             p               = s.c_str();
3505         float                   x[8];
3506         bool                    b[8];
3507         const float             tv[8]   = { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3508         const float             v               = deFloatAbs(val);
3509         float                   res             = 0;
3510         int                             depth   = -1;
3511         int                             skip    = 0;
3512
3513         for (int i = 7; i >= 0; --i)
3514                 x[i] = std::fmod((float)v, (float)(2 << i));
3515         for (int i = 7; i >= 0; --i)
3516                 b[i] = x[i] > tv[i];
3517
3518         while (*p)
3519         {
3520                 if (*p == 'A')
3521                 {
3522                         depth++;
3523                         if (skip == 0 && b[depth])
3524                         {
3525                                 res++;
3526                         }
3527                         else
3528                                 skip++;
3529                 }
3530                 if (*p == 'B')
3531                 {
3532                         if (skip)
3533                                 skip--;
3534                         if (b[depth] || skip)
3535                                 skip++;
3536                 }
3537                 if (*p == 'C')
3538                 {
3539                         depth--;
3540                         if (skip)
3541                                 skip--;
3542                 }
3543                 p++;
3544         }
3545         return res;
3546 }
3547
3548 // In the code string, the letters represent the following:
3549 //
3550 // A:
3551 //     if (certain bit is set)
3552 //     {
3553 //       result++;
3554 //
3555 // B:
3556 //     } else {
3557 //
3558 // C:
3559 //     }
3560 //
3561 // examples:
3562 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3563 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3564 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3565 //
3566 // Code generation gets a bit complicated due to the else-branches,
3567 // which do not generate new values. Thus, the generator needs to
3568 // keep track of the previous variable change seen by the else
3569 // branch.
3570 string generateOpPhiCase5 (const string& s)
3571 {
3572         std::stack<int>                         idStack;
3573         std::stack<std::string>         value;
3574         std::stack<std::string>         valueLabel;
3575         std::stack<std::string>         mergeLeft;
3576         std::stack<std::string>         mergeRight;
3577         std::ostringstream                      res;
3578         const char*                                     p                       = s.c_str();
3579         int                                                     depth           = -1;
3580         int                                                     currId          = 0;
3581         int                                                     iter            = 0;
3582
3583         idStack.push(-1);
3584         value.push("%f32_0");
3585         valueLabel.push("%f32_0 %entry");
3586
3587         while (*p)
3588         {
3589                 if (*p == 'A')
3590                 {
3591                         depth++;
3592                         currId = iter;
3593                         idStack.push(currId);
3594                         res << "\tOpSelectionMerge %m" << currId << " None\n";
3595                         res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3596                         res << "%t" << currId << " = OpLabel\n";
3597                         res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3598                         std::ostringstream tag;
3599                         tag << "%rt" << currId;
3600                         value.push(tag.str());
3601                         tag << " %t" << currId;
3602                         valueLabel.push(tag.str());
3603                 }
3604
3605                 if (*p == 'B')
3606                 {
3607                         mergeLeft.push(valueLabel.top());
3608                         value.pop();
3609                         valueLabel.pop();
3610                         res << "\tOpBranch %m" << currId << "\n";
3611                         res << "%f" << currId << " = OpLabel\n";
3612                         std::ostringstream tag;
3613                         tag << value.top() << " %f" << currId;
3614                         valueLabel.pop();
3615                         valueLabel.push(tag.str());
3616                 }
3617
3618                 if (*p == 'C')
3619                 {
3620                         mergeRight.push(valueLabel.top());
3621                         res << "\tOpBranch %m" << currId << "\n";
3622                         res << "%m" << currId << " = OpLabel\n";
3623                         if (*(p + 1) == 0)
3624                                 res << "%res"; // last result goes to %res
3625                         else
3626                                 res << "%rm" << currId;
3627                         res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3628                         std::ostringstream tag;
3629                         tag << "%rm" << currId;
3630                         value.pop();
3631                         value.push(tag.str());
3632                         tag << " %m" << currId;
3633                         valueLabel.pop();
3634                         valueLabel.push(tag.str());
3635                         mergeLeft.pop();
3636                         mergeRight.pop();
3637                         depth--;
3638                         idStack.pop();
3639                         currId = idStack.top();
3640                 }
3641                 p++;
3642                 iter++;
3643         }
3644         return res.str();
3645 }
3646
3647 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3648 {
3649         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3650         ComputeShaderSpec                               spec1;
3651         ComputeShaderSpec                               spec2;
3652         ComputeShaderSpec                               spec3;
3653         ComputeShaderSpec                               spec4;
3654         ComputeShaderSpec                               spec5;
3655         de::Random                                              rnd                             (deStringHash(group->getName()));
3656         const int                                               numElements             = 100;
3657         vector<float>                                   inputFloats             (numElements, 0);
3658         vector<float>                                   outputFloats1   (numElements, 0);
3659         vector<float>                                   outputFloats2   (numElements, 0);
3660         vector<float>                                   outputFloats3   (numElements, 0);
3661         vector<float>                                   outputFloats4   (numElements, 0);
3662         vector<float>                                   outputFloats5   (numElements, 0);
3663         std::string                                             codestring              = "ABC";
3664         const int                                               test4Width              = 1024;
3665
3666         // Build case 5 code string. Each iteration makes the hierarchy more complicated.
3667         // 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3668         // shader code.
3669         for (int i = 0, acc = 0; i < 9; i++)
3670                 codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3671
3672         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3673
3674         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3675         floorAll(inputFloats);
3676
3677         for (size_t ndx = 0; ndx < numElements; ++ndx)
3678         {
3679                 switch (ndx % 3)
3680                 {
3681                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
3682                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
3683                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
3684                         default:        break;
3685                 }
3686                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3687                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3688
3689                 int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3690                 outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3691
3692                 outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3693         }
3694
3695         spec1.assembly =
3696                 string(getComputeAsmShaderPreamble()) +
3697
3698                 "OpSource GLSL 430\n"
3699                 "OpName %main \"main\"\n"
3700                 "OpName %id \"gl_GlobalInvocationID\"\n"
3701
3702                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3703
3704                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3705
3706                 "%id = OpVariable %uvec3ptr Input\n"
3707                 "%zero       = OpConstant %i32 0\n"
3708                 "%three      = OpConstant %u32 3\n"
3709                 "%constf5p5  = OpConstant %f32 5.5\n"
3710                 "%constf20p5 = OpConstant %f32 20.5\n"
3711                 "%constf1p75 = OpConstant %f32 1.75\n"
3712                 "%constf8p5  = OpConstant %f32 8.5\n"
3713                 "%constf6p5  = OpConstant %f32 6.5\n"
3714
3715                 "%main     = OpFunction %void None %voidf\n"
3716                 "%entry    = OpLabel\n"
3717                 "%idval    = OpLoad %uvec3 %id\n"
3718                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3719                 "%selector = OpUMod %u32 %x %three\n"
3720                 "            OpSelectionMerge %phi None\n"
3721                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3722
3723                 // Case 1 before OpPhi.
3724                 "%case1    = OpLabel\n"
3725                 "            OpBranch %phi\n"
3726
3727                 "%default  = OpLabel\n"
3728                 "            OpUnreachable\n"
3729
3730                 "%phi      = OpLabel\n"
3731                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3732                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3733                 "%inval    = OpLoad %f32 %inloc\n"
3734                 "%add      = OpFAdd %f32 %inval %operand\n"
3735                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3736                 "            OpStore %outloc %add\n"
3737                 "            OpReturn\n"
3738
3739                 // Case 0 after OpPhi.
3740                 "%case0    = OpLabel\n"
3741                 "            OpBranch %phi\n"
3742
3743
3744                 // Case 2 after OpPhi.
3745                 "%case2    = OpLabel\n"
3746                 "            OpBranch %phi\n"
3747
3748                 "            OpFunctionEnd\n";
3749         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3750         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3751         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3752
3753         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3754
3755         spec2.assembly =
3756                 string(getComputeAsmShaderPreamble()) +
3757
3758                 "OpName %main \"main\"\n"
3759                 "OpName %id \"gl_GlobalInvocationID\"\n"
3760
3761                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3762
3763                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3764
3765                 "%id         = OpVariable %uvec3ptr Input\n"
3766                 "%zero       = OpConstant %i32 0\n"
3767                 "%one        = OpConstant %i32 1\n"
3768                 "%three      = OpConstant %i32 3\n"
3769                 "%constf6p5  = OpConstant %f32 6.5\n"
3770
3771                 "%main       = OpFunction %void None %voidf\n"
3772                 "%entry      = OpLabel\n"
3773                 "%idval      = OpLoad %uvec3 %id\n"
3774                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3775                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3776                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3777                 "%inval      = OpLoad %f32 %inloc\n"
3778                 "              OpBranch %phi\n"
3779
3780                 "%phi        = OpLabel\n"
3781                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3782                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3783                 "%step_next  = OpIAdd %i32 %step %one\n"
3784                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3785                 "%still_loop = OpSLessThan %bool %step %three\n"
3786                 "              OpLoopMerge %exit %phi None\n"
3787                 "              OpBranchConditional %still_loop %phi %exit\n"
3788
3789                 "%exit       = OpLabel\n"
3790                 "              OpStore %outloc %accum\n"
3791                 "              OpReturn\n"
3792                 "              OpFunctionEnd\n";
3793         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3794         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3795         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3796
3797         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3798
3799         spec3.assembly =
3800                 string(getComputeAsmShaderPreamble()) +
3801
3802                 "OpName %main \"main\"\n"
3803                 "OpName %id \"gl_GlobalInvocationID\"\n"
3804
3805                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3806
3807                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3808
3809                 "%f32ptr_f   = OpTypePointer Function %f32\n"
3810                 "%id         = OpVariable %uvec3ptr Input\n"
3811                 "%true       = OpConstantTrue %bool\n"
3812                 "%false      = OpConstantFalse %bool\n"
3813                 "%zero       = OpConstant %i32 0\n"
3814                 "%constf8p5  = OpConstant %f32 8.5\n"
3815
3816                 "%main       = OpFunction %void None %voidf\n"
3817                 "%entry      = OpLabel\n"
3818                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3819                 "%idval      = OpLoad %uvec3 %id\n"
3820                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3821                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3822                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3823                 "%a_init     = OpLoad %f32 %inloc\n"
3824                 "%b_init     = OpLoad %f32 %b\n"
3825                 "              OpBranch %phi\n"
3826
3827                 "%phi        = OpLabel\n"
3828                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3829                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3830                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3831                 "              OpLoopMerge %exit %phi None\n"
3832                 "              OpBranchConditional %still_loop %phi %exit\n"
3833
3834                 "%exit       = OpLabel\n"
3835                 "%sub        = OpFSub %f32 %a_next %b_next\n"
3836                 "              OpStore %outloc %sub\n"
3837                 "              OpReturn\n"
3838                 "              OpFunctionEnd\n";
3839         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3840         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3841         spec3.numWorkGroups = IVec3(numElements, 1, 1);
3842
3843         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3844
3845         spec4.assembly =
3846                 "OpCapability Shader\n"
3847                 "%ext = OpExtInstImport \"GLSL.std.450\"\n"
3848                 "OpMemoryModel Logical GLSL450\n"
3849                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3850                 "OpExecutionMode %main LocalSize 1 1 1\n"
3851
3852                 "OpSource GLSL 430\n"
3853                 "OpName %main \"main\"\n"
3854                 "OpName %id \"gl_GlobalInvocationID\"\n"
3855
3856                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3857
3858                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3859
3860                 "%id       = OpVariable %uvec3ptr Input\n"
3861                 "%zero     = OpConstant %i32 0\n"
3862                 "%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3863
3864                 + generateConstantDefinitions(test4Width) +
3865
3866                 "%main     = OpFunction %void None %voidf\n"
3867                 "%entry    = OpLabel\n"
3868                 "%idval    = OpLoad %uvec3 %id\n"
3869                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3870                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3871                 "%inval    = OpLoad %f32 %inloc\n"
3872                 "%xf       = OpConvertUToF %f32 %x\n"
3873                 "%xm       = OpFMul %f32 %xf %inval\n"
3874                 "%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3875                 "%xi       = OpConvertFToU %u32 %xa\n"
3876                 "%selector = OpUMod %u32 %xi %cimod\n"
3877                 "            OpSelectionMerge %phi None\n"
3878                 "            OpSwitch %selector %default "
3879
3880                 + generateSwitchCases(test4Width) +
3881
3882                 "%default  = OpLabel\n"
3883                 "            OpUnreachable\n"
3884
3885                 + generateSwitchTargets(test4Width) +
3886
3887                 "%phi      = OpLabel\n"
3888                 "%result   = OpPhi %f32"
3889
3890                 + generateOpPhiParams(test4Width) +
3891
3892                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3893                 "            OpStore %outloc %result\n"
3894                 "            OpReturn\n"
3895
3896                 "            OpFunctionEnd\n";
3897         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3898         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3899         spec4.numWorkGroups = IVec3(numElements, 1, 1);
3900
3901         group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3902
3903         spec5.assembly =
3904                 "OpCapability Shader\n"
3905                 "%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3906                 "OpMemoryModel Logical GLSL450\n"
3907                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3908                 "OpExecutionMode %main LocalSize 1 1 1\n"
3909                 "%code     = OpString \"" + codestring + "\"\n"
3910
3911                 "OpSource GLSL 430\n"
3912                 "OpName %main \"main\"\n"
3913                 "OpName %id \"gl_GlobalInvocationID\"\n"
3914
3915                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3916
3917                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3918
3919                 "%id       = OpVariable %uvec3ptr Input\n"
3920                 "%zero     = OpConstant %i32 0\n"
3921                 "%f32_0    = OpConstant %f32 0.0\n"
3922                 "%f32_0_5  = OpConstant %f32 0.5\n"
3923                 "%f32_1    = OpConstant %f32 1.0\n"
3924                 "%f32_1_5  = OpConstant %f32 1.5\n"
3925                 "%f32_2    = OpConstant %f32 2.0\n"
3926                 "%f32_3_5  = OpConstant %f32 3.5\n"
3927                 "%f32_4    = OpConstant %f32 4.0\n"
3928                 "%f32_7_5  = OpConstant %f32 7.5\n"
3929                 "%f32_8    = OpConstant %f32 8.0\n"
3930                 "%f32_15_5 = OpConstant %f32 15.5\n"
3931                 "%f32_16   = OpConstant %f32 16.0\n"
3932                 "%f32_31_5 = OpConstant %f32 31.5\n"
3933                 "%f32_32   = OpConstant %f32 32.0\n"
3934                 "%f32_63_5 = OpConstant %f32 63.5\n"
3935                 "%f32_64   = OpConstant %f32 64.0\n"
3936                 "%f32_127_5 = OpConstant %f32 127.5\n"
3937                 "%f32_128  = OpConstant %f32 128.0\n"
3938                 "%f32_256  = OpConstant %f32 256.0\n"
3939
3940                 "%main     = OpFunction %void None %voidf\n"
3941                 "%entry    = OpLabel\n"
3942                 "%idval    = OpLoad %uvec3 %id\n"
3943                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3944                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3945                 "%inval    = OpLoad %f32 %inloc\n"
3946
3947                 "%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3948                 "%x8       = OpFMod %f32 %xabs %f32_256\n"
3949                 "%x7       = OpFMod %f32 %xabs %f32_128\n"
3950                 "%x6       = OpFMod %f32 %xabs %f32_64\n"
3951                 "%x5       = OpFMod %f32 %xabs %f32_32\n"
3952                 "%x4       = OpFMod %f32 %xabs %f32_16\n"
3953                 "%x3       = OpFMod %f32 %xabs %f32_8\n"
3954                 "%x2       = OpFMod %f32 %xabs %f32_4\n"
3955                 "%x1       = OpFMod %f32 %xabs %f32_2\n"
3956
3957                 "%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3958                 "%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3959                 "%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3960                 "%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3961                 "%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3962                 "%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3963                 "%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3964                 "%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3965
3966                 + generateOpPhiCase5(codestring) +
3967
3968                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3969                 "            OpStore %outloc %res\n"
3970                 "            OpReturn\n"
3971
3972                 "            OpFunctionEnd\n";
3973         spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3974         spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
3975         spec5.numWorkGroups = IVec3(numElements, 1, 1);
3976
3977         group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
3978
3979         createOpPhiVartypeTests(group, testCtx);
3980
3981         return group.release();
3982 }
3983
3984 // Assembly code used for testing block order is based on GLSL source code:
3985 //
3986 // #version 430
3987 //
3988 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3989 //   float elements[];
3990 // } input_data;
3991 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3992 //   float elements[];
3993 // } output_data;
3994 //
3995 // void main() {
3996 //   uint x = gl_GlobalInvocationID.x;
3997 //   output_data.elements[x] = input_data.elements[x];
3998 //   if (x > uint(50)) {
3999 //     switch (x % uint(3)) {
4000 //       case 0: output_data.elements[x] += 1.5f; break;
4001 //       case 1: output_data.elements[x] += 42.f; break;
4002 //       case 2: output_data.elements[x] -= 27.f; break;
4003 //       default: break;
4004 //     }
4005 //   } else {
4006 //     output_data.elements[x] = -input_data.elements[x];
4007 //   }
4008 // }
4009 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
4010 {
4011         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
4012         ComputeShaderSpec                               spec;
4013         de::Random                                              rnd                             (deStringHash(group->getName()));
4014         const int                                               numElements             = 100;
4015         vector<float>                                   inputFloats             (numElements, 0);
4016         vector<float>                                   outputFloats    (numElements, 0);
4017
4018         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
4019
4020         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
4021         floorAll(inputFloats);
4022
4023         for (size_t ndx = 0; ndx <= 50; ++ndx)
4024                 outputFloats[ndx] = -inputFloats[ndx];
4025
4026         for (size_t ndx = 51; ndx < numElements; ++ndx)
4027         {
4028                 switch (ndx % 3)
4029                 {
4030                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
4031                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
4032                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
4033                         default:        break;
4034                 }
4035         }
4036
4037         spec.assembly =
4038                 string(getComputeAsmShaderPreamble()) +
4039
4040                 "OpSource GLSL 430\n"
4041                 "OpName %main \"main\"\n"
4042                 "OpName %id \"gl_GlobalInvocationID\"\n"
4043
4044                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4045
4046                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4047
4048                 "%u32ptr       = OpTypePointer Function %u32\n"
4049                 "%u32ptr_input = OpTypePointer Input %u32\n"
4050
4051                 + string(getComputeAsmInputOutputBuffer()) +
4052
4053                 "%id        = OpVariable %uvec3ptr Input\n"
4054                 "%zero      = OpConstant %i32 0\n"
4055                 "%const3    = OpConstant %u32 3\n"
4056                 "%const50   = OpConstant %u32 50\n"
4057                 "%constf1p5 = OpConstant %f32 1.5\n"
4058                 "%constf27  = OpConstant %f32 27.0\n"
4059                 "%constf42  = OpConstant %f32 42.0\n"
4060
4061                 "%main = OpFunction %void None %voidf\n"
4062
4063                 // entry block.
4064                 "%entry    = OpLabel\n"
4065
4066                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
4067                 "%xvar     = OpVariable %u32ptr Function\n"
4068                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
4069                 "%x        = OpLoad %u32 %xptr\n"
4070                 "            OpStore %xvar %x\n"
4071
4072                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
4073                 "            OpSelectionMerge %if_merge None\n"
4074                 "            OpBranchConditional %cmp %if_true %if_false\n"
4075
4076                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
4077                 "%if_false = OpLabel\n"
4078                 "%x_f      = OpLoad %u32 %xvar\n"
4079                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
4080                 "%inval_f  = OpLoad %f32 %inloc_f\n"
4081                 "%negate   = OpFNegate %f32 %inval_f\n"
4082                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
4083                 "            OpStore %outloc_f %negate\n"
4084                 "            OpBranch %if_merge\n"
4085
4086                 // Merge block for if-statement: placed in the middle of true and false branch.
4087                 "%if_merge = OpLabel\n"
4088                 "            OpReturn\n"
4089
4090                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
4091                 "%if_true  = OpLabel\n"
4092                 "%xval_t   = OpLoad %u32 %xvar\n"
4093                 "%mod      = OpUMod %u32 %xval_t %const3\n"
4094                 "            OpSelectionMerge %switch_merge None\n"
4095                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
4096
4097                 // Merge block for switch-statement: placed before the case
4098                 // bodies.  But it must follow OpSwitch which dominates it.
4099                 "%switch_merge = OpLabel\n"
4100                 "                OpBranch %if_merge\n"
4101
4102                 // Case 1 for switch-statement: placed before case 0.
4103                 // It must follow the OpSwitch that dominates it.
4104                 "%case1    = OpLabel\n"
4105                 "%x_1      = OpLoad %u32 %xvar\n"
4106                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
4107                 "%inval_1  = OpLoad %f32 %inloc_1\n"
4108                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
4109                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
4110                 "            OpStore %outloc_1 %addf42\n"
4111                 "            OpBranch %switch_merge\n"
4112
4113                 // Case 2 for switch-statement.
4114                 "%case2    = OpLabel\n"
4115                 "%x_2      = OpLoad %u32 %xvar\n"
4116                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
4117                 "%inval_2  = OpLoad %f32 %inloc_2\n"
4118                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
4119                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
4120                 "            OpStore %outloc_2 %subf27\n"
4121                 "            OpBranch %switch_merge\n"
4122
4123                 // Default case for switch-statement: placed in the middle of normal cases.
4124                 "%default = OpLabel\n"
4125                 "           OpBranch %switch_merge\n"
4126
4127                 // Case 0 for switch-statement: out of order.
4128                 "%case0    = OpLabel\n"
4129                 "%x_0      = OpLoad %u32 %xvar\n"
4130                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
4131                 "%inval_0  = OpLoad %f32 %inloc_0\n"
4132                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
4133                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
4134                 "            OpStore %outloc_0 %addf1p5\n"
4135                 "            OpBranch %switch_merge\n"
4136
4137                 "            OpFunctionEnd\n";
4138         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4139         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4140         spec.numWorkGroups = IVec3(numElements, 1, 1);
4141
4142         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
4143
4144         return group.release();
4145 }
4146
4147 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
4148 {
4149         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
4150         ComputeShaderSpec                               spec1;
4151         ComputeShaderSpec                               spec2;
4152         de::Random                                              rnd                             (deStringHash(group->getName()));
4153         const int                                               numElements             = 100;
4154         vector<float>                                   inputFloats             (numElements, 0);
4155         vector<float>                                   outputFloats1   (numElements, 0);
4156         vector<float>                                   outputFloats2   (numElements, 0);
4157         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
4158
4159         for (size_t ndx = 0; ndx < numElements; ++ndx)
4160         {
4161                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
4162                 outputFloats2[ndx] = -inputFloats[ndx];
4163         }
4164
4165         const string assembly(
4166                 "OpCapability Shader\n"
4167                 "OpMemoryModel Logical GLSL450\n"
4168                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
4169                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
4170                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
4171                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
4172                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
4173                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
4174
4175                 "OpName %comp_main1              \"entrypoint1\"\n"
4176                 "OpName %comp_main2              \"entrypoint2\"\n"
4177                 "OpName %vert_main               \"entrypoint2\"\n"
4178                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
4179                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
4180                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
4181                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
4182                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
4183                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
4184                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
4185
4186                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
4187                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
4188                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
4189                 "OpDecorate %vert_builtin_st         Block\n"
4190                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
4191                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
4192                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
4193
4194                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4195
4196                 "%zero       = OpConstant %i32 0\n"
4197                 "%one        = OpConstant %u32 1\n"
4198                 "%c_f32_1    = OpConstant %f32 1\n"
4199
4200                 "%i32inputptr         = OpTypePointer Input %i32\n"
4201                 "%vec4                = OpTypeVector %f32 4\n"
4202                 "%vec4ptr             = OpTypePointer Output %vec4\n"
4203                 "%f32arr1             = OpTypeArray %f32 %one\n"
4204                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
4205                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
4206                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
4207
4208                 "%id         = OpVariable %uvec3ptr Input\n"
4209                 "%vertexIndex = OpVariable %i32inputptr Input\n"
4210                 "%instanceIndex = OpVariable %i32inputptr Input\n"
4211                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
4212
4213                 // gl_Position = vec4(1.);
4214                 "%vert_main  = OpFunction %void None %voidf\n"
4215                 "%vert_entry = OpLabel\n"
4216                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
4217                 "              OpStore %position %c_vec4_1\n"
4218                 "              OpReturn\n"
4219                 "              OpFunctionEnd\n"
4220
4221                 // Double inputs.
4222                 "%comp_main1  = OpFunction %void None %voidf\n"
4223                 "%comp1_entry = OpLabel\n"
4224                 "%idval1      = OpLoad %uvec3 %id\n"
4225                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
4226                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
4227                 "%inval1      = OpLoad %f32 %inloc1\n"
4228                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
4229                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
4230                 "               OpStore %outloc1 %add\n"
4231                 "               OpReturn\n"
4232                 "               OpFunctionEnd\n"
4233
4234                 // Negate inputs.
4235                 "%comp_main2  = OpFunction %void None %voidf\n"
4236                 "%comp2_entry = OpLabel\n"
4237                 "%idval2      = OpLoad %uvec3 %id\n"
4238                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
4239                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
4240                 "%inval2      = OpLoad %f32 %inloc2\n"
4241                 "%neg         = OpFNegate %f32 %inval2\n"
4242                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
4243                 "               OpStore %outloc2 %neg\n"
4244                 "               OpReturn\n"
4245                 "               OpFunctionEnd\n");
4246
4247         spec1.assembly = assembly;
4248         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4249         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
4250         spec1.numWorkGroups = IVec3(numElements, 1, 1);
4251         spec1.entryPoint = "entrypoint1";
4252
4253         spec2.assembly = assembly;
4254         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4255         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
4256         spec2.numWorkGroups = IVec3(numElements, 1, 1);
4257         spec2.entryPoint = "entrypoint2";
4258
4259         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
4260         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
4261
4262         return group.release();
4263 }
4264
4265 inline std::string makeLongUTF8String (size_t num4ByteChars)
4266 {
4267         // An example of a longest valid UTF-8 character.  Be explicit about the
4268         // character type because Microsoft compilers can otherwise interpret the
4269         // character string as being over wide (16-bit) characters. Ideally, we
4270         // would just use a C++11 UTF-8 string literal, but we want to support older
4271         // Microsoft compilers.
4272         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
4273         std::string longString;
4274         longString.reserve(num4ByteChars * 4);
4275         for (size_t count = 0; count < num4ByteChars; count++)
4276         {
4277                 longString += earthAfrica;
4278         }
4279         return longString;
4280 }
4281
4282 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
4283 {
4284         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
4285         vector<CaseParameter>                   cases;
4286         de::Random                                              rnd                             (deStringHash(group->getName()));
4287         const int                                               numElements             = 100;
4288         vector<float>                                   positiveFloats  (numElements, 0);
4289         vector<float>                                   negativeFloats  (numElements, 0);
4290         const StringTemplate                    shaderTemplate  (
4291                 "OpCapability Shader\n"
4292                 "OpMemoryModel Logical GLSL450\n"
4293
4294                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4295                 "OpExecutionMode %main LocalSize 1 1 1\n"
4296
4297                 "${SOURCE}\n"
4298
4299                 "OpName %main           \"main\"\n"
4300                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4301
4302                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4303
4304                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4305
4306                 "%id        = OpVariable %uvec3ptr Input\n"
4307                 "%zero      = OpConstant %i32 0\n"
4308
4309                 "%main      = OpFunction %void None %voidf\n"
4310                 "%label     = OpLabel\n"
4311                 "%idval     = OpLoad %uvec3 %id\n"
4312                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4313                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4314                 "%inval     = OpLoad %f32 %inloc\n"
4315                 "%neg       = OpFNegate %f32 %inval\n"
4316                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4317                 "             OpStore %outloc %neg\n"
4318                 "             OpReturn\n"
4319                 "             OpFunctionEnd\n");
4320
4321         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
4322         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
4323         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
4324                                                                                                                                                         "OpSource GLSL 430 %fname"));
4325         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
4326                                                                                                                                                         "OpSource GLSL 430 %fname"));
4327         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
4328                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
4329         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
4330                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
4331         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
4332                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
4333         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
4334                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
4335         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
4336                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
4337                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
4338         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4339                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4340                                                                                                                                                         "OpSourceContinued \"\""));
4341         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4342                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4343                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
4344         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4345                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4346                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
4347         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4348                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
4349                                                                                                                                                         "OpSourceContinued \"void\"\n"
4350                                                                                                                                                         "OpSourceContinued \"main()\"\n"
4351                                                                                                                                                         "OpSourceContinued \"{}\""));
4352         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
4353                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
4354                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
4355
4356         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4357
4358         for (size_t ndx = 0; ndx < numElements; ++ndx)
4359                 negativeFloats[ndx] = -positiveFloats[ndx];
4360
4361         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4362         {
4363                 map<string, string>             specializations;
4364                 ComputeShaderSpec               spec;
4365
4366                 specializations["SOURCE"] = cases[caseNdx].param;
4367                 spec.assembly = shaderTemplate.specialize(specializations);
4368                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4369                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4370                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4371
4372                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4373         }
4374
4375         return group.release();
4376 }
4377
4378 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
4379 {
4380         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
4381         vector<CaseParameter>                   cases;
4382         de::Random                                              rnd                             (deStringHash(group->getName()));
4383         const int                                               numElements             = 100;
4384         vector<float>                                   inputFloats             (numElements, 0);
4385         vector<float>                                   outputFloats    (numElements, 0);
4386         const StringTemplate                    shaderTemplate  (
4387                 string(getComputeAsmShaderPreamble()) +
4388
4389                 "OpSourceExtension \"${EXTENSION}\"\n"
4390
4391                 "OpName %main           \"main\"\n"
4392                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4393
4394                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4395
4396                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4397
4398                 "%id        = OpVariable %uvec3ptr Input\n"
4399                 "%zero      = OpConstant %i32 0\n"
4400
4401                 "%main      = OpFunction %void None %voidf\n"
4402                 "%label     = OpLabel\n"
4403                 "%idval     = OpLoad %uvec3 %id\n"
4404                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4405                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4406                 "%inval     = OpLoad %f32 %inloc\n"
4407                 "%neg       = OpFNegate %f32 %inval\n"
4408                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4409                 "             OpStore %outloc %neg\n"
4410                 "             OpReturn\n"
4411                 "             OpFunctionEnd\n");
4412
4413         cases.push_back(CaseParameter("empty_extension",        ""));
4414         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
4415         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
4416         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
4417         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
4418
4419         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
4420
4421         for (size_t ndx = 0; ndx < numElements; ++ndx)
4422                 outputFloats[ndx] = -inputFloats[ndx];
4423
4424         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4425         {
4426                 map<string, string>             specializations;
4427                 ComputeShaderSpec               spec;
4428
4429                 specializations["EXTENSION"] = cases[caseNdx].param;
4430                 spec.assembly = shaderTemplate.specialize(specializations);
4431                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4432                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4433                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4434
4435                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4436         }
4437
4438         return group.release();
4439 }
4440
4441 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
4442 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
4443 {
4444         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
4445         vector<CaseParameter>                   cases;
4446         de::Random                                              rnd                             (deStringHash(group->getName()));
4447         const int                                               numElements             = 100;
4448         vector<float>                                   positiveFloats  (numElements, 0);
4449         vector<float>                                   negativeFloats  (numElements, 0);
4450         const StringTemplate                    shaderTemplate  (
4451                 string(getComputeAsmShaderPreamble()) +
4452
4453                 "OpSource GLSL 430\n"
4454                 "OpName %main           \"main\"\n"
4455                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4456
4457                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4458
4459                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4460                 "%uvec2     = OpTypeVector %u32 2\n"
4461                 "%bvec3     = OpTypeVector %bool 3\n"
4462                 "%fvec4     = OpTypeVector %f32 4\n"
4463                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
4464                 "%const100  = OpConstant %u32 100\n"
4465                 "%uarr100   = OpTypeArray %i32 %const100\n"
4466                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
4467                 "%pointer   = OpTypePointer Function %i32\n"
4468                 + string(getComputeAsmInputOutputBuffer()) +
4469
4470                 "%null      = OpConstantNull ${TYPE}\n"
4471
4472                 "%id        = OpVariable %uvec3ptr Input\n"
4473                 "%zero      = OpConstant %i32 0\n"
4474
4475                 "%main      = OpFunction %void None %voidf\n"
4476                 "%label     = OpLabel\n"
4477                 "%idval     = OpLoad %uvec3 %id\n"
4478                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4479                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4480                 "%inval     = OpLoad %f32 %inloc\n"
4481                 "%neg       = OpFNegate %f32 %inval\n"
4482                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4483                 "             OpStore %outloc %neg\n"
4484                 "             OpReturn\n"
4485                 "             OpFunctionEnd\n");
4486
4487         cases.push_back(CaseParameter("bool",                   "%bool"));
4488         cases.push_back(CaseParameter("sint32",                 "%i32"));
4489         cases.push_back(CaseParameter("uint32",                 "%u32"));
4490         cases.push_back(CaseParameter("float32",                "%f32"));
4491         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
4492         cases.push_back(CaseParameter("vec3bool",               "%bvec3"));
4493         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
4494         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
4495         cases.push_back(CaseParameter("array",                  "%uarr100"));
4496         cases.push_back(CaseParameter("struct",                 "%struct"));
4497         cases.push_back(CaseParameter("pointer",                "%pointer"));
4498
4499         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4500
4501         for (size_t ndx = 0; ndx < numElements; ++ndx)
4502                 negativeFloats[ndx] = -positiveFloats[ndx];
4503
4504         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4505         {
4506                 map<string, string>             specializations;
4507                 ComputeShaderSpec               spec;
4508
4509                 specializations["TYPE"] = cases[caseNdx].param;
4510                 spec.assembly = shaderTemplate.specialize(specializations);
4511                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4512                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4513                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4514
4515                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4516         }
4517
4518         return group.release();
4519 }
4520
4521 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4522 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4523 {
4524         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4525         vector<CaseParameter>                   cases;
4526         de::Random                                              rnd                             (deStringHash(group->getName()));
4527         const int                                               numElements             = 100;
4528         vector<float>                                   positiveFloats  (numElements, 0);
4529         vector<float>                                   negativeFloats  (numElements, 0);
4530         const StringTemplate                    shaderTemplate  (
4531                 string(getComputeAsmShaderPreamble()) +
4532
4533                 "OpSource GLSL 430\n"
4534                 "OpName %main           \"main\"\n"
4535                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4536
4537                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4538
4539                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4540
4541                 "%id        = OpVariable %uvec3ptr Input\n"
4542                 "%zero      = OpConstant %i32 0\n"
4543
4544                 "${CONSTANT}\n"
4545
4546                 "%main      = OpFunction %void None %voidf\n"
4547                 "%label     = OpLabel\n"
4548                 "%idval     = OpLoad %uvec3 %id\n"
4549                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4550                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4551                 "%inval     = OpLoad %f32 %inloc\n"
4552                 "%neg       = OpFNegate %f32 %inval\n"
4553                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4554                 "             OpStore %outloc %neg\n"
4555                 "             OpReturn\n"
4556                 "             OpFunctionEnd\n");
4557
4558         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
4559                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
4560         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4561                                                                                                         "%ten = OpConstant %f32 10.\n"
4562                                                                                                         "%fzero = OpConstant %f32 0.\n"
4563                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4564                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4565         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
4566                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4567                                                                                                         "%fzero = OpConstant %f32 0.\n"
4568                                                                                                         "%one = OpConstant %f32 1.\n"
4569                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4570                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4571                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4572                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4573         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
4574                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
4575                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
4576                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4577                                                                                                         "%one = OpConstant %u32 1\n"
4578                                                                                                         "%ten = OpConstant %i32 10\n"
4579                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
4580                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
4581                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
4582
4583         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4584
4585         for (size_t ndx = 0; ndx < numElements; ++ndx)
4586                 negativeFloats[ndx] = -positiveFloats[ndx];
4587
4588         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4589         {
4590                 map<string, string>             specializations;
4591                 ComputeShaderSpec               spec;
4592
4593                 specializations["CONSTANT"] = cases[caseNdx].param;
4594                 spec.assembly = shaderTemplate.specialize(specializations);
4595                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4596                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4597                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4598
4599                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4600         }
4601
4602         return group.release();
4603 }
4604
4605 // Creates a floating point number with the given exponent, and significand
4606 // bits set. It can only create normalized numbers. Only the least significant
4607 // 24 bits of the significand will be examined. The final bit of the
4608 // significand will also be ignored. This allows alignment to be written
4609 // similarly to C99 hex-floats.
4610 // For example if you wanted to write 0x1.7f34p-12 you would call
4611 // constructNormalizedFloat(-12, 0x7f3400)
4612 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4613 {
4614         float f = 1.0f;
4615
4616         for (deInt32 idx = 0; idx < 23; ++idx)
4617         {
4618                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4619                 significand <<= 1;
4620         }
4621
4622         return std::ldexp(f, exponent);
4623 }
4624
4625 // Compare instruction for the OpQuantizeF16 compute exact case.
4626 // Returns true if the output is what is expected from the test case.
4627 bool compareOpQuantizeF16ComputeExactCase (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4628 {
4629         if (outputAllocs.size() != 1)
4630                 return false;
4631
4632         // Only size is needed because we cannot compare Nans.
4633         size_t byteSize = expectedOutputs[0].getByteSize();
4634
4635         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4636
4637         if (byteSize != 4*sizeof(float)) {
4638                 return false;
4639         }
4640
4641         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4642                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4643                 return false;
4644         }
4645         outputAsFloat++;
4646
4647         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4648                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4649                 return false;
4650         }
4651         outputAsFloat++;
4652
4653         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4654                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4655                 return false;
4656         }
4657         outputAsFloat++;
4658
4659         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4660                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4661                 return false;
4662         }
4663
4664         return true;
4665 }
4666
4667 // Checks that every output from a test-case is a float NaN.
4668 bool compareNan (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4669 {
4670         if (outputAllocs.size() != 1)
4671                 return false;
4672
4673         // Only size is needed because we cannot compare Nans.
4674         size_t byteSize = expectedOutputs[0].getByteSize();
4675
4676         const float* const      output_as_float = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4677
4678         for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4679         {
4680                 if (!deFloatIsNaN(output_as_float[idx]))
4681                 {
4682                         return false;
4683                 }
4684         }
4685
4686         return true;
4687 }
4688
4689 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4690 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4691 {
4692         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4693
4694         const std::string shader (
4695                 string(getComputeAsmShaderPreamble()) +
4696
4697                 "OpSource GLSL 430\n"
4698                 "OpName %main           \"main\"\n"
4699                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4700
4701                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4702
4703                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4704
4705                 "%id        = OpVariable %uvec3ptr Input\n"
4706                 "%zero      = OpConstant %i32 0\n"
4707
4708                 "%main      = OpFunction %void None %voidf\n"
4709                 "%label     = OpLabel\n"
4710                 "%idval     = OpLoad %uvec3 %id\n"
4711                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4712                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4713                 "%inval     = OpLoad %f32 %inloc\n"
4714                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
4715                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4716                 "             OpStore %outloc %quant\n"
4717                 "             OpReturn\n"
4718                 "             OpFunctionEnd\n");
4719
4720         {
4721                 ComputeShaderSpec       spec;
4722                 const deUint32          numElements             = 100;
4723                 vector<float>           infinities;
4724                 vector<float>           results;
4725
4726                 infinities.reserve(numElements);
4727                 results.reserve(numElements);
4728
4729                 for (size_t idx = 0; idx < numElements; ++idx)
4730                 {
4731                         switch(idx % 4)
4732                         {
4733                                 case 0:
4734                                         infinities.push_back(std::numeric_limits<float>::infinity());
4735                                         results.push_back(std::numeric_limits<float>::infinity());
4736                                         break;
4737                                 case 1:
4738                                         infinities.push_back(-std::numeric_limits<float>::infinity());
4739                                         results.push_back(-std::numeric_limits<float>::infinity());
4740                                         break;
4741                                 case 2:
4742                                         infinities.push_back(std::ldexp(1.0f, 16));
4743                                         results.push_back(std::numeric_limits<float>::infinity());
4744                                         break;
4745                                 case 3:
4746                                         infinities.push_back(std::ldexp(-1.0f, 32));
4747                                         results.push_back(-std::numeric_limits<float>::infinity());
4748                                         break;
4749                         }
4750                 }
4751
4752                 spec.assembly = shader;
4753                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4754                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4755                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4756
4757                 group->addChild(new SpvAsmComputeShaderCase(
4758                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4759         }
4760
4761         {
4762                 ComputeShaderSpec       spec;
4763                 vector<float>           nans;
4764                 const deUint32          numElements             = 100;
4765
4766                 nans.reserve(numElements);
4767
4768                 for (size_t idx = 0; idx < numElements; ++idx)
4769                 {
4770                         if (idx % 2 == 0)
4771                         {
4772                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
4773                         }
4774                         else
4775                         {
4776                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4777                         }
4778                 }
4779
4780                 spec.assembly = shader;
4781                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4782                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4783                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4784                 spec.verifyIO = &compareNan;
4785
4786                 group->addChild(new SpvAsmComputeShaderCase(
4787                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4788         }
4789
4790         {
4791                 ComputeShaderSpec       spec;
4792                 vector<float>           small;
4793                 vector<float>           zeros;
4794                 const deUint32          numElements             = 100;
4795
4796                 small.reserve(numElements);
4797                 zeros.reserve(numElements);
4798
4799                 for (size_t idx = 0; idx < numElements; ++idx)
4800                 {
4801                         switch(idx % 6)
4802                         {
4803                                 case 0:
4804                                         small.push_back(0.f);
4805                                         zeros.push_back(0.f);
4806                                         break;
4807                                 case 1:
4808                                         small.push_back(-0.f);
4809                                         zeros.push_back(-0.f);
4810                                         break;
4811                                 case 2:
4812                                         small.push_back(std::ldexp(1.0f, -16));
4813                                         zeros.push_back(0.f);
4814                                         break;
4815                                 case 3:
4816                                         small.push_back(std::ldexp(-1.0f, -32));
4817                                         zeros.push_back(-0.f);
4818                                         break;
4819                                 case 4:
4820                                         small.push_back(std::ldexp(1.0f, -127));
4821                                         zeros.push_back(0.f);
4822                                         break;
4823                                 case 5:
4824                                         small.push_back(-std::ldexp(1.0f, -128));
4825                                         zeros.push_back(-0.f);
4826                                         break;
4827                         }
4828                 }
4829
4830                 spec.assembly = shader;
4831                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4832                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4833                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4834
4835                 group->addChild(new SpvAsmComputeShaderCase(
4836                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4837         }
4838
4839         {
4840                 ComputeShaderSpec       spec;
4841                 vector<float>           exact;
4842                 const deUint32          numElements             = 200;
4843
4844                 exact.reserve(numElements);
4845
4846                 for (size_t idx = 0; idx < numElements; ++idx)
4847                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4848
4849                 spec.assembly = shader;
4850                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4851                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4852                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4853
4854                 group->addChild(new SpvAsmComputeShaderCase(
4855                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4856         }
4857
4858         {
4859                 ComputeShaderSpec       spec;
4860                 vector<float>           inputs;
4861                 const deUint32          numElements             = 4;
4862
4863                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
4864                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
4865                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
4866                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
4867
4868                 spec.assembly = shader;
4869                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4870                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4871                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4872                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4873
4874                 group->addChild(new SpvAsmComputeShaderCase(
4875                         testCtx, "rounded", "Check that are rounded when needed", spec));
4876         }
4877
4878         return group.release();
4879 }
4880
4881 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4882 {
4883         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4884
4885         const std::string shader (
4886                 string(getComputeAsmShaderPreamble()) +
4887
4888                 "OpName %main           \"main\"\n"
4889                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4890
4891                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4892
4893                 "OpDecorate %sc_0  SpecId 0\n"
4894                 "OpDecorate %sc_1  SpecId 1\n"
4895                 "OpDecorate %sc_2  SpecId 2\n"
4896                 "OpDecorate %sc_3  SpecId 3\n"
4897                 "OpDecorate %sc_4  SpecId 4\n"
4898                 "OpDecorate %sc_5  SpecId 5\n"
4899
4900                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4901
4902                 "%id        = OpVariable %uvec3ptr Input\n"
4903                 "%zero      = OpConstant %i32 0\n"
4904                 "%c_u32_6   = OpConstant %u32 6\n"
4905
4906                 "%sc_0      = OpSpecConstant %f32 0.\n"
4907                 "%sc_1      = OpSpecConstant %f32 0.\n"
4908                 "%sc_2      = OpSpecConstant %f32 0.\n"
4909                 "%sc_3      = OpSpecConstant %f32 0.\n"
4910                 "%sc_4      = OpSpecConstant %f32 0.\n"
4911                 "%sc_5      = OpSpecConstant %f32 0.\n"
4912
4913                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4914                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4915                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4916                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4917                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4918                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4919
4920                 "%main      = OpFunction %void None %voidf\n"
4921                 "%label     = OpLabel\n"
4922                 "%idval     = OpLoad %uvec3 %id\n"
4923                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4924                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4925                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
4926                 "            OpSelectionMerge %exit None\n"
4927                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4928
4929                 "%case0     = OpLabel\n"
4930                 "             OpStore %outloc %sc_0_quant\n"
4931                 "             OpBranch %exit\n"
4932
4933                 "%case1     = OpLabel\n"
4934                 "             OpStore %outloc %sc_1_quant\n"
4935                 "             OpBranch %exit\n"
4936
4937                 "%case2     = OpLabel\n"
4938                 "             OpStore %outloc %sc_2_quant\n"
4939                 "             OpBranch %exit\n"
4940
4941                 "%case3     = OpLabel\n"
4942                 "             OpStore %outloc %sc_3_quant\n"
4943                 "             OpBranch %exit\n"
4944
4945                 "%case4     = OpLabel\n"
4946                 "             OpStore %outloc %sc_4_quant\n"
4947                 "             OpBranch %exit\n"
4948
4949                 "%case5     = OpLabel\n"
4950                 "             OpStore %outloc %sc_5_quant\n"
4951                 "             OpBranch %exit\n"
4952
4953                 "%exit      = OpLabel\n"
4954                 "             OpReturn\n"
4955
4956                 "             OpFunctionEnd\n");
4957
4958         {
4959                 ComputeShaderSpec       spec;
4960                 const deUint8           numCases        = 4;
4961                 vector<float>           inputs          (numCases, 0.f);
4962                 vector<float>           outputs;
4963
4964                 spec.assembly           = shader;
4965                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4966
4967                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4968                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4969                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4970                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4971
4972                 outputs.push_back(std::numeric_limits<float>::infinity());
4973                 outputs.push_back(-std::numeric_limits<float>::infinity());
4974                 outputs.push_back(std::numeric_limits<float>::infinity());
4975                 outputs.push_back(-std::numeric_limits<float>::infinity());
4976
4977                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4978                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4979
4980                 group->addChild(new SpvAsmComputeShaderCase(
4981                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4982         }
4983
4984         {
4985                 ComputeShaderSpec       spec;
4986                 const deUint8           numCases        = 2;
4987                 vector<float>           inputs          (numCases, 0.f);
4988                 vector<float>           outputs;
4989
4990                 spec.assembly           = shader;
4991                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4992                 spec.verifyIO           = &compareNan;
4993
4994                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
4995                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
4996
4997                 for (deUint8 idx = 0; idx < numCases; ++idx)
4998                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4999
5000                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5001                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5002
5003                 group->addChild(new SpvAsmComputeShaderCase(
5004                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
5005         }
5006
5007         {
5008                 ComputeShaderSpec       spec;
5009                 const deUint8           numCases        = 6;
5010                 vector<float>           inputs          (numCases, 0.f);
5011                 vector<float>           outputs;
5012
5013                 spec.assembly           = shader;
5014                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
5015
5016                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(0.f));
5017                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-0.f));
5018                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
5019                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
5020                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
5021                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
5022
5023                 outputs.push_back(0.f);
5024                 outputs.push_back(-0.f);
5025                 outputs.push_back(0.f);
5026                 outputs.push_back(-0.f);
5027                 outputs.push_back(0.f);
5028                 outputs.push_back(-0.f);
5029
5030                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5031                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5032
5033                 group->addChild(new SpvAsmComputeShaderCase(
5034                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
5035         }
5036
5037         {
5038                 ComputeShaderSpec       spec;
5039                 const deUint8           numCases        = 6;
5040                 vector<float>           inputs          (numCases, 0.f);
5041                 vector<float>           outputs;
5042
5043                 spec.assembly           = shader;
5044                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
5045
5046                 for (deUint8 idx = 0; idx < 6; ++idx)
5047                 {
5048                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
5049                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(f));
5050                         outputs.push_back(f);
5051                 }
5052
5053                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5054                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5055
5056                 group->addChild(new SpvAsmComputeShaderCase(
5057                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
5058         }
5059
5060         {
5061                 ComputeShaderSpec       spec;
5062                 const deUint8           numCases        = 4;
5063                 vector<float>           inputs          (numCases, 0.f);
5064                 vector<float>           outputs;
5065
5066                 spec.assembly           = shader;
5067                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
5068                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
5069
5070                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
5071                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
5072                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
5073                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
5074
5075                 for (deUint8 idx = 0; idx < numCases; ++idx)
5076                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
5077
5078                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5079                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5080
5081                 group->addChild(new SpvAsmComputeShaderCase(
5082                         testCtx, "rounded", "Check that are rounded when needed", spec));
5083         }
5084
5085         return group.release();
5086 }
5087
5088 // Checks that constant null/composite values can be used in computation.
5089 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
5090 {
5091         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
5092         ComputeShaderSpec                               spec;
5093         de::Random                                              rnd                             (deStringHash(group->getName()));
5094         const int                                               numElements             = 100;
5095         vector<float>                                   positiveFloats  (numElements, 0);
5096         vector<float>                                   negativeFloats  (numElements, 0);
5097
5098         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5099
5100         for (size_t ndx = 0; ndx < numElements; ++ndx)
5101                 negativeFloats[ndx] = -positiveFloats[ndx];
5102
5103         spec.assembly =
5104                 "OpCapability Shader\n"
5105                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
5106                 "OpMemoryModel Logical GLSL450\n"
5107                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5108                 "OpExecutionMode %main LocalSize 1 1 1\n"
5109
5110                 "OpSource GLSL 430\n"
5111                 "OpName %main           \"main\"\n"
5112                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5113
5114                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5115
5116                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5117
5118                 "%fmat      = OpTypeMatrix %fvec3 3\n"
5119                 "%ten       = OpConstant %u32 10\n"
5120                 "%f32arr10  = OpTypeArray %f32 %ten\n"
5121                 "%fst       = OpTypeStruct %f32 %f32\n"
5122
5123                 + string(getComputeAsmInputOutputBuffer()) +
5124
5125                 "%id        = OpVariable %uvec3ptr Input\n"
5126                 "%zero      = OpConstant %i32 0\n"
5127
5128                 // Create a bunch of null values
5129                 "%unull     = OpConstantNull %u32\n"
5130                 "%fnull     = OpConstantNull %f32\n"
5131                 "%vnull     = OpConstantNull %fvec3\n"
5132                 "%mnull     = OpConstantNull %fmat\n"
5133                 "%anull     = OpConstantNull %f32arr10\n"
5134                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
5135
5136                 "%main      = OpFunction %void None %voidf\n"
5137                 "%label     = OpLabel\n"
5138                 "%idval     = OpLoad %uvec3 %id\n"
5139                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5140                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5141                 "%inval     = OpLoad %f32 %inloc\n"
5142                 "%neg       = OpFNegate %f32 %inval\n"
5143
5144                 // Get the abs() of (a certain element of) those null values
5145                 "%unull_cov = OpConvertUToF %f32 %unull\n"
5146                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
5147                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
5148                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
5149                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
5150                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
5151                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
5152                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
5153                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
5154                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
5155                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
5156
5157                 // Add them all
5158                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
5159                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
5160                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
5161                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
5162                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
5163                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
5164
5165                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5166                 "             OpStore %outloc %final\n" // write to output
5167                 "             OpReturn\n"
5168                 "             OpFunctionEnd\n";
5169         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5170         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5171         spec.numWorkGroups = IVec3(numElements, 1, 1);
5172
5173         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
5174
5175         return group.release();
5176 }
5177
5178 // Assembly code used for testing loop control is based on GLSL source code:
5179 // #version 430
5180 //
5181 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5182 //   float elements[];
5183 // } input_data;
5184 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5185 //   float elements[];
5186 // } output_data;
5187 //
5188 // void main() {
5189 //   uint x = gl_GlobalInvocationID.x;
5190 //   output_data.elements[x] = input_data.elements[x];
5191 //   for (uint i = 0; i < 4; ++i)
5192 //     output_data.elements[x] += 1.f;
5193 // }
5194 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
5195 {
5196         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
5197         vector<CaseParameter>                   cases;
5198         de::Random                                              rnd                             (deStringHash(group->getName()));
5199         const int                                               numElements             = 100;
5200         vector<float>                                   inputFloats             (numElements, 0);
5201         vector<float>                                   outputFloats    (numElements, 0);
5202         const StringTemplate                    shaderTemplate  (
5203                 string(getComputeAsmShaderPreamble()) +
5204
5205                 "OpSource GLSL 430\n"
5206                 "OpName %main \"main\"\n"
5207                 "OpName %id \"gl_GlobalInvocationID\"\n"
5208
5209                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5210
5211                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5212
5213                 "%u32ptr      = OpTypePointer Function %u32\n"
5214
5215                 "%id          = OpVariable %uvec3ptr Input\n"
5216                 "%zero        = OpConstant %i32 0\n"
5217                 "%uzero       = OpConstant %u32 0\n"
5218                 "%one         = OpConstant %i32 1\n"
5219                 "%constf1     = OpConstant %f32 1.0\n"
5220                 "%four        = OpConstant %u32 4\n"
5221
5222                 "%main        = OpFunction %void None %voidf\n"
5223                 "%entry       = OpLabel\n"
5224                 "%i           = OpVariable %u32ptr Function\n"
5225                 "               OpStore %i %uzero\n"
5226
5227                 "%idval       = OpLoad %uvec3 %id\n"
5228                 "%x           = OpCompositeExtract %u32 %idval 0\n"
5229                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
5230                 "%inval       = OpLoad %f32 %inloc\n"
5231                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
5232                 "               OpStore %outloc %inval\n"
5233                 "               OpBranch %loop_entry\n"
5234
5235                 "%loop_entry  = OpLabel\n"
5236                 "%i_val       = OpLoad %u32 %i\n"
5237                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
5238                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
5239                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
5240                 "%loop_body   = OpLabel\n"
5241                 "%outval      = OpLoad %f32 %outloc\n"
5242                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
5243                 "               OpStore %outloc %addf1\n"
5244                 "%new_i       = OpIAdd %u32 %i_val %one\n"
5245                 "               OpStore %i %new_i\n"
5246                 "               OpBranch %loop_entry\n"
5247                 "%loop_merge  = OpLabel\n"
5248                 "               OpReturn\n"
5249                 "               OpFunctionEnd\n");
5250
5251         cases.push_back(CaseParameter("none",                           "None"));
5252         cases.push_back(CaseParameter("unroll",                         "Unroll"));
5253         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
5254
5255         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5256
5257         for (size_t ndx = 0; ndx < numElements; ++ndx)
5258                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
5259
5260         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5261         {
5262                 map<string, string>             specializations;
5263                 ComputeShaderSpec               spec;
5264
5265                 specializations["CONTROL"] = cases[caseNdx].param;
5266                 spec.assembly = shaderTemplate.specialize(specializations);
5267                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5268                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5269                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5270
5271                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5272         }
5273
5274         group->addChild(new SpvAsmLoopControlDependencyLengthCase(testCtx, "dependency_length", "dependency_length"));
5275         group->addChild(new SpvAsmLoopControlDependencyInfiniteCase(testCtx, "dependency_infinite", "dependency_infinite"));
5276
5277         return group.release();
5278 }
5279
5280 // Assembly code used for testing selection control is based on GLSL source code:
5281 // #version 430
5282 //
5283 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5284 //   float elements[];
5285 // } input_data;
5286 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5287 //   float elements[];
5288 // } output_data;
5289 //
5290 // void main() {
5291 //   uint x = gl_GlobalInvocationID.x;
5292 //   float val = input_data.elements[x];
5293 //   if (val > 10.f)
5294 //     output_data.elements[x] = val + 1.f;
5295 //   else
5296 //     output_data.elements[x] = val - 1.f;
5297 // }
5298 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
5299 {
5300         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
5301         vector<CaseParameter>                   cases;
5302         de::Random                                              rnd                             (deStringHash(group->getName()));
5303         const int                                               numElements             = 100;
5304         vector<float>                                   inputFloats             (numElements, 0);
5305         vector<float>                                   outputFloats    (numElements, 0);
5306         const StringTemplate                    shaderTemplate  (
5307                 string(getComputeAsmShaderPreamble()) +
5308
5309                 "OpSource GLSL 430\n"
5310                 "OpName %main \"main\"\n"
5311                 "OpName %id \"gl_GlobalInvocationID\"\n"
5312
5313                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5314
5315                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5316
5317                 "%id       = OpVariable %uvec3ptr Input\n"
5318                 "%zero     = OpConstant %i32 0\n"
5319                 "%constf1  = OpConstant %f32 1.0\n"
5320                 "%constf10 = OpConstant %f32 10.0\n"
5321
5322                 "%main     = OpFunction %void None %voidf\n"
5323                 "%entry    = OpLabel\n"
5324                 "%idval    = OpLoad %uvec3 %id\n"
5325                 "%x        = OpCompositeExtract %u32 %idval 0\n"
5326                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
5327                 "%inval    = OpLoad %f32 %inloc\n"
5328                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
5329                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
5330
5331                 "            OpSelectionMerge %if_end ${CONTROL}\n"
5332                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
5333                 "%if_true  = OpLabel\n"
5334                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
5335                 "            OpStore %outloc %addf1\n"
5336                 "            OpBranch %if_end\n"
5337                 "%if_false = OpLabel\n"
5338                 "%subf1    = OpFSub %f32 %inval %constf1\n"
5339                 "            OpStore %outloc %subf1\n"
5340                 "            OpBranch %if_end\n"
5341                 "%if_end   = OpLabel\n"
5342                 "            OpReturn\n"
5343                 "            OpFunctionEnd\n");
5344
5345         cases.push_back(CaseParameter("none",                                   "None"));
5346         cases.push_back(CaseParameter("flatten",                                "Flatten"));
5347         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
5348         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
5349
5350         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5351
5352         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5353         floorAll(inputFloats);
5354
5355         for (size_t ndx = 0; ndx < numElements; ++ndx)
5356                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
5357
5358         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5359         {
5360                 map<string, string>             specializations;
5361                 ComputeShaderSpec               spec;
5362
5363                 specializations["CONTROL"] = cases[caseNdx].param;
5364                 spec.assembly = shaderTemplate.specialize(specializations);
5365                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5366                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5367                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5368
5369                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5370         }
5371
5372         return group.release();
5373 }
5374
5375 void getOpNameAbuseCases (vector<CaseParameter> &abuseCases)
5376 {
5377         // Generate a long name.
5378         std::string longname;
5379         longname.resize(65535, 'k'); // max string literal, spir-v 2.17
5380
5381         // Some bad names, abusing utf-8 encoding. This may also cause problems
5382         // with the logs.
5383         // 1. Various illegal code points in utf-8
5384         std::string utf8illegal =
5385                 "Illegal bytes in UTF-8: "
5386                 "\xc0 \xc1 \xf5 \xf6 \xf7 \xf8 \xf9 \xfa \xfb \xfc \xfd \xfe \xff"
5387                 "illegal surrogates: \xed\xad\xbf \xed\xbe\x80";
5388
5389         // 2. Zero encoded as overlong, not exactly legal but often supported to differentiate from terminating zero
5390         std::string utf8nul = "UTF-8 encoded nul \xC0\x80 (should not end name)";
5391
5392         // 3. Some overlong encodings
5393         std::string utf8overlong =
5394                 "UTF-8 overlong \xF0\x82\x82\xAC \xfc\x83\xbf\xbf\xbf\xbf \xf8\x87\xbf\xbf\xbf "
5395                 "\xf0\x8f\xbf\xbf";
5396
5397         // 4. Internet "zalgo" meme "bleeding text"
5398         std::string utf8zalgo =
5399                 "\x56\xcc\xb5\xcc\x85\xcc\x94\xcc\x88\xcd\x8a\xcc\x91\xcc\x88\xcd\x91\xcc\x83\xcd\x82"
5400                 "\xcc\x83\xcd\x90\xcc\x8a\xcc\x92\xcc\x92\xcd\x8b\xcc\x94\xcd\x9d\xcc\x98\xcc\xab\xcc"
5401                 "\xae\xcc\xa9\xcc\xad\xcc\x97\xcc\xb0\x75\xcc\xb6\xcc\xbe\xcc\x80\xcc\x82\xcc\x84\xcd"
5402                 "\x84\xcc\x90\xcd\x86\xcc\x9a\xcd\x84\xcc\x9b\xcd\x86\xcd\x92\xcc\x9a\xcd\x99\xcd\x99"
5403                 "\xcc\xbb\xcc\x98\xcd\x8e\xcd\x88\xcd\x9a\xcc\xa6\xcc\x9c\xcc\xab\xcc\x99\xcd\x94\xcd"
5404                 "\x99\xcd\x95\xcc\xa5\xcc\xab\xcd\x89\x6c\xcc\xb8\xcc\x8e\xcc\x8b\xcc\x8b\xcc\x9a\xcc"
5405                 "\x8e\xcd\x9d\xcc\x80\xcc\xa1\xcc\xad\xcd\x9c\xcc\xba\xcc\x96\xcc\xb3\xcc\xa2\xcd\x8e"
5406                 "\xcc\xa2\xcd\x96\x6b\xcc\xb8\xcc\x84\xcd\x81\xcc\xbf\xcc\x8d\xcc\x89\xcc\x85\xcc\x92"
5407                 "\xcc\x84\xcc\x90\xcd\x81\xcc\x93\xcd\x90\xcd\x92\xcd\x9d\xcc\x84\xcd\x98\xcd\x9d\xcd"
5408                 "\xa0\xcd\x91\xcc\x94\xcc\xb9\xcd\x93\xcc\xa5\xcd\x87\xcc\xad\xcc\xa7\xcd\x96\xcd\x99"
5409                 "\xcc\x9d\xcc\xbc\xcd\x96\xcd\x93\xcc\x9d\xcc\x99\xcc\xa8\xcc\xb1\xcd\x85\xcc\xba\xcc"
5410                 "\xa7\x61\xcc\xb8\xcc\x8e\xcc\x81\xcd\x90\xcd\x84\xcd\x8c\xcc\x8c\xcc\x85\xcd\x86\xcc"
5411                 "\x84\xcd\x84\xcc\x90\xcc\x84\xcc\x8d\xcd\x99\xcd\x8d\xcc\xb0\xcc\xa3\xcc\xa6\xcd\x89"
5412                 "\xcd\x8d\xcd\x87\xcc\x98\xcd\x8d\xcc\xa4\xcd\x9a\xcd\x8e\xcc\xab\xcc\xb9\xcc\xac\xcc"
5413                 "\xa2\xcd\x87\xcc\xa0\xcc\xb3\xcd\x89\xcc\xb9\xcc\xa7\xcc\xa6\xcd\x89\xcd\x95\x6e\xcc"
5414                 "\xb8\xcd\x8a\xcc\x8a\xcd\x82\xcc\x9b\xcd\x81\xcd\x90\xcc\x85\xcc\x9b\xcd\x80\xcd\x91"
5415                 "\xcd\x9b\xcc\x81\xcd\x81\xcc\x9a\xcc\xb3\xcd\x9c\xcc\x9e\xcc\x9d\xcd\x99\xcc\xa2\xcd"
5416                 "\x93\xcd\x96\xcc\x97\xff";
5417
5418         // General name abuses
5419         abuseCases.push_back(CaseParameter("_has_very_long_name", longname));
5420         abuseCases.push_back(CaseParameter("_utf8_illegal", utf8illegal));
5421         abuseCases.push_back(CaseParameter("_utf8_nul", utf8nul));
5422         abuseCases.push_back(CaseParameter("_utf8_overlong", utf8overlong));
5423         abuseCases.push_back(CaseParameter("_utf8_zalgo", utf8zalgo));
5424
5425         // GL keywords
5426         abuseCases.push_back(CaseParameter("_is_gl_Position", "gl_Position"));
5427         abuseCases.push_back(CaseParameter("_is_gl_InstanceID", "gl_InstanceID"));
5428         abuseCases.push_back(CaseParameter("_is_gl_PrimitiveID", "gl_PrimitiveID"));
5429         abuseCases.push_back(CaseParameter("_is_gl_TessCoord", "gl_TessCoord"));
5430         abuseCases.push_back(CaseParameter("_is_gl_PerVertex", "gl_PerVertex"));
5431         abuseCases.push_back(CaseParameter("_is_gl_InvocationID", "gl_InvocationID"));
5432         abuseCases.push_back(CaseParameter("_is_gl_PointSize", "gl_PointSize"));
5433         abuseCases.push_back(CaseParameter("_is_gl_PointCoord", "gl_PointCoord"));
5434         abuseCases.push_back(CaseParameter("_is_gl_Layer", "gl_Layer"));
5435         abuseCases.push_back(CaseParameter("_is_gl_FragDepth", "gl_FragDepth"));
5436         abuseCases.push_back(CaseParameter("_is_gl_NumWorkGroups", "gl_NumWorkGroups"));
5437         abuseCases.push_back(CaseParameter("_is_gl_WorkGroupID", "gl_WorkGroupID"));
5438         abuseCases.push_back(CaseParameter("_is_gl_LocalInvocationID", "gl_LocalInvocationID"));
5439         abuseCases.push_back(CaseParameter("_is_gl_GlobalInvocationID", "gl_GlobalInvocationID"));
5440         abuseCases.push_back(CaseParameter("_is_gl_MaxVertexAttribs", "gl_MaxVertexAttribs"));
5441         abuseCases.push_back(CaseParameter("_is_gl_MaxViewports", "gl_MaxViewports"));
5442         abuseCases.push_back(CaseParameter("_is_gl_MaxComputeWorkGroupCount", "gl_MaxComputeWorkGroupCount"));
5443         abuseCases.push_back(CaseParameter("_is_mat3", "mat3"));
5444         abuseCases.push_back(CaseParameter("_is_volatile", "volatile"));
5445         abuseCases.push_back(CaseParameter("_is_inout", "inout"));
5446         abuseCases.push_back(CaseParameter("_is_isampler3d", "isampler3d"));
5447 }
5448
5449 tcu::TestCaseGroup* createOpNameGroup (tcu::TestContext& testCtx)
5450 {
5451         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opname", "Tests OpName cases"));
5452         de::MovePtr<tcu::TestCaseGroup> entryMainGroup  (new tcu::TestCaseGroup(testCtx, "entry_main", "OpName tests with entry main"));
5453         de::MovePtr<tcu::TestCaseGroup> entryNotGroup   (new tcu::TestCaseGroup(testCtx, "entry_rdc", "OpName tests with entry rdc"));
5454         de::MovePtr<tcu::TestCaseGroup> abuseGroup              (new tcu::TestCaseGroup(testCtx, "abuse", "OpName abuse tests"));
5455         vector<CaseParameter>                   cases;
5456         vector<CaseParameter>                   abuseCases;
5457         vector<string>                                  testFunc;
5458         de::Random                                              rnd                             (deStringHash(group->getName()));
5459         const int                                               numElements             = 128;
5460         vector<float>                                   inputFloats             (numElements, 0);
5461         vector<float>                                   outputFloats    (numElements, 0);
5462
5463         getOpNameAbuseCases(abuseCases);
5464
5465         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5466
5467         for(size_t ndx = 0; ndx < numElements; ++ndx)
5468                 outputFloats[ndx] = -inputFloats[ndx];
5469
5470         const string commonShaderHeader =
5471                 "OpCapability Shader\n"
5472                 "OpMemoryModel Logical GLSL450\n"
5473                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5474                 "OpExecutionMode %main LocalSize 1 1 1\n";
5475
5476         const string commonShaderFooter =
5477                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5478
5479                 + string(getComputeAsmInputOutputBufferTraits())
5480                 + string(getComputeAsmCommonTypes())
5481                 + string(getComputeAsmInputOutputBuffer()) +
5482
5483                 "%id        = OpVariable %uvec3ptr Input\n"
5484                 "%zero      = OpConstant %i32 0\n"
5485
5486                 "%func      = OpFunction %void None %voidf\n"
5487                 "%5         = OpLabel\n"
5488                 "             OpReturn\n"
5489                 "             OpFunctionEnd\n"
5490
5491                 "%main      = OpFunction %void None %voidf\n"
5492                 "%entry     = OpLabel\n"
5493                 "%7         = OpFunctionCall %void %func\n"
5494
5495                 "%idval     = OpLoad %uvec3 %id\n"
5496                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5497
5498                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5499                 "%inval     = OpLoad %f32 %inloc\n"
5500                 "%neg       = OpFNegate %f32 %inval\n"
5501                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5502                 "             OpStore %outloc %neg\n"
5503
5504                 "             OpReturn\n"
5505                 "             OpFunctionEnd\n";
5506
5507         const StringTemplate shaderTemplate (
5508                 "OpCapability Shader\n"
5509                 "OpMemoryModel Logical GLSL450\n"
5510                 "OpEntryPoint GLCompute %main \"${ENTRY}\" %id\n"
5511                 "OpExecutionMode %main LocalSize 1 1 1\n"
5512                 "OpName %${ID} \"${NAME}\"\n" +
5513                 commonShaderFooter);
5514
5515         const std::string multipleNames =
5516                 commonShaderHeader +
5517                 "OpName %main \"to_be\"\n"
5518                 "OpName %id   \"or_not\"\n"
5519                 "OpName %main \"to_be\"\n"
5520                 "OpName %main \"makes_no\"\n"
5521                 "OpName %func \"difference\"\n"
5522                 "OpName %5    \"to_me\"\n" +
5523                 commonShaderFooter;
5524
5525         {
5526                 ComputeShaderSpec       spec;
5527
5528                 spec.assembly           = multipleNames;
5529                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5530                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5531                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5532
5533                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "main_has_multiple_names", "multiple_names", spec));
5534         }
5535
5536         const std::string everythingNamed =
5537                 commonShaderHeader +
5538                 "OpName %main   \"name1\"\n"
5539                 "OpName %id     \"name2\"\n"
5540                 "OpName %zero   \"name3\"\n"
5541                 "OpName %entry  \"name4\"\n"
5542                 "OpName %func   \"name5\"\n"
5543                 "OpName %5      \"name6\"\n"
5544                 "OpName %7      \"name7\"\n"
5545                 "OpName %idval  \"name8\"\n"
5546                 "OpName %inloc  \"name9\"\n"
5547                 "OpName %inval  \"name10\"\n"
5548                 "OpName %neg    \"name11\"\n"
5549                 "OpName %outloc \"name12\"\n"+
5550                 commonShaderFooter;
5551         {
5552                 ComputeShaderSpec       spec;
5553
5554                 spec.assembly           = everythingNamed;
5555                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5556                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5557                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5558
5559                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named", "everything_named", spec));
5560         }
5561
5562         const std::string everythingNamedTheSame =
5563                 commonShaderHeader +
5564                 "OpName %main   \"the_same\"\n"
5565                 "OpName %id     \"the_same\"\n"
5566                 "OpName %zero   \"the_same\"\n"
5567                 "OpName %entry  \"the_same\"\n"
5568                 "OpName %func   \"the_same\"\n"
5569                 "OpName %5      \"the_same\"\n"
5570                 "OpName %7      \"the_same\"\n"
5571                 "OpName %idval  \"the_same\"\n"
5572                 "OpName %inloc  \"the_same\"\n"
5573                 "OpName %inval  \"the_same\"\n"
5574                 "OpName %neg    \"the_same\"\n"
5575                 "OpName %outloc \"the_same\"\n"+
5576                 commonShaderFooter;
5577         {
5578                 ComputeShaderSpec       spec;
5579
5580                 spec.assembly           = everythingNamedTheSame;
5581                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5582                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5583                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5584
5585                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5586         }
5587
5588         // main_is_...
5589         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5590         {
5591                 map<string, string>     specializations;
5592                 ComputeShaderSpec       spec;
5593
5594                 specializations["ENTRY"]        = "main";
5595                 specializations["ID"]           = "main";
5596                 specializations["NAME"]         = abuseCases[ndx].param;
5597                 spec.assembly                           = shaderTemplate.specialize(specializations);
5598                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5599                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5600                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5601
5602                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("main") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5603         }
5604
5605         // x_is_....
5606         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5607         {
5608                 map<string, string>     specializations;
5609                 ComputeShaderSpec       spec;
5610
5611                 specializations["ENTRY"]        = "main";
5612                 specializations["ID"]           = "x";
5613                 specializations["NAME"]         = abuseCases[ndx].param;
5614                 spec.assembly                           = shaderTemplate.specialize(specializations);
5615                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5616                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5617                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5618
5619                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5620         }
5621
5622         cases.push_back(CaseParameter("_is_main", "main"));
5623         cases.push_back(CaseParameter("_is_not_main", "not_main"));
5624         testFunc.push_back("main");
5625         testFunc.push_back("func");
5626
5627         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5628         {
5629                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5630                 {
5631                         map<string, string>     specializations;
5632                         ComputeShaderSpec       spec;
5633
5634                         specializations["ENTRY"]        = "main";
5635                         specializations["ID"]           = testFunc[fNdx];
5636                         specializations["NAME"]         = cases[ndx].param;
5637                         spec.assembly                           = shaderTemplate.specialize(specializations);
5638                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5639                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5640                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5641
5642                         entryMainGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5643                 }
5644         }
5645
5646         cases.push_back(CaseParameter("_is_entry", "rdc"));
5647
5648         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5649         {
5650                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5651                 {
5652                         map<string, string>     specializations;
5653                         ComputeShaderSpec       spec;
5654
5655                         specializations["ENTRY"]        = "rdc";
5656                         specializations["ID"]           = testFunc[fNdx];
5657                         specializations["NAME"]         = cases[ndx].param;
5658                         spec.assembly                           = shaderTemplate.specialize(specializations);
5659                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5660                         spec.entryPoint                         = "rdc";
5661                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5662                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5663
5664                         entryNotGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5665                 }
5666         }
5667
5668         group->addChild(entryMainGroup.release());
5669         group->addChild(entryNotGroup.release());
5670         group->addChild(abuseGroup.release());
5671
5672         return group.release();
5673 }
5674
5675 tcu::TestCaseGroup* createOpMemberNameGroup (tcu::TestContext& testCtx)
5676 {
5677         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opmembername", "Tests OpMemberName cases"));
5678         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "abuse", "OpMemberName abuse tests"));
5679         vector<CaseParameter>                   abuseCases;
5680         vector<string>                                  testFunc;
5681         de::Random                                              rnd(deStringHash(group->getName()));
5682         const int                                               numElements = 128;
5683         vector<float>                                   inputFloats(numElements, 0);
5684         vector<float>                                   outputFloats(numElements, 0);
5685
5686         getOpNameAbuseCases(abuseCases);
5687
5688         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5689
5690         for (size_t ndx = 0; ndx < numElements; ++ndx)
5691                 outputFloats[ndx] = -inputFloats[ndx];
5692
5693         const string commonShaderHeader =
5694                 "OpCapability Shader\n"
5695                 "OpMemoryModel Logical GLSL450\n"
5696                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5697                 "OpExecutionMode %main LocalSize 1 1 1\n";
5698
5699         const string commonShaderFooter =
5700                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5701
5702                 + string(getComputeAsmInputOutputBufferTraits())
5703                 + string(getComputeAsmCommonTypes())
5704                 + string(getComputeAsmInputOutputBuffer()) +
5705
5706                 "%u3str     = OpTypeStruct %u32 %u32 %u32\n"
5707
5708                 "%id        = OpVariable %uvec3ptr Input\n"
5709                 "%zero      = OpConstant %i32 0\n"
5710
5711                 "%main      = OpFunction %void None %voidf\n"
5712                 "%entry     = OpLabel\n"
5713
5714                 "%idval     = OpLoad %uvec3 %id\n"
5715                 "%x0        = OpCompositeExtract %u32 %idval 0\n"
5716
5717                 "%idstr     = OpCompositeConstruct %u3str %x0 %x0 %x0\n"
5718                 "%x         = OpCompositeExtract %u32 %idstr 0\n"
5719
5720                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5721                 "%inval     = OpLoad %f32 %inloc\n"
5722                 "%neg       = OpFNegate %f32 %inval\n"
5723                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5724                 "             OpStore %outloc %neg\n"
5725
5726                 "             OpReturn\n"
5727                 "             OpFunctionEnd\n";
5728
5729         const StringTemplate shaderTemplate(
5730                 commonShaderHeader +
5731                 "OpMemberName %u3str 0 \"${NAME}\"\n" +
5732                 commonShaderFooter);
5733
5734         const std::string multipleNames =
5735                 commonShaderHeader +
5736                 "OpMemberName %u3str 0 \"to_be\"\n"
5737                 "OpMemberName %u3str 1 \"or_not\"\n"
5738                 "OpMemberName %u3str 0 \"to_be\"\n"
5739                 "OpMemberName %u3str 2 \"makes_no\"\n"
5740                 "OpMemberName %u3str 0 \"difference\"\n"
5741                 "OpMemberName %u3str 0 \"to_me\"\n" +
5742                 commonShaderFooter;
5743         {
5744                 ComputeShaderSpec       spec;
5745
5746                 spec.assembly = multipleNames;
5747                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5748                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5749                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5750
5751                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "u3str_x_has_multiple_names", "multiple_names", spec));
5752         }
5753
5754         const std::string everythingNamedTheSame =
5755                 commonShaderHeader +
5756                 "OpMemberName %u3str 0 \"the_same\"\n"
5757                 "OpMemberName %u3str 1 \"the_same\"\n"
5758                 "OpMemberName %u3str 2 \"the_same\"\n" +
5759                 commonShaderFooter;
5760
5761         {
5762                 ComputeShaderSpec       spec;
5763
5764                 spec.assembly = everythingNamedTheSame;
5765                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5766                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5767                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5768
5769                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5770         }
5771
5772         // u3str_x_is_....
5773         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5774         {
5775                 map<string, string>     specializations;
5776                 ComputeShaderSpec       spec;
5777
5778                 specializations["NAME"] = abuseCases[ndx].param;
5779                 spec.assembly = shaderTemplate.specialize(specializations);
5780                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5781                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5782                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5783
5784                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("u3str_x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5785         }
5786
5787         group->addChild(abuseGroup.release());
5788
5789         return group.release();
5790 }
5791
5792 // Assembly code used for testing function control is based on GLSL source code:
5793 //
5794 // #version 430
5795 //
5796 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5797 //   float elements[];
5798 // } input_data;
5799 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5800 //   float elements[];
5801 // } output_data;
5802 //
5803 // float const10() { return 10.f; }
5804 //
5805 // void main() {
5806 //   uint x = gl_GlobalInvocationID.x;
5807 //   output_data.elements[x] = input_data.elements[x] + const10();
5808 // }
5809 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
5810 {
5811         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
5812         vector<CaseParameter>                   cases;
5813         de::Random                                              rnd                             (deStringHash(group->getName()));
5814         const int                                               numElements             = 100;
5815         vector<float>                                   inputFloats             (numElements, 0);
5816         vector<float>                                   outputFloats    (numElements, 0);
5817         const StringTemplate                    shaderTemplate  (
5818                 string(getComputeAsmShaderPreamble()) +
5819
5820                 "OpSource GLSL 430\n"
5821                 "OpName %main \"main\"\n"
5822                 "OpName %func_const10 \"const10(\"\n"
5823                 "OpName %id \"gl_GlobalInvocationID\"\n"
5824
5825                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5826
5827                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5828
5829                 "%f32f = OpTypeFunction %f32\n"
5830                 "%id = OpVariable %uvec3ptr Input\n"
5831                 "%zero = OpConstant %i32 0\n"
5832                 "%constf10 = OpConstant %f32 10.0\n"
5833
5834                 "%main         = OpFunction %void None %voidf\n"
5835                 "%entry        = OpLabel\n"
5836                 "%idval        = OpLoad %uvec3 %id\n"
5837                 "%x            = OpCompositeExtract %u32 %idval 0\n"
5838                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
5839                 "%inval        = OpLoad %f32 %inloc\n"
5840                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
5841                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
5842                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
5843                 "                OpStore %outloc %fadd\n"
5844                 "                OpReturn\n"
5845                 "                OpFunctionEnd\n"
5846
5847                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
5848                 "%label        = OpLabel\n"
5849                 "                OpReturnValue %constf10\n"
5850                 "                OpFunctionEnd\n");
5851
5852         cases.push_back(CaseParameter("none",                                           "None"));
5853         cases.push_back(CaseParameter("inline",                                         "Inline"));
5854         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
5855         cases.push_back(CaseParameter("pure",                                           "Pure"));
5856         cases.push_back(CaseParameter("const",                                          "Const"));
5857         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
5858         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
5859         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
5860         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
5861
5862         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5863
5864         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5865         floorAll(inputFloats);
5866
5867         for (size_t ndx = 0; ndx < numElements; ++ndx)
5868                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
5869
5870         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5871         {
5872                 map<string, string>             specializations;
5873                 ComputeShaderSpec               spec;
5874
5875                 specializations["CONTROL"] = cases[caseNdx].param;
5876                 spec.assembly = shaderTemplate.specialize(specializations);
5877                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5878                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5879                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5880
5881                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5882         }
5883
5884         return group.release();
5885 }
5886
5887 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5888 {
5889         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5890         vector<CaseParameter>                   cases;
5891         de::Random                                              rnd                             (deStringHash(group->getName()));
5892         const int                                               numElements             = 100;
5893         vector<float>                                   inputFloats             (numElements, 0);
5894         vector<float>                                   outputFloats    (numElements, 0);
5895         const StringTemplate                    shaderTemplate  (
5896                 string(getComputeAsmShaderPreamble()) +
5897
5898                 "OpSource GLSL 430\n"
5899                 "OpName %main           \"main\"\n"
5900                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5901
5902                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5903
5904                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5905
5906                 "%f32ptr_f  = OpTypePointer Function %f32\n"
5907
5908                 "%id        = OpVariable %uvec3ptr Input\n"
5909                 "%zero      = OpConstant %i32 0\n"
5910                 "%four      = OpConstant %i32 4\n"
5911
5912                 "%main      = OpFunction %void None %voidf\n"
5913                 "%label     = OpLabel\n"
5914                 "%copy      = OpVariable %f32ptr_f Function\n"
5915                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5916                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5917                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5918                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5919                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
5920                 "%val1      = OpLoad %f32 %copy\n"
5921                 "%val2      = OpLoad %f32 %inloc\n"
5922                 "%add       = OpFAdd %f32 %val1 %val2\n"
5923                 "             OpStore %outloc %add ${ACCESS}\n"
5924                 "             OpReturn\n"
5925                 "             OpFunctionEnd\n");
5926
5927         cases.push_back(CaseParameter("null",                                   ""));
5928         cases.push_back(CaseParameter("none",                                   "None"));
5929         cases.push_back(CaseParameter("volatile",                               "Volatile"));
5930         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
5931         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
5932         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
5933         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
5934
5935         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5936
5937         for (size_t ndx = 0; ndx < numElements; ++ndx)
5938                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5939
5940         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5941         {
5942                 map<string, string>             specializations;
5943                 ComputeShaderSpec               spec;
5944
5945                 specializations["ACCESS"] = cases[caseNdx].param;
5946                 spec.assembly = shaderTemplate.specialize(specializations);
5947                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5948                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5949                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5950
5951                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5952         }
5953
5954         return group.release();
5955 }
5956
5957 // Checks that we can get undefined values for various types, without exercising a computation with it.
5958 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5959 {
5960         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5961         vector<CaseParameter>                   cases;
5962         de::Random                                              rnd                             (deStringHash(group->getName()));
5963         const int                                               numElements             = 100;
5964         vector<float>                                   positiveFloats  (numElements, 0);
5965         vector<float>                                   negativeFloats  (numElements, 0);
5966         const StringTemplate                    shaderTemplate  (
5967                 string(getComputeAsmShaderPreamble()) +
5968
5969                 "OpSource GLSL 430\n"
5970                 "OpName %main           \"main\"\n"
5971                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5972
5973                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5974
5975                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5976                 "%uvec2     = OpTypeVector %u32 2\n"
5977                 "%fvec4     = OpTypeVector %f32 4\n"
5978                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
5979                 "%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
5980                 "%sampler   = OpTypeSampler\n"
5981                 "%simage    = OpTypeSampledImage %image\n"
5982                 "%const100  = OpConstant %u32 100\n"
5983                 "%uarr100   = OpTypeArray %i32 %const100\n"
5984                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
5985                 "%pointer   = OpTypePointer Function %i32\n"
5986                 + string(getComputeAsmInputOutputBuffer()) +
5987
5988                 "%id        = OpVariable %uvec3ptr Input\n"
5989                 "%zero      = OpConstant %i32 0\n"
5990
5991                 "%main      = OpFunction %void None %voidf\n"
5992                 "%label     = OpLabel\n"
5993
5994                 "%undef     = OpUndef ${TYPE}\n"
5995
5996                 "%idval     = OpLoad %uvec3 %id\n"
5997                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5998
5999                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
6000                 "%inval     = OpLoad %f32 %inloc\n"
6001                 "%neg       = OpFNegate %f32 %inval\n"
6002                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
6003                 "             OpStore %outloc %neg\n"
6004                 "             OpReturn\n"
6005                 "             OpFunctionEnd\n");
6006
6007         cases.push_back(CaseParameter("bool",                   "%bool"));
6008         cases.push_back(CaseParameter("sint32",                 "%i32"));
6009         cases.push_back(CaseParameter("uint32",                 "%u32"));
6010         cases.push_back(CaseParameter("float32",                "%f32"));
6011         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
6012         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
6013         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
6014         cases.push_back(CaseParameter("image",                  "%image"));
6015         cases.push_back(CaseParameter("sampler",                "%sampler"));
6016         cases.push_back(CaseParameter("sampledimage",   "%simage"));
6017         cases.push_back(CaseParameter("array",                  "%uarr100"));
6018         cases.push_back(CaseParameter("runtimearray",   "%f32arr"));
6019         cases.push_back(CaseParameter("struct",                 "%struct"));
6020         cases.push_back(CaseParameter("pointer",                "%pointer"));
6021
6022         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
6023
6024         for (size_t ndx = 0; ndx < numElements; ++ndx)
6025                 negativeFloats[ndx] = -positiveFloats[ndx];
6026
6027         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
6028         {
6029                 map<string, string>             specializations;
6030                 ComputeShaderSpec               spec;
6031
6032                 specializations["TYPE"] = cases[caseNdx].param;
6033                 spec.assembly = shaderTemplate.specialize(specializations);
6034                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
6035                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
6036                 spec.numWorkGroups = IVec3(numElements, 1, 1);
6037
6038                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
6039         }
6040
6041                 return group.release();
6042 }
6043
6044 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
6045 tcu::TestCaseGroup* createFloat16OpConstantCompositeGroup (tcu::TestContext& testCtx)
6046 {
6047         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
6048         vector<CaseParameter>                   cases;
6049         de::Random                                              rnd                             (deStringHash(group->getName()));
6050         const int                                               numElements             = 100;
6051         vector<float>                                   positiveFloats  (numElements, 0);
6052         vector<float>                                   negativeFloats  (numElements, 0);
6053         const StringTemplate                    shaderTemplate  (
6054                 "OpCapability Shader\n"
6055                 "OpCapability Float16\n"
6056                 "OpMemoryModel Logical GLSL450\n"
6057                 "OpEntryPoint GLCompute %main \"main\" %id\n"
6058                 "OpExecutionMode %main LocalSize 1 1 1\n"
6059                 "OpSource GLSL 430\n"
6060                 "OpName %main           \"main\"\n"
6061                 "OpName %id             \"gl_GlobalInvocationID\"\n"
6062
6063                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
6064
6065                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
6066
6067                 "%id        = OpVariable %uvec3ptr Input\n"
6068                 "%zero      = OpConstant %i32 0\n"
6069                 "%f16       = OpTypeFloat 16\n"
6070                 "%c_f16_0   = OpConstant %f16 0.0\n"
6071                 "%c_f16_0_5 = OpConstant %f16 0.5\n"
6072                 "%c_f16_1   = OpConstant %f16 1.0\n"
6073                 "%v2f16     = OpTypeVector %f16 2\n"
6074                 "%v3f16     = OpTypeVector %f16 3\n"
6075                 "%v4f16     = OpTypeVector %f16 4\n"
6076
6077                 "${CONSTANT}\n"
6078
6079                 "%main      = OpFunction %void None %voidf\n"
6080                 "%label     = OpLabel\n"
6081                 "%idval     = OpLoad %uvec3 %id\n"
6082                 "%x         = OpCompositeExtract %u32 %idval 0\n"
6083                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
6084                 "%inval     = OpLoad %f32 %inloc\n"
6085                 "%neg       = OpFNegate %f32 %inval\n"
6086                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
6087                 "             OpStore %outloc %neg\n"
6088                 "             OpReturn\n"
6089                 "             OpFunctionEnd\n");
6090
6091
6092         cases.push_back(CaseParameter("vector",                 "%const = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"));
6093         cases.push_back(CaseParameter("matrix",                 "%m3v3f16 = OpTypeMatrix %v3f16 3\n"
6094                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
6095                                                                                                         "%mat = OpConstantComposite %m3v3f16 %vec %vec %vec"));
6096         cases.push_back(CaseParameter("struct",                 "%m2v3f16 = OpTypeMatrix %v3f16 2\n"
6097                                                                                                         "%struct = OpTypeStruct %i32 %f16 %v3f16 %m2v3f16\n"
6098                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
6099                                                                                                         "%mat = OpConstantComposite %m2v3f16 %vec %vec\n"
6100                                                                                                         "%const = OpConstantComposite %struct %zero %c_f16_0_5 %vec %mat\n"));
6101         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %i32 %f16\n"
6102                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
6103                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
6104                                                                                                         "%st1val = OpConstantComposite %st1 %zero %c_f16_0_5\n"
6105                                                                                                         "%st2val = OpConstantComposite %st2 %zero %zero\n"
6106                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
6107
6108         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
6109
6110         for (size_t ndx = 0; ndx < numElements; ++ndx)
6111                 negativeFloats[ndx] = -positiveFloats[ndx];
6112
6113         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
6114         {
6115                 map<string, string>             specializations;
6116                 ComputeShaderSpec               spec;
6117
6118                 specializations["CONSTANT"] = cases[caseNdx].param;
6119                 spec.assembly = shaderTemplate.specialize(specializations);
6120                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
6121                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
6122                 spec.numWorkGroups = IVec3(numElements, 1, 1);
6123
6124                 spec.extensions.push_back("VK_KHR_16bit_storage");
6125                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
6126
6127                 spec.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
6128                 spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
6129
6130                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
6131         }
6132
6133         return group.release();
6134 }
6135
6136 const vector<deFloat16> squarize(const vector<deFloat16>& inData, const deUint32 argNo)
6137 {
6138         const size_t            inDataLength    = inData.size();
6139         vector<deFloat16>       result;
6140
6141         result.reserve(inDataLength * inDataLength);
6142
6143         if (argNo == 0)
6144         {
6145                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6146                         result.insert(result.end(), inData.begin(), inData.end());
6147         }
6148
6149         if (argNo == 1)
6150         {
6151                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6152                 {
6153                         const vector<deFloat16> tmp(inDataLength, inData[numIdx]);
6154
6155                         result.insert(result.end(), tmp.begin(), tmp.end());
6156                 }
6157         }
6158
6159         return result;
6160 }
6161
6162 const vector<deFloat16> squarizeVector(const vector<deFloat16>& inData, const deUint32 argNo)
6163 {
6164         vector<deFloat16>       vec;
6165         vector<deFloat16>       result;
6166
6167         // Create vectors. vec will contain each possible pair from inData
6168         {
6169                 const size_t    inDataLength    = inData.size();
6170
6171                 DE_ASSERT(inDataLength <= 64);
6172
6173                 vec.reserve(2 * inDataLength * inDataLength);
6174
6175                 for (size_t numIdxX = 0; numIdxX < inDataLength; ++numIdxX)
6176                 for (size_t numIdxY = 0; numIdxY < inDataLength; ++numIdxY)
6177                 {
6178                         vec.push_back(inData[numIdxX]);
6179                         vec.push_back(inData[numIdxY]);
6180                 }
6181         }
6182
6183         // Create vector pairs. result will contain each possible pair from vec
6184         {
6185                 const size_t    coordsPerVector = 2;
6186                 const size_t    vectorsCount    = vec.size() / coordsPerVector;
6187
6188                 result.reserve(coordsPerVector * vectorsCount * vectorsCount);
6189
6190                 if (argNo == 0)
6191                 {
6192                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6193                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6194                         {
6195                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6196                                         result.push_back(vec[coordsPerVector * numIdxY + coordNdx]);
6197                         }
6198                 }
6199
6200                 if (argNo == 1)
6201                 {
6202                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6203                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6204                         {
6205                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6206                                         result.push_back(vec[coordsPerVector * numIdxX + coordNdx]);
6207                         }
6208                 }
6209         }
6210
6211         return result;
6212 }
6213
6214 struct fp16isNan                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isNaN(); } };
6215 struct fp16isInf                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isInf(); } };
6216 struct fp16isEqual                      { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() == in2.asFloat(); } };
6217 struct fp16isUnequal            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() != in2.asFloat(); } };
6218 struct fp16isLess                       { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <  in2.asFloat(); } };
6219 struct fp16isGreater            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >  in2.asFloat(); } };
6220 struct fp16isLessOrEqual        { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <= in2.asFloat(); } };
6221 struct fp16isGreaterOrEqual     { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >= in2.asFloat(); } };
6222
6223 template <class TestedLogicalFunction, bool onlyTestFunc, bool unationModeAnd, bool nanSupported>
6224 bool compareFP16Logical (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
6225 {
6226         if (inputs.size() != 2 || outputAllocs.size() != 1)
6227                 return false;
6228
6229         vector<deUint8> input1Bytes;
6230         vector<deUint8> input2Bytes;
6231
6232         inputs[0].getBytes(input1Bytes);
6233         inputs[1].getBytes(input2Bytes);
6234
6235         const deUint32                  denormModesCount                        = 2;
6236         const deFloat16                 float16one                                      = tcu::Float16(1.0f).bits();
6237         const deFloat16                 float16zero                                     = tcu::Float16(0.0f).bits();
6238         const tcu::Float16              zero                                            = tcu::Float16::zero(1);
6239         const deFloat16* const  outputAsFP16                            = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
6240         const deFloat16* const  input1AsFP16                            = reinterpret_cast<deFloat16* const>(&input1Bytes.front());
6241         const deFloat16* const  input2AsFP16                            = reinterpret_cast<deFloat16* const>(&input2Bytes.front());
6242         deUint32                                successfulRuns                          = denormModesCount;
6243         std::string                             results[denormModesCount];
6244         TestedLogicalFunction   testedLogicalFunction;
6245
6246         for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6247         {
6248                 const bool flushToZero = (denormMode == 1);
6249
6250                 for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deFloat16); ++idx)
6251                 {
6252                         const tcu::Float16      f1pre                   = tcu::Float16(input1AsFP16[idx]);
6253                         const tcu::Float16      f2pre                   = tcu::Float16(input2AsFP16[idx]);
6254                         const tcu::Float16      f1                              = (flushToZero && f1pre.isDenorm()) ? zero : f1pre;
6255                         const tcu::Float16      f2                              = (flushToZero && f2pre.isDenorm()) ? zero : f2pre;
6256                         deFloat16                       expectedOutput  = float16zero;
6257
6258                         if (onlyTestFunc)
6259                         {
6260                                 if (testedLogicalFunction(f1, f2))
6261                                         expectedOutput = float16one;
6262                         }
6263                         else
6264                         {
6265                                 const bool      f1nan   = f1.isNaN();
6266                                 const bool      f2nan   = f2.isNaN();
6267
6268                                 // Skip NaN floats if not supported by implementation
6269                                 if (!nanSupported && (f1nan || f2nan))
6270                                         continue;
6271
6272                                 if (unationModeAnd)
6273                                 {
6274                                         const bool      ordered         = !f1nan && !f2nan;
6275
6276                                         if (ordered && testedLogicalFunction(f1, f2))
6277                                                 expectedOutput = float16one;
6278                                 }
6279                                 else
6280                                 {
6281                                         const bool      unordered       = f1nan || f2nan;
6282
6283                                         if (unordered || testedLogicalFunction(f1, f2))
6284                                                 expectedOutput = float16one;
6285                                 }
6286                         }
6287
6288                         if (outputAsFP16[idx] != expectedOutput)
6289                         {
6290                                 std::ostringstream str;
6291
6292                                 str << "ERROR: Sub-case #" << idx
6293                                         << " flushToZero:" << flushToZero
6294                                         << std::hex
6295                                         << " failed, inputs: 0x" << f1.bits()
6296                                         << ";0x" << f2.bits()
6297                                         << " output: 0x" << outputAsFP16[idx]
6298                                         << " expected output: 0x" << expectedOutput;
6299
6300                                 results[denormMode] = str.str();
6301
6302                                 successfulRuns--;
6303
6304                                 break;
6305                         }
6306                 }
6307         }
6308
6309         if (successfulRuns == 0)
6310                 for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6311                         log << TestLog::Message << results[denormMode] << TestLog::EndMessage;
6312
6313         return successfulRuns > 0;
6314 }
6315
6316 } // anonymous
6317
6318 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
6319 {
6320         struct NameCodePair { string name, code; };
6321         RGBA                                                    defaultColors[4];
6322         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
6323         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
6324         map<string, string>                             fragments                               = passthruFragments();
6325         const NameCodePair                              tests[]                                 =
6326         {
6327                 {"unknown", "OpSource Unknown 321"},
6328                 {"essl", "OpSource ESSL 310"},
6329                 {"glsl", "OpSource GLSL 450"},
6330                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
6331                 {"opencl_c", "OpSource OpenCL_C 120"},
6332                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
6333                 {"file", opsourceGLSLWithFile},
6334                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
6335                 // Longest possible source string: SPIR-V limits instructions to 65535
6336                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
6337                 // contain 65530 UTF8 characters (one word each) plus one last word
6338                 // containing 3 ASCII characters and \0.
6339                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
6340         };
6341
6342         getDefaultColors(defaultColors);
6343         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6344         {
6345                 fragments["debug"] = tests[testNdx].code;
6346                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6347         }
6348
6349         return opSourceTests.release();
6350 }
6351
6352 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
6353 {
6354         struct NameCodePair { string name, code; };
6355         RGBA                                                            defaultColors[4];
6356         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
6357         map<string, string>                                     fragments                       = passthruFragments();
6358         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
6359         const NameCodePair                                      tests[]                         =
6360         {
6361                 {"empty", opsource + "OpSourceContinued \"\""},
6362                 {"short", opsource + "OpSourceContinued \"abcde\""},
6363                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
6364                 // Longest possible source string: SPIR-V limits instructions to 65535
6365                 // words, of which the first one is OpSourceContinued/length; the rest
6366                 // will contain 65533 UTF8 characters (one word each) plus one last word
6367                 // containing 3 ASCII characters and \0.
6368                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
6369         };
6370
6371         getDefaultColors(defaultColors);
6372         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6373         {
6374                 fragments["debug"] = tests[testNdx].code;
6375                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6376         }
6377
6378         return opSourceTests.release();
6379 }
6380 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
6381 {
6382         RGBA                                                             defaultColors[4];
6383         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
6384         map<string, string>                                      fragments;
6385         getDefaultColors(defaultColors);
6386         fragments["debug"]                      =
6387                 "%name = OpString \"name\"\n";
6388
6389         fragments["pre_main"]   =
6390                 "OpNoLine\n"
6391                 "OpNoLine\n"
6392                 "OpLine %name 1 1\n"
6393                 "OpNoLine\n"
6394                 "OpLine %name 1 1\n"
6395                 "OpLine %name 1 1\n"
6396                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6397                 "OpNoLine\n"
6398                 "OpLine %name 1 1\n"
6399                 "OpNoLine\n"
6400                 "OpLine %name 1 1\n"
6401                 "OpLine %name 1 1\n"
6402                 "%second_param1 = OpFunctionParameter %v4f32\n"
6403                 "OpNoLine\n"
6404                 "OpNoLine\n"
6405                 "%label_secondfunction = OpLabel\n"
6406                 "OpNoLine\n"
6407                 "OpReturnValue %second_param1\n"
6408                 "OpFunctionEnd\n"
6409                 "OpNoLine\n"
6410                 "OpNoLine\n";
6411
6412         fragments["testfun"]            =
6413                 // A %test_code function that returns its argument unchanged.
6414                 "OpNoLine\n"
6415                 "OpNoLine\n"
6416                 "OpLine %name 1 1\n"
6417                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6418                 "OpNoLine\n"
6419                 "%param1 = OpFunctionParameter %v4f32\n"
6420                 "OpNoLine\n"
6421                 "OpNoLine\n"
6422                 "%label_testfun = OpLabel\n"
6423                 "OpNoLine\n"
6424                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6425                 "OpReturnValue %val1\n"
6426                 "OpFunctionEnd\n"
6427                 "OpLine %name 1 1\n"
6428                 "OpNoLine\n";
6429
6430         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
6431
6432         return opLineTests.release();
6433 }
6434
6435 tcu::TestCaseGroup* createOpModuleProcessedTests(tcu::TestContext& testCtx)
6436 {
6437         RGBA                                                            defaultColors[4];
6438         de::MovePtr<tcu::TestCaseGroup>         opModuleProcessedTests                  (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "OpModuleProcessed instruction"));
6439         map<string, string>                                     fragments;
6440         std::vector<std::string>                        noExtensions;
6441         GraphicsResources                                       resources;
6442
6443         getDefaultColors(defaultColors);
6444         resources.verifyBinary = veryfiBinaryShader;
6445         resources.spirvVersion = SPIRV_VERSION_1_3;
6446
6447         fragments["moduleprocessed"]                                                    =
6448                 "OpModuleProcessed \"VULKAN CTS\"\n"
6449                 "OpModuleProcessed \"Negative values\"\n"
6450                 "OpModuleProcessed \"Date: 2017/09/21\"\n";
6451
6452         fragments["pre_main"]   =
6453                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6454                 "%second_param1 = OpFunctionParameter %v4f32\n"
6455                 "%label_secondfunction = OpLabel\n"
6456                 "OpReturnValue %second_param1\n"
6457                 "OpFunctionEnd\n";
6458
6459         fragments["testfun"]            =
6460                 // A %test_code function that returns its argument unchanged.
6461                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6462                 "%param1 = OpFunctionParameter %v4f32\n"
6463                 "%label_testfun = OpLabel\n"
6464                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6465                 "OpReturnValue %val1\n"
6466                 "OpFunctionEnd\n";
6467
6468         createTestsForAllStages ("opmoduleprocessed", defaultColors, defaultColors, fragments, resources, noExtensions, opModuleProcessedTests.get());
6469
6470         return opModuleProcessedTests.release();
6471 }
6472
6473
6474 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
6475 {
6476         RGBA                                                                                                    defaultColors[4];
6477         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
6478         map<string, string>                                                                             fragments;
6479         std::vector<std::pair<std::string, std::string> >               problemStrings;
6480
6481         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
6482         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
6483         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
6484         getDefaultColors(defaultColors);
6485
6486         fragments["debug"]                      =
6487                 "%other_name = OpString \"other_name\"\n";
6488
6489         fragments["pre_main"]   =
6490                 "OpLine %file_name 32 0\n"
6491                 "OpLine %file_name 32 32\n"
6492                 "OpLine %file_name 32 40\n"
6493                 "OpLine %other_name 32 40\n"
6494                 "OpLine %other_name 0 100\n"
6495                 "OpLine %other_name 0 4294967295\n"
6496                 "OpLine %other_name 4294967295 0\n"
6497                 "OpLine %other_name 32 40\n"
6498                 "OpLine %file_name 0 0\n"
6499                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6500                 "OpLine %file_name 1 0\n"
6501                 "%second_param1 = OpFunctionParameter %v4f32\n"
6502                 "OpLine %file_name 1 3\n"
6503                 "OpLine %file_name 1 2\n"
6504                 "%label_secondfunction = OpLabel\n"
6505                 "OpLine %file_name 0 2\n"
6506                 "OpReturnValue %second_param1\n"
6507                 "OpFunctionEnd\n"
6508                 "OpLine %file_name 0 2\n"
6509                 "OpLine %file_name 0 2\n";
6510
6511         fragments["testfun"]            =
6512                 // A %test_code function that returns its argument unchanged.
6513                 "OpLine %file_name 1 0\n"
6514                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6515                 "OpLine %file_name 16 330\n"
6516                 "%param1 = OpFunctionParameter %v4f32\n"
6517                 "OpLine %file_name 14 442\n"
6518                 "%label_testfun = OpLabel\n"
6519                 "OpLine %file_name 11 1024\n"
6520                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6521                 "OpLine %file_name 2 97\n"
6522                 "OpReturnValue %val1\n"
6523                 "OpFunctionEnd\n"
6524                 "OpLine %file_name 5 32\n";
6525
6526         for (size_t i = 0; i < problemStrings.size(); ++i)
6527         {
6528                 map<string, string> testFragments = fragments;
6529                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
6530                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
6531         }
6532
6533         return opLineTests.release();
6534 }
6535
6536 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
6537 {
6538         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
6539         RGBA                                                    colors[4];
6540
6541
6542         const char                                              functionStart[] =
6543                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6544                 "%param1 = OpFunctionParameter %v4f32\n"
6545                 "%lbl    = OpLabel\n";
6546
6547         const char                                              functionEnd[]   =
6548                 "OpReturnValue %transformed_param\n"
6549                 "OpFunctionEnd\n";
6550
6551         struct NameConstantsCode
6552         {
6553                 string name;
6554                 string constants;
6555                 string code;
6556         };
6557
6558         NameConstantsCode tests[] =
6559         {
6560                 {
6561                         "vec4",
6562                         "%cnull = OpConstantNull %v4f32\n",
6563                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
6564                 },
6565                 {
6566                         "float",
6567                         "%cnull = OpConstantNull %f32\n",
6568                         "%vp = OpVariable %fp_v4f32 Function\n"
6569                         "%v  = OpLoad %v4f32 %vp\n"
6570                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
6571                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
6572                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
6573                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
6574                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
6575                 },
6576                 {
6577                         "bool",
6578                         "%cnull             = OpConstantNull %bool\n",
6579                         "%v                 = OpVariable %fp_v4f32 Function\n"
6580                         "                     OpStore %v %param1\n"
6581                         "                     OpSelectionMerge %false_label None\n"
6582                         "                     OpBranchConditional %cnull %true_label %false_label\n"
6583                         "%true_label        = OpLabel\n"
6584                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
6585                         "                     OpBranch %false_label\n"
6586                         "%false_label       = OpLabel\n"
6587                         "%transformed_param = OpLoad %v4f32 %v\n"
6588                 },
6589                 {
6590                         "i32",
6591                         "%cnull             = OpConstantNull %i32\n",
6592                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
6593                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
6594                         "                     OpSelectionMerge %false_label None\n"
6595                         "                     OpBranchConditional %b %true_label %false_label\n"
6596                         "%true_label        = OpLabel\n"
6597                         "                     OpStore %v %param1\n"
6598                         "                     OpBranch %false_label\n"
6599                         "%false_label       = OpLabel\n"
6600                         "%transformed_param = OpLoad %v4f32 %v\n"
6601                 },
6602                 {
6603                         "struct",
6604                         "%stype             = OpTypeStruct %f32 %v4f32\n"
6605                         "%fp_stype          = OpTypePointer Function %stype\n"
6606                         "%cnull             = OpConstantNull %stype\n",
6607                         "%v                 = OpVariable %fp_stype Function %cnull\n"
6608                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
6609                         "%f_val             = OpLoad %v4f32 %f\n"
6610                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
6611                 },
6612                 {
6613                         "array",
6614                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
6615                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
6616                         "%cnull             = OpConstantNull %a4_v4f32\n",
6617                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
6618                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6619                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
6620                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
6621                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
6622                         "%f_val             = OpLoad %v4f32 %f\n"
6623                         "%f1_val            = OpLoad %v4f32 %f1\n"
6624                         "%f2_val            = OpLoad %v4f32 %f2\n"
6625                         "%f3_val            = OpLoad %v4f32 %f3\n"
6626                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
6627                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
6628                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
6629                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
6630                 },
6631                 {
6632                         "matrix",
6633                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
6634                         "%cnull             = OpConstantNull %mat4x4_f32\n",
6635                         // Our null matrix * any vector should result in a zero vector.
6636                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
6637                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
6638                 }
6639         };
6640
6641         getHalfColorsFullAlpha(colors);
6642
6643         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6644         {
6645                 map<string, string> fragments;
6646                 fragments["pre_main"] = tests[testNdx].constants;
6647                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6648                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
6649         }
6650         return opConstantNullTests.release();
6651 }
6652 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
6653 {
6654         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
6655         RGBA                                                    inputColors[4];
6656         RGBA                                                    outputColors[4];
6657
6658
6659         const char                                              functionStart[]  =
6660                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6661                 "%param1 = OpFunctionParameter %v4f32\n"
6662                 "%lbl    = OpLabel\n";
6663
6664         const char                                              functionEnd[]           =
6665                 "OpReturnValue %transformed_param\n"
6666                 "OpFunctionEnd\n";
6667
6668         struct NameConstantsCode
6669         {
6670                 string name;
6671                 string constants;
6672                 string code;
6673         };
6674
6675         NameConstantsCode tests[] =
6676         {
6677                 {
6678                         "vec4",
6679
6680                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
6681                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
6682                 },
6683                 {
6684                         "struct",
6685
6686                         "%stype             = OpTypeStruct %v4f32 %f32\n"
6687                         "%fp_stype          = OpTypePointer Function %stype\n"
6688                         "%f32_n_1           = OpConstant %f32 -1.0\n"
6689                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
6690                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
6691                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
6692
6693                         "%v                 = OpVariable %fp_stype Function %cval\n"
6694                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6695                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
6696                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
6697                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
6698                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
6699                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
6700                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
6701                 },
6702                 {
6703                         // [1|0|0|0.5] [x] = x + 0.5
6704                         // [0|1|0|0.5] [y] = y + 0.5
6705                         // [0|0|1|0.5] [z] = z + 0.5
6706                         // [0|0|0|1  ] [1] = 1
6707                         "matrix",
6708
6709                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
6710                         "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
6711                         "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
6712                         "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
6713                         "%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"
6714                         "%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",
6715
6716                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
6717                 },
6718                 {
6719                         "array",
6720
6721                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6722                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6723                         "%f32_n_1             = OpConstant %f32 -1.0\n"
6724                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
6725                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
6726
6727                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
6728                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
6729                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
6730                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
6731                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
6732                         "%f_val               = OpLoad %f32 %f\n"
6733                         "%f1_val              = OpLoad %f32 %f1\n"
6734                         "%f2_val              = OpLoad %f32 %f2\n"
6735                         "%f3_val              = OpLoad %f32 %f3\n"
6736                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
6737                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
6738                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
6739                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
6740                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6741                 },
6742                 {
6743                         //
6744                         // [
6745                         //   {
6746                         //      0.0,
6747                         //      [ 1.0, 1.0, 1.0, 1.0]
6748                         //   },
6749                         //   {
6750                         //      1.0,
6751                         //      [ 0.0, 0.5, 0.0, 0.0]
6752                         //   }, //     ^^^
6753                         //   {
6754                         //      0.0,
6755                         //      [ 1.0, 1.0, 1.0, 1.0]
6756                         //   }
6757                         // ]
6758                         "array_of_struct_of_array",
6759
6760                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6761                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6762                         "%stype               = OpTypeStruct %f32 %a4f32\n"
6763                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
6764                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
6765                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
6766                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6767                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
6768                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
6769                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
6770
6771                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
6772                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
6773                         "%f_l                 = OpLoad %f32 %f\n"
6774                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
6775                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6776                 }
6777         };
6778
6779         getHalfColorsFullAlpha(inputColors);
6780         outputColors[0] = RGBA(255, 255, 255, 255);
6781         outputColors[1] = RGBA(255, 127, 127, 255);
6782         outputColors[2] = RGBA(127, 255, 127, 255);
6783         outputColors[3] = RGBA(127, 127, 255, 255);
6784
6785         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6786         {
6787                 map<string, string> fragments;
6788                 fragments["pre_main"] = tests[testNdx].constants;
6789                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6790                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
6791         }
6792         return opConstantCompositeTests.release();
6793 }
6794
6795 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
6796 {
6797         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
6798         RGBA                                                    inputColors[4];
6799         RGBA                                                    outputColors[4];
6800         map<string, string>                             fragments;
6801
6802         // vec4 test_code(vec4 param) {
6803         //   vec4 result = param;
6804         //   for (int i = 0; i < 4; ++i) {
6805         //     if (i == 0) result[i] = 0.;
6806         //     else        result[i] = 1. - result[i];
6807         //   }
6808         //   return result;
6809         // }
6810         const char                                              function[]                      =
6811                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6812                 "%param1    = OpFunctionParameter %v4f32\n"
6813                 "%lbl       = OpLabel\n"
6814                 "%iptr      = OpVariable %fp_i32 Function\n"
6815                 "%result    = OpVariable %fp_v4f32 Function\n"
6816                 "             OpStore %iptr %c_i32_0\n"
6817                 "             OpStore %result %param1\n"
6818                 "             OpBranch %loop\n"
6819
6820                 // Loop entry block.
6821                 "%loop      = OpLabel\n"
6822                 "%ival      = OpLoad %i32 %iptr\n"
6823                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6824                 "             OpLoopMerge %exit %if_entry None\n"
6825                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
6826
6827                 // Merge block for loop.
6828                 "%exit      = OpLabel\n"
6829                 "%ret       = OpLoad %v4f32 %result\n"
6830                 "             OpReturnValue %ret\n"
6831
6832                 // If-statement entry block.
6833                 "%if_entry  = OpLabel\n"
6834                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6835                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
6836                 "             OpSelectionMerge %if_exit None\n"
6837                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
6838
6839                 // False branch for if-statement.
6840                 "%if_false  = OpLabel\n"
6841                 "%val       = OpLoad %f32 %loc\n"
6842                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
6843                 "             OpStore %loc %sub\n"
6844                 "             OpBranch %if_exit\n"
6845
6846                 // Merge block for if-statement.
6847                 "%if_exit   = OpLabel\n"
6848                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6849                 "             OpStore %iptr %ival_next\n"
6850                 "             OpBranch %loop\n"
6851
6852                 // True branch for if-statement.
6853                 "%if_true   = OpLabel\n"
6854                 "             OpStore %loc %c_f32_0\n"
6855                 "             OpBranch %if_exit\n"
6856
6857                 "             OpFunctionEnd\n";
6858
6859         fragments["testfun"]    = function;
6860
6861         inputColors[0]                  = RGBA(127, 127, 127, 0);
6862         inputColors[1]                  = RGBA(127, 0,   0,   0);
6863         inputColors[2]                  = RGBA(0,   127, 0,   0);
6864         inputColors[3]                  = RGBA(0,   0,   127, 0);
6865
6866         outputColors[0]                 = RGBA(0, 128, 128, 255);
6867         outputColors[1]                 = RGBA(0, 255, 255, 255);
6868         outputColors[2]                 = RGBA(0, 128, 255, 255);
6869         outputColors[3]                 = RGBA(0, 255, 128, 255);
6870
6871         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6872
6873         return group.release();
6874 }
6875
6876 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
6877 {
6878         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
6879         RGBA                                                    inputColors[4];
6880         RGBA                                                    outputColors[4];
6881         map<string, string>                             fragments;
6882
6883         const char                                              typesAndConstants[]     =
6884                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6885                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6886                 "%c_f32_p6  = OpConstant %f32 0.6\n"
6887                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6888
6889         // vec4 test_code(vec4 param) {
6890         //   vec4 result = param;
6891         //   for (int i = 0; i < 4; ++i) {
6892         //     switch (i) {
6893         //       case 0: result[i] += .2; break;
6894         //       case 1: result[i] += .6; break;
6895         //       case 2: result[i] += .4; break;
6896         //       case 3: result[i] += .8; break;
6897         //       default: break; // unreachable
6898         //     }
6899         //   }
6900         //   return result;
6901         // }
6902         const char                                              function[]                      =
6903                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6904                 "%param1    = OpFunctionParameter %v4f32\n"
6905                 "%lbl       = OpLabel\n"
6906                 "%iptr      = OpVariable %fp_i32 Function\n"
6907                 "%result    = OpVariable %fp_v4f32 Function\n"
6908                 "             OpStore %iptr %c_i32_0\n"
6909                 "             OpStore %result %param1\n"
6910                 "             OpBranch %loop\n"
6911
6912                 // Loop entry block.
6913                 "%loop      = OpLabel\n"
6914                 "%ival      = OpLoad %i32 %iptr\n"
6915                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6916                 "             OpLoopMerge %exit %switch_exit None\n"
6917                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
6918
6919                 // Merge block for loop.
6920                 "%exit      = OpLabel\n"
6921                 "%ret       = OpLoad %v4f32 %result\n"
6922                 "             OpReturnValue %ret\n"
6923
6924                 // Switch-statement entry block.
6925                 "%switch_entry   = OpLabel\n"
6926                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
6927                 "%val            = OpLoad %f32 %loc\n"
6928                 "                  OpSelectionMerge %switch_exit None\n"
6929                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6930
6931                 "%case2          = OpLabel\n"
6932                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
6933                 "                  OpStore %loc %addp4\n"
6934                 "                  OpBranch %switch_exit\n"
6935
6936                 "%switch_default = OpLabel\n"
6937                 "                  OpUnreachable\n"
6938
6939                 "%case3          = OpLabel\n"
6940                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
6941                 "                  OpStore %loc %addp8\n"
6942                 "                  OpBranch %switch_exit\n"
6943
6944                 "%case0          = OpLabel\n"
6945                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
6946                 "                  OpStore %loc %addp2\n"
6947                 "                  OpBranch %switch_exit\n"
6948
6949                 // Merge block for switch-statement.
6950                 "%switch_exit    = OpLabel\n"
6951                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
6952                 "                  OpStore %iptr %ival_next\n"
6953                 "                  OpBranch %loop\n"
6954
6955                 "%case1          = OpLabel\n"
6956                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
6957                 "                  OpStore %loc %addp6\n"
6958                 "                  OpBranch %switch_exit\n"
6959
6960                 "                  OpFunctionEnd\n";
6961
6962         fragments["pre_main"]   = typesAndConstants;
6963         fragments["testfun"]    = function;
6964
6965         inputColors[0]                  = RGBA(127, 27,  127, 51);
6966         inputColors[1]                  = RGBA(127, 0,   0,   51);
6967         inputColors[2]                  = RGBA(0,   27,  0,   51);
6968         inputColors[3]                  = RGBA(0,   0,   127, 51);
6969
6970         outputColors[0]                 = RGBA(178, 180, 229, 255);
6971         outputColors[1]                 = RGBA(178, 153, 102, 255);
6972         outputColors[2]                 = RGBA(51,  180, 102, 255);
6973         outputColors[3]                 = RGBA(51,  153, 229, 255);
6974
6975         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6976
6977         return group.release();
6978 }
6979
6980 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
6981 {
6982         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
6983         RGBA                                                    inputColors[4];
6984         RGBA                                                    outputColors[4];
6985         map<string, string>                             fragments;
6986
6987         const char                                              decorations[]           =
6988                 "OpDecorate %array_group         ArrayStride 4\n"
6989                 "OpDecorate %struct_member_group Offset 0\n"
6990                 "%array_group         = OpDecorationGroup\n"
6991                 "%struct_member_group = OpDecorationGroup\n"
6992
6993                 "OpDecorate %group1 RelaxedPrecision\n"
6994                 "OpDecorate %group3 RelaxedPrecision\n"
6995                 "OpDecorate %group3 Invariant\n"
6996                 "OpDecorate %group3 Restrict\n"
6997                 "%group0 = OpDecorationGroup\n"
6998                 "%group1 = OpDecorationGroup\n"
6999                 "%group3 = OpDecorationGroup\n";
7000
7001         const char                                              typesAndConstants[]     =
7002                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
7003                 "%struct1   = OpTypeStruct %a3f32\n"
7004                 "%struct2   = OpTypeStruct %a3f32\n"
7005                 "%fp_struct1 = OpTypePointer Function %struct1\n"
7006                 "%fp_struct2 = OpTypePointer Function %struct2\n"
7007                 "%c_f32_2    = OpConstant %f32 2.\n"
7008                 "%c_f32_n2   = OpConstant %f32 -2.\n"
7009
7010                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
7011                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
7012                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
7013                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
7014
7015         const char                                              function[]                      =
7016                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7017                 "%param     = OpFunctionParameter %v4f32\n"
7018                 "%entry     = OpLabel\n"
7019                 "%result    = OpVariable %fp_v4f32 Function\n"
7020                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
7021                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
7022                 "             OpStore %result %param\n"
7023                 "             OpStore %v_struct1 %c_struct1\n"
7024                 "             OpStore %v_struct2 %c_struct2\n"
7025                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
7026                 "%val1      = OpLoad %f32 %ptr1\n"
7027                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
7028                 "%val2      = OpLoad %f32 %ptr2\n"
7029                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
7030                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7031                 "%val       = OpLoad %f32 %ptr\n"
7032                 "%addresult = OpFAdd %f32 %addvalues %val\n"
7033                 "             OpStore %ptr %addresult\n"
7034                 "%ret       = OpLoad %v4f32 %result\n"
7035                 "             OpReturnValue %ret\n"
7036                 "             OpFunctionEnd\n";
7037
7038         struct CaseNameDecoration
7039         {
7040                 string name;
7041                 string decoration;
7042         };
7043
7044         CaseNameDecoration tests[] =
7045         {
7046                 {
7047                         "same_decoration_group_on_multiple_types",
7048                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
7049                 },
7050                 {
7051                         "empty_decoration_group",
7052                         "OpGroupDecorate %group0      %a3f32\n"
7053                         "OpGroupDecorate %group0      %result\n"
7054                 },
7055                 {
7056                         "one_element_decoration_group",
7057                         "OpGroupDecorate %array_group %a3f32\n"
7058                 },
7059                 {
7060                         "multiple_elements_decoration_group",
7061                         "OpGroupDecorate %group3      %v_struct1\n"
7062                 },
7063                 {
7064                         "multiple_decoration_groups_on_same_variable",
7065                         "OpGroupDecorate %group0      %v_struct2\n"
7066                         "OpGroupDecorate %group1      %v_struct2\n"
7067                         "OpGroupDecorate %group3      %v_struct2\n"
7068                 },
7069                 {
7070                         "same_decoration_group_multiple_times",
7071                         "OpGroupDecorate %group1      %addvalues\n"
7072                         "OpGroupDecorate %group1      %addvalues\n"
7073                         "OpGroupDecorate %group1      %addvalues\n"
7074                 },
7075
7076         };
7077
7078         getHalfColorsFullAlpha(inputColors);
7079         getHalfColorsFullAlpha(outputColors);
7080
7081         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
7082         {
7083                 fragments["decoration"] = decorations + tests[idx].decoration;
7084                 fragments["pre_main"]   = typesAndConstants;
7085                 fragments["testfun"]    = function;
7086
7087                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
7088         }
7089
7090         return group.release();
7091 }
7092
7093 struct SpecConstantTwoIntGraphicsCase
7094 {
7095         const char*             caseName;
7096         const char*             scDefinition0;
7097         const char*             scDefinition1;
7098         const char*             scResultType;
7099         const char*             scOperation;
7100         deInt32                 scActualValue0;
7101         deInt32                 scActualValue1;
7102         const char*             resultOperation;
7103         RGBA                    expectedColors[4];
7104         deInt32                 scActualValueLength;
7105
7106                                         SpecConstantTwoIntGraphicsCase (const char*             name,
7107                                                                                                         const char*             definition0,
7108                                                                                                         const char*             definition1,
7109                                                                                                         const char*             resultType,
7110                                                                                                         const char*             operation,
7111                                                                                                         const deInt32   value0,
7112                                                                                                         const deInt32   value1,
7113                                                                                                         const char*             resultOp,
7114                                                                                                         const RGBA              (&output)[4],
7115                                                                                                         const deInt32   valueLength = sizeof(deInt32))
7116                                                 : caseName                              (name)
7117                                                 , scDefinition0                 (definition0)
7118                                                 , scDefinition1                 (definition1)
7119                                                 , scResultType                  (resultType)
7120                                                 , scOperation                   (operation)
7121                                                 , scActualValue0                (value0)
7122                                                 , scActualValue1                (value1)
7123                                                 , resultOperation               (resultOp)
7124                                                 , scActualValueLength   (valueLength)
7125         {
7126                 expectedColors[0] = output[0];
7127                 expectedColors[1] = output[1];
7128                 expectedColors[2] = output[2];
7129                 expectedColors[3] = output[3];
7130         }
7131 };
7132
7133 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
7134 {
7135         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
7136         vector<SpecConstantTwoIntGraphicsCase>  cases;
7137         RGBA                                                    inputColors[4];
7138         RGBA                                                    outputColors0[4];
7139         RGBA                                                    outputColors1[4];
7140         RGBA                                                    outputColors2[4];
7141
7142         const deInt32                                   m1AsFloat16                     = 0xbc00; // -1(fp16) == 1 01111 0000000000 == 1011 1100 0000 0000
7143
7144         const char      decorations1[]                  =
7145                 "OpDecorate %sc_0  SpecId 0\n"
7146                 "OpDecorate %sc_1  SpecId 1\n";
7147
7148         const char      typesAndConstants1[]    =
7149                 "${OPTYPE_DEFINITIONS:opt}"
7150                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
7151                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
7152                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
7153
7154         const char      function1[]                             =
7155                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7156                 "%param     = OpFunctionParameter %v4f32\n"
7157                 "%label     = OpLabel\n"
7158                 "%result    = OpVariable %fp_v4f32 Function\n"
7159                 "${TYPE_CONVERT:opt}"
7160                 "             OpStore %result %param\n"
7161                 "%gen       = ${GEN_RESULT}\n"
7162                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
7163                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
7164                 "%val       = OpLoad %f32 %loc\n"
7165                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7166                 "             OpStore %loc %add\n"
7167                 "%ret       = OpLoad %v4f32 %result\n"
7168                 "             OpReturnValue %ret\n"
7169                 "             OpFunctionEnd\n";
7170
7171         inputColors[0] = RGBA(127, 127, 127, 255);
7172         inputColors[1] = RGBA(127, 0,   0,   255);
7173         inputColors[2] = RGBA(0,   127, 0,   255);
7174         inputColors[3] = RGBA(0,   0,   127, 255);
7175
7176         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
7177         outputColors0[0] = RGBA(255, 127, 127, 255);
7178         outputColors0[1] = RGBA(255, 0,   0,   255);
7179         outputColors0[2] = RGBA(128, 127, 0,   255);
7180         outputColors0[3] = RGBA(128, 0,   127, 255);
7181
7182         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
7183         outputColors1[0] = RGBA(127, 255, 127, 255);
7184         outputColors1[1] = RGBA(127, 128, 0,   255);
7185         outputColors1[2] = RGBA(0,   255, 0,   255);
7186         outputColors1[3] = RGBA(0,   128, 127, 255);
7187
7188         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
7189         outputColors2[0] = RGBA(127, 127, 255, 255);
7190         outputColors2[1] = RGBA(127, 0,   128, 255);
7191         outputColors2[2] = RGBA(0,   127, 128, 255);
7192         outputColors2[3] = RGBA(0,   0,   255, 255);
7193
7194         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
7195         const char addZeroToSc32[]              = "OpIAdd %i32 %c_i32_0 %sc_op32";
7196         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
7197         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
7198
7199         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
7200         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
7201         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
7202         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
7203         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
7204         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7205         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7206         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
7207         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
7208         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
7209         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
7210         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
7211         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
7212         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
7213         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
7214         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
7215         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7216         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
7217         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
7218         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
7219         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7220         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
7221         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
7222         cases.push_back(SpecConstantTwoIntGraphicsCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                             42,             24,             selectTrueUsingSc,      outputColors2));
7223         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7224         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7225         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7226         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7227         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
7228         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
7229         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
7230         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
7231         cases.push_back(SpecConstantTwoIntGraphicsCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                                   -1,             0,              addZeroToSc32,          outputColors0));
7232         // -1082130432 stored as 32-bit two's complement is the binary representation of -1 as IEEE-754 Float
7233         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                                   -1082130432, 0, addZeroToSc32,          outputColors0));
7234         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                                   m1AsFloat16, 0, addZeroToSc32,          outputColors0, sizeof(deFloat16)));
7235         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
7236
7237         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
7238         {
7239                 map<string, string>                     specializations;
7240                 map<string, string>                     fragments;
7241                 SpecConstants                           specConstants;
7242                 PushConstants                           noPushConstants;
7243                 GraphicsResources                       noResources;
7244                 GraphicsInterfaces                      noInterfaces;
7245                 vector<string>                          extensions;
7246                 VulkanFeatures                          requiredFeatures;
7247
7248                 // Special SPIR-V code for SConvert-case
7249                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
7250                 {
7251                         requiredFeatures.coreFeatures.shaderInt16 = VK_TRUE;
7252                         fragments["capability"]                                 = "OpCapability Int16\n";                                       // Adds 16-bit integer capability
7253                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                            // Adds 16-bit integer type
7254                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpSConvert %i32 %sc_op\n";        // Converts 16-bit integer to 32-bit integer
7255                 }
7256
7257                 // Special SPIR-V code for FConvert-case
7258                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
7259                 {
7260                         requiredFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
7261                         fragments["capability"]                                 = "OpCapability Float64\n";                                     // Adds 64-bit float capability
7262                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                            // Adds 64-bit float type
7263                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 64-bit float to 32-bit integer
7264                 }
7265
7266                 // Special SPIR-V code for FConvert-case for 16-bit floats
7267                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
7268                 {
7269                         extensions.push_back("VK_KHR_shader_float16_int8");
7270                         requiredFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
7271                         fragments["capability"]                                 = "OpCapability Float16\n";                                     // Adds 16-bit float capability
7272                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                            // Adds 16-bit float type
7273                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 16-bit float to 32-bit integer
7274                 }
7275
7276                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
7277                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
7278                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
7279                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
7280                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
7281
7282                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
7283                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
7284                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
7285
7286                 specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
7287                 specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
7288
7289                 createTestsForAllStages(
7290                         cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants,
7291                         noPushConstants, noResources, noInterfaces, extensions, requiredFeatures, group.get());
7292         }
7293
7294         const char      decorations2[]                  =
7295                 "OpDecorate %sc_0  SpecId 0\n"
7296                 "OpDecorate %sc_1  SpecId 1\n"
7297                 "OpDecorate %sc_2  SpecId 2\n";
7298
7299         const char      typesAndConstants2[]    =
7300                 "%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
7301                 "%vec3_undef  = OpUndef %v3i32\n"
7302
7303                 "%sc_0        = OpSpecConstant %i32 0\n"
7304                 "%sc_1        = OpSpecConstant %i32 0\n"
7305                 "%sc_2        = OpSpecConstant %i32 0\n"
7306                 "%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0      0\n"                                                 // (sc_0, 0,    0)
7307                 "%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0      1\n"                                                 // (0,    sc_1, 0)
7308                 "%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0      2\n"                                                 // (0,    0,    sc_2)
7309                 "%sc_vec3_0_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
7310                 "%sc_vec3_1_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
7311                 "%sc_vec3_2_s = OpSpecConstantOp %v3i32 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
7312                 "%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
7313                 "%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
7314                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
7315                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
7316                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
7317                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
7318                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";                                                             // (sc_2 - sc_0) * sc_1
7319
7320         const char      function2[]                             =
7321                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7322                 "%param     = OpFunctionParameter %v4f32\n"
7323                 "%label     = OpLabel\n"
7324                 "%result    = OpVariable %fp_v4f32 Function\n"
7325                 "             OpStore %result %param\n"
7326                 "%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
7327                 "%val       = OpLoad %f32 %loc\n"
7328                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7329                 "             OpStore %loc %add\n"
7330                 "%ret       = OpLoad %v4f32 %result\n"
7331                 "             OpReturnValue %ret\n"
7332                 "             OpFunctionEnd\n";
7333
7334         map<string, string>     fragments;
7335         SpecConstants           specConstants;
7336
7337         fragments["decoration"] = decorations2;
7338         fragments["pre_main"]   = typesAndConstants2;
7339         fragments["testfun"]    = function2;
7340
7341         specConstants.append<deInt32>(56789);
7342         specConstants.append<deInt32>(-2);
7343         specConstants.append<deInt32>(56788);
7344
7345         createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
7346
7347         return group.release();
7348 }
7349
7350 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
7351 {
7352         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
7353         RGBA                                                    inputColors[4];
7354         RGBA                                                    outputColors1[4];
7355         RGBA                                                    outputColors2[4];
7356         RGBA                                                    outputColors3[4];
7357         RGBA                                                    outputColors4[4];
7358         map<string, string>                             fragments1;
7359         map<string, string>                             fragments2;
7360         map<string, string>                             fragments3;
7361         map<string, string>                             fragments4;
7362         std::vector<std::string>                extensions4;
7363         GraphicsResources                               resources4;
7364         VulkanFeatures                                  vulkanFeatures4;
7365
7366         const char      typesAndConstants1[]    =
7367                 "%c_f32_p2  = OpConstant %f32 0.2\n"
7368                 "%c_f32_p4  = OpConstant %f32 0.4\n"
7369                 "%c_f32_p5  = OpConstant %f32 0.5\n"
7370                 "%c_f32_p8  = OpConstant %f32 0.8\n";
7371
7372         // vec4 test_code(vec4 param) {
7373         //   vec4 result = param;
7374         //   for (int i = 0; i < 4; ++i) {
7375         //     float operand;
7376         //     switch (i) {
7377         //       case 0: operand = .2; break;
7378         //       case 1: operand = .5; break;
7379         //       case 2: operand = .4; break;
7380         //       case 3: operand = .0; break;
7381         //       default: break; // unreachable
7382         //     }
7383         //     result[i] += operand;
7384         //   }
7385         //   return result;
7386         // }
7387         const char      function1[]                             =
7388                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7389                 "%param1    = OpFunctionParameter %v4f32\n"
7390                 "%lbl       = OpLabel\n"
7391                 "%iptr      = OpVariable %fp_i32 Function\n"
7392                 "%result    = OpVariable %fp_v4f32 Function\n"
7393                 "             OpStore %iptr %c_i32_0\n"
7394                 "             OpStore %result %param1\n"
7395                 "             OpBranch %loop\n"
7396
7397                 "%loop      = OpLabel\n"
7398                 "%ival      = OpLoad %i32 %iptr\n"
7399                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
7400                 "             OpLoopMerge %exit %phi None\n"
7401                 "             OpBranchConditional %lt_4 %entry %exit\n"
7402
7403                 "%entry     = OpLabel\n"
7404                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
7405                 "%val       = OpLoad %f32 %loc\n"
7406                 "             OpSelectionMerge %phi None\n"
7407                 "             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
7408
7409                 "%case0     = OpLabel\n"
7410                 "             OpBranch %phi\n"
7411                 "%case1     = OpLabel\n"
7412                 "             OpBranch %phi\n"
7413                 "%case2     = OpLabel\n"
7414                 "             OpBranch %phi\n"
7415                 "%case3     = OpLabel\n"
7416                 "             OpBranch %phi\n"
7417
7418                 "%default   = OpLabel\n"
7419                 "             OpUnreachable\n"
7420
7421                 "%phi       = OpLabel\n"
7422                 "%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
7423                 "%add       = OpFAdd %f32 %val %operand\n"
7424                 "             OpStore %loc %add\n"
7425                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
7426                 "             OpStore %iptr %ival_next\n"
7427                 "             OpBranch %loop\n"
7428
7429                 "%exit      = OpLabel\n"
7430                 "%ret       = OpLoad %v4f32 %result\n"
7431                 "             OpReturnValue %ret\n"
7432
7433                 "             OpFunctionEnd\n";
7434
7435         fragments1["pre_main"]  = typesAndConstants1;
7436         fragments1["testfun"]   = function1;
7437
7438         getHalfColorsFullAlpha(inputColors);
7439
7440         outputColors1[0]                = RGBA(178, 255, 229, 255);
7441         outputColors1[1]                = RGBA(178, 127, 102, 255);
7442         outputColors1[2]                = RGBA(51,  255, 102, 255);
7443         outputColors1[3]                = RGBA(51,  127, 229, 255);
7444
7445         createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
7446
7447         const char      typesAndConstants2[]    =
7448                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7449
7450         // Add .4 to the second element of the given parameter.
7451         const char      function2[]                             =
7452                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7453                 "%param     = OpFunctionParameter %v4f32\n"
7454                 "%entry     = OpLabel\n"
7455                 "%result    = OpVariable %fp_v4f32 Function\n"
7456                 "             OpStore %result %param\n"
7457                 "%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7458                 "%val       = OpLoad %f32 %loc\n"
7459                 "             OpBranch %phi\n"
7460
7461                 "%phi        = OpLabel\n"
7462                 "%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
7463                 "%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
7464                 "%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
7465                 "%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
7466                 "%still_loop = OpSLessThan %bool %step %c_i32_2\n"
7467                 "              OpLoopMerge %exit %phi None\n"
7468                 "              OpBranchConditional %still_loop %phi %exit\n"
7469
7470                 "%exit       = OpLabel\n"
7471                 "              OpStore %loc %accum\n"
7472                 "%ret        = OpLoad %v4f32 %result\n"
7473                 "              OpReturnValue %ret\n"
7474
7475                 "              OpFunctionEnd\n";
7476
7477         fragments2["pre_main"]  = typesAndConstants2;
7478         fragments2["testfun"]   = function2;
7479
7480         outputColors2[0]                        = RGBA(127, 229, 127, 255);
7481         outputColors2[1]                        = RGBA(127, 102, 0,   255);
7482         outputColors2[2]                        = RGBA(0,   229, 0,   255);
7483         outputColors2[3]                        = RGBA(0,   102, 127, 255);
7484
7485         createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
7486
7487         const char      typesAndConstants3[]    =
7488                 "%true      = OpConstantTrue %bool\n"
7489                 "%false     = OpConstantFalse %bool\n"
7490                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7491
7492         // Swap the second and the third element of the given parameter.
7493         const char      function3[]                             =
7494                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7495                 "%param     = OpFunctionParameter %v4f32\n"
7496                 "%entry     = OpLabel\n"
7497                 "%result    = OpVariable %fp_v4f32 Function\n"
7498                 "             OpStore %result %param\n"
7499                 "%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
7500                 "%a_init    = OpLoad %f32 %a_loc\n"
7501                 "%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
7502                 "%b_init    = OpLoad %f32 %b_loc\n"
7503                 "             OpBranch %phi\n"
7504
7505                 "%phi        = OpLabel\n"
7506                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7507                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
7508                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
7509                 "              OpLoopMerge %exit %phi None\n"
7510                 "              OpBranchConditional %still_loop %phi %exit\n"
7511
7512                 "%exit       = OpLabel\n"
7513                 "              OpStore %a_loc %a_next\n"
7514                 "              OpStore %b_loc %b_next\n"
7515                 "%ret        = OpLoad %v4f32 %result\n"
7516                 "              OpReturnValue %ret\n"
7517
7518                 "              OpFunctionEnd\n";
7519
7520         fragments3["pre_main"]  = typesAndConstants3;
7521         fragments3["testfun"]   = function3;
7522
7523         outputColors3[0]                        = RGBA(127, 127, 127, 255);
7524         outputColors3[1]                        = RGBA(127, 0,   0,   255);
7525         outputColors3[2]                        = RGBA(0,   0,   127, 255);
7526         outputColors3[3]                        = RGBA(0,   127, 0,   255);
7527
7528         createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
7529
7530         const char      typesAndConstants4[]    =
7531                 "%f16        = OpTypeFloat 16\n"
7532                 "%v4f16      = OpTypeVector %f16 4\n"
7533                 "%fp_f16     = OpTypePointer Function %f16\n"
7534                 "%fp_v4f16   = OpTypePointer Function %v4f16\n"
7535                 "%true       = OpConstantTrue %bool\n"
7536                 "%false      = OpConstantFalse %bool\n"
7537                 "%c_f32_p2   = OpConstant %f32 0.2\n";
7538
7539         // Swap the second and the third element of the given parameter.
7540         const char      function4[]                             =
7541                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7542                 "%param      = OpFunctionParameter %v4f32\n"
7543                 "%entry      = OpLabel\n"
7544                 "%result     = OpVariable %fp_v4f16 Function\n"
7545                 "%param16    = OpFConvert %v4f16 %param\n"
7546                 "              OpStore %result %param16\n"
7547                 "%a_loc      = OpAccessChain %fp_f16 %result %c_i32_1\n"
7548                 "%a_init     = OpLoad %f16 %a_loc\n"
7549                 "%b_loc      = OpAccessChain %fp_f16 %result %c_i32_2\n"
7550                 "%b_init     = OpLoad %f16 %b_loc\n"
7551                 "              OpBranch %phi\n"
7552
7553                 "%phi        = OpLabel\n"
7554                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7555                 "%a_next     = OpPhi %f16  %a_init %entry %b_next %phi\n"
7556                 "%b_next     = OpPhi %f16  %b_init %entry %a_next %phi\n"
7557                 "              OpLoopMerge %exit %phi None\n"
7558                 "              OpBranchConditional %still_loop %phi %exit\n"
7559
7560                 "%exit       = OpLabel\n"
7561                 "              OpStore %a_loc %a_next\n"
7562                 "              OpStore %b_loc %b_next\n"
7563                 "%ret16      = OpLoad %v4f16 %result\n"
7564                 "%ret        = OpFConvert %v4f32 %ret16\n"
7565                 "              OpReturnValue %ret\n"
7566
7567                 "              OpFunctionEnd\n";
7568
7569         fragments4["pre_main"]          = typesAndConstants4;
7570         fragments4["testfun"]           = function4;
7571         fragments4["capability"]        = "OpCapability StorageUniformBufferBlock16\n";
7572         fragments4["extension"]         = "OpExtension \"SPV_KHR_16bit_storage\"";
7573
7574         extensions4.push_back("VK_KHR_16bit_storage");
7575         extensions4.push_back("VK_KHR_shader_float16_int8");
7576
7577         vulkanFeatures4.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
7578         vulkanFeatures4.extFloat16Int8  = EXTFLOAT16INT8FEATURES_FLOAT16;
7579
7580         outputColors4[0]                        = RGBA(127, 127, 127, 255);
7581         outputColors4[1]                        = RGBA(127, 0,   0,   255);
7582         outputColors4[2]                        = RGBA(0,   0,   127, 255);
7583         outputColors4[3]                        = RGBA(0,   127, 0,   255);
7584
7585         createTestsForAllStages("swap16", inputColors, outputColors4, fragments4, resources4, extensions4, group.get(), vulkanFeatures4);
7586
7587         return group.release();
7588 }
7589
7590 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
7591 {
7592         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
7593         RGBA                                                    inputColors[4];
7594         RGBA                                                    outputColors[4];
7595
7596         // With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
7597         // For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
7598         // only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
7599         // On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
7600         const char                                              constantsAndTypes[]      =
7601                 "%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
7602                 "%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
7603                 "%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
7604                 "%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
7605                 "%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n";
7606
7607         const char                                              function[]       =
7608                 "%test_code      = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7609                 "%param          = OpFunctionParameter %v4f32\n"
7610                 "%label          = OpLabel\n"
7611                 "%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
7612                 "%var2           = OpVariable %fp_f32 Function\n"
7613                 "%red            = OpCompositeExtract %f32 %param 0\n"
7614                 "%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
7615                 "                  OpStore %var2 %plus_red\n"
7616                 "%val1           = OpLoad %f32 %var1\n"
7617                 "%val2           = OpLoad %f32 %var2\n"
7618                 "%mul            = OpFMul %f32 %val1 %val2\n"
7619                 "%add            = OpFAdd %f32 %mul %c_f32_n1\n"
7620                 "%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
7621                 "%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
7622                 "%success        = OpLogicalOr %bool %is0 %isn1n24\n"
7623                 "%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
7624                 "%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
7625                 "                  OpReturnValue %ret\n"
7626                 "                  OpFunctionEnd\n";
7627
7628         struct CaseNameDecoration
7629         {
7630                 string name;
7631                 string decoration;
7632         };
7633
7634
7635         CaseNameDecoration tests[] = {
7636                 {"multiplication",      "OpDecorate %mul NoContraction"},
7637                 {"addition",            "OpDecorate %add NoContraction"},
7638                 {"both",                        "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
7639         };
7640
7641         getHalfColorsFullAlpha(inputColors);
7642
7643         for (deUint8 idx = 0; idx < 4; ++idx)
7644         {
7645                 inputColors[idx].setRed(0);
7646                 outputColors[idx] = RGBA(0, 0, 0, 255);
7647         }
7648
7649         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
7650         {
7651                 map<string, string> fragments;
7652
7653                 fragments["decoration"] = tests[testNdx].decoration;
7654                 fragments["pre_main"] = constantsAndTypes;
7655                 fragments["testfun"] = function;
7656
7657                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
7658         }
7659
7660         return group.release();
7661 }
7662
7663 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
7664 {
7665         de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
7666         RGBA                                                    colors[4];
7667
7668         const char                                              constantsAndTypes[]      =
7669                 "%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
7670                 "%fp_a2f32          = OpTypePointer Function %a2f32\n"
7671                 "%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
7672                 "%fp_stype          = OpTypePointer Function %stype\n";
7673
7674         const char                                              function[]       =
7675                 "%test_code         = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7676                 "%param1            = OpFunctionParameter %v4f32\n"
7677                 "%lbl               = OpLabel\n"
7678                 "%v1                = OpVariable %fp_v4f32 Function\n"
7679                 "%v2                = OpVariable %fp_a2f32 Function\n"
7680                 "%v3                = OpVariable %fp_f32 Function\n"
7681                 "%v                 = OpVariable %fp_stype Function\n"
7682                 "%vv                = OpVariable %fp_stype Function\n"
7683                 "%vvv               = OpVariable %fp_f32 Function\n"
7684
7685                 "                     OpStore %v1 %c_v4f32_1_1_1_1\n"
7686                 "                     OpStore %v2 %c_a2f32_1\n"
7687                 "                     OpStore %v3 %c_f32_1\n"
7688
7689                 "%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
7690                 "%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
7691                 "%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
7692                 "%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
7693                 "%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
7694                 "%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
7695
7696                 "                    OpStore %p_v4f32 %v1_v ${access_type}\n"
7697                 "                    OpStore %p_a2f32 %v2_v ${access_type}\n"
7698                 "                    OpStore %p_f32 %v3_v ${access_type}\n"
7699
7700                 "                    OpCopyMemory %vv %v ${access_type}\n"
7701                 "                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
7702
7703                 "%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
7704                 "%v_f32_2          = OpLoad %f32 %p_f32_2\n"
7705                 "%v_f32_3          = OpLoad %f32 %vvv\n"
7706
7707                 "%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
7708                 "%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
7709                 "                    OpReturnValue %ret2\n"
7710                 "                    OpFunctionEnd\n";
7711
7712         struct NameMemoryAccess
7713         {
7714                 string name;
7715                 string accessType;
7716         };
7717
7718
7719         NameMemoryAccess tests[] =
7720         {
7721                 { "none", "" },
7722                 { "volatile", "Volatile" },
7723                 { "aligned",  "Aligned 1" },
7724                 { "volatile_aligned",  "Volatile|Aligned 1" },
7725                 { "nontemporal_aligned",  "Nontemporal|Aligned 1" },
7726                 { "volatile_nontemporal",  "Volatile|Nontemporal" },
7727                 { "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
7728         };
7729
7730         getHalfColorsFullAlpha(colors);
7731
7732         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
7733         {
7734                 map<string, string> fragments;
7735                 map<string, string> memoryAccess;
7736                 memoryAccess["access_type"] = tests[testNdx].accessType;
7737
7738                 fragments["pre_main"] = constantsAndTypes;
7739                 fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
7740                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
7741         }
7742         return memoryAccessTests.release();
7743 }
7744 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
7745 {
7746         de::MovePtr<tcu::TestCaseGroup>         opUndefTests             (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
7747         RGBA                                                            defaultColors[4];
7748         map<string, string>                                     fragments;
7749         getDefaultColors(defaultColors);
7750
7751         // First, simple cases that don't do anything with the OpUndef result.
7752         struct NameCodePair { string name, decl, type; };
7753         const NameCodePair tests[] =
7754         {
7755                 {"bool", "", "%bool"},
7756                 {"vec2uint32", "", "%v2u32"},
7757                 {"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown", "%type"},
7758                 {"sampler", "%type = OpTypeSampler", "%type"},
7759                 {"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img", "%type"},
7760                 {"pointer", "", "%fp_i32"},
7761                 {"runtimearray", "%type = OpTypeRuntimeArray %f32", "%type"},
7762                 {"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100", "%type"},
7763                 {"struct", "%type = OpTypeStruct %f32 %i32 %u32", "%type"}};
7764         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
7765         {
7766                 fragments["undef_type"] = tests[testNdx].type;
7767                 fragments["testfun"] = StringTemplate(
7768                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7769                         "%param1 = OpFunctionParameter %v4f32\n"
7770                         "%label_testfun = OpLabel\n"
7771                         "%undef = OpUndef ${undef_type}\n"
7772                         "OpReturnValue %param1\n"
7773                         "OpFunctionEnd\n").specialize(fragments);
7774                 fragments["pre_main"] = tests[testNdx].decl;
7775                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
7776         }
7777         fragments.clear();
7778
7779         fragments["testfun"] =
7780                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7781                 "%param1 = OpFunctionParameter %v4f32\n"
7782                 "%label_testfun = OpLabel\n"
7783                 "%undef = OpUndef %f32\n"
7784                 "%zero = OpFMul %f32 %undef %c_f32_0\n"
7785                 "%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
7786                 "%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
7787                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7788                 "%b = OpFAdd %f32 %a %actually_zero\n"
7789                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
7790                 "OpReturnValue %ret\n"
7791                 "OpFunctionEnd\n";
7792
7793         createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7794
7795         fragments["testfun"] =
7796                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7797                 "%param1 = OpFunctionParameter %v4f32\n"
7798                 "%label_testfun = OpLabel\n"
7799                 "%undef = OpUndef %i32\n"
7800                 "%zero = OpIMul %i32 %undef %c_i32_0\n"
7801                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7802                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7803                 "OpReturnValue %ret\n"
7804                 "OpFunctionEnd\n";
7805
7806         createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7807
7808         fragments["testfun"] =
7809                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7810                 "%param1 = OpFunctionParameter %v4f32\n"
7811                 "%label_testfun = OpLabel\n"
7812                 "%undef = OpUndef %u32\n"
7813                 "%zero = OpIMul %u32 %undef %c_i32_0\n"
7814                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7815                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7816                 "OpReturnValue %ret\n"
7817                 "OpFunctionEnd\n";
7818
7819         createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7820
7821         fragments["testfun"] =
7822                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7823                 "%param1 = OpFunctionParameter %v4f32\n"
7824                 "%label_testfun = OpLabel\n"
7825                 "%undef = OpUndef %v4f32\n"
7826                 "%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
7827                 "%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
7828                 "%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
7829                 "%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
7830                 "%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
7831                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7832                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7833                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7834                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7835                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7836                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7837                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7838                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7839                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7840                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7841                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7842                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7843                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7844                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7845                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7846                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7847                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7848                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7849                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7850                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7851                 "OpReturnValue %ret\n"
7852                 "OpFunctionEnd\n";
7853
7854         createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7855
7856         fragments["pre_main"] =
7857                 "%m2x2f32 = OpTypeMatrix %v2f32 2\n";
7858         fragments["testfun"] =
7859                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7860                 "%param1 = OpFunctionParameter %v4f32\n"
7861                 "%label_testfun = OpLabel\n"
7862                 "%undef = OpUndef %m2x2f32\n"
7863                 "%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
7864                 "%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
7865                 "%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
7866                 "%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
7867                 "%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
7868                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7869                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7870                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7871                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7872                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7873                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7874                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7875                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7876                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7877                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7878                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7879                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7880                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7881                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7882                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7883                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7884                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7885                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7886                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7887                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7888                 "OpReturnValue %ret\n"
7889                 "OpFunctionEnd\n";
7890
7891         createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
7892
7893         return opUndefTests.release();
7894 }
7895
7896 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
7897 {
7898         const RGBA              inputColors[4]          =
7899         {
7900                 RGBA(0,         0,              0,              255),
7901                 RGBA(0,         0,              255,    255),
7902                 RGBA(0,         255,    0,              255),
7903                 RGBA(0,         255,    255,    255)
7904         };
7905
7906         const RGBA              expectedColors[4]       =
7907         {
7908                 RGBA(255,        0,              0,              255),
7909                 RGBA(255,        0,              0,              255),
7910                 RGBA(255,        0,              0,              255),
7911                 RGBA(255,        0,              0,              255)
7912         };
7913
7914         const struct SingleFP16Possibility
7915         {
7916                 const char* name;
7917                 const char* constant;  // Value to assign to %test_constant.
7918                 float           valueAsFloat;
7919                 const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
7920         }                               tests[]                         =
7921         {
7922                 {
7923                         "negative",
7924                         "-0x1.3p1\n",
7925                         -constructNormalizedFloat(1, 0x300000),
7926                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7927                 }, // -19
7928                 {
7929                         "positive",
7930                         "0x1.0p7\n",
7931                         constructNormalizedFloat(7, 0x000000),
7932                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7933                 },  // +128
7934                 // SPIR-V requires that OpQuantizeToF16 flushes
7935                 // any numbers that would end up denormalized in F16 to zero.
7936                 {
7937                         "denorm",
7938                         "0x0.0006p-126\n",
7939                         std::ldexp(1.5f, -140),
7940                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7941                 },  // denorm
7942                 {
7943                         "negative_denorm",
7944                         "-0x0.0006p-126\n",
7945                         -std::ldexp(1.5f, -140),
7946                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7947                 }, // -denorm
7948                 {
7949                         "too_small",
7950                         "0x1.0p-16\n",
7951                         std::ldexp(1.0f, -16),
7952                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7953                 },     // too small positive
7954                 {
7955                         "negative_too_small",
7956                         "-0x1.0p-32\n",
7957                         -std::ldexp(1.0f, -32),
7958                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7959                 },      // too small negative
7960                 {
7961                         "negative_inf",
7962                         "-0x1.0p128\n",
7963                         -std::ldexp(1.0f, 128),
7964
7965                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7966                         "%inf = OpIsInf %bool %c\n"
7967                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7968                 },     // -inf to -inf
7969                 {
7970                         "inf",
7971                         "0x1.0p128\n",
7972                         std::ldexp(1.0f, 128),
7973
7974                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7975                         "%inf = OpIsInf %bool %c\n"
7976                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7977                 },     // +inf to +inf
7978                 {
7979                         "round_to_negative_inf",
7980                         "-0x1.0p32\n",
7981                         -std::ldexp(1.0f, 32),
7982
7983                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7984                         "%inf = OpIsInf %bool %c\n"
7985                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7986                 },     // round to -inf
7987                 {
7988                         "round_to_inf",
7989                         "0x1.0p16\n",
7990                         std::ldexp(1.0f, 16),
7991
7992                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7993                         "%inf = OpIsInf %bool %c\n"
7994                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7995                 },     // round to +inf
7996                 {
7997                         "nan",
7998                         "0x1.1p128\n",
7999                         std::numeric_limits<float>::quiet_NaN(),
8000
8001                         // Test for any NaN value, as NaNs are not preserved
8002                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
8003                         "%cond = OpIsNan %bool %direct_quant\n"
8004                 }, // nan
8005                 {
8006                         "negative_nan",
8007                         "-0x1.0001p128\n",
8008                         std::numeric_limits<float>::quiet_NaN(),
8009
8010                         // Test for any NaN value, as NaNs are not preserved
8011                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
8012                         "%cond = OpIsNan %bool %direct_quant\n"
8013                 } // -nan
8014         };
8015         const char*             constants                       =
8016                 "%test_constant = OpConstant %f32 ";  // The value will be test.constant.
8017
8018         StringTemplate  function                        (
8019                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8020                 "%param1        = OpFunctionParameter %v4f32\n"
8021                 "%label_testfun = OpLabel\n"
8022                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8023                 "%b             = OpFAdd %f32 %test_constant %a\n"
8024                 "%c             = OpQuantizeToF16 %f32 %b\n"
8025                 "${condition}\n"
8026                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8027                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
8028                 "                 OpReturnValue %retval\n"
8029                 "OpFunctionEnd\n"
8030         );
8031
8032         const char*             specDecorations         = "OpDecorate %test_constant SpecId 0\n";
8033         const char*             specConstants           =
8034                         "%test_constant = OpSpecConstant %f32 0.\n"
8035                         "%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
8036
8037         StringTemplate  specConstantFunction(
8038                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8039                 "%param1        = OpFunctionParameter %v4f32\n"
8040                 "%label_testfun = OpLabel\n"
8041                 "${condition}\n"
8042                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8043                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
8044                 "                 OpReturnValue %retval\n"
8045                 "OpFunctionEnd\n"
8046         );
8047
8048         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
8049         {
8050                 map<string, string>                                                             codeSpecialization;
8051                 map<string, string>                                                             fragments;
8052                 codeSpecialization["condition"]                                 = tests[idx].condition;
8053                 fragments["testfun"]                                                    = function.specialize(codeSpecialization);
8054                 fragments["pre_main"]                                                   = string(constants) + tests[idx].constant + "\n";
8055                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
8056         }
8057
8058         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
8059         {
8060                 map<string, string>                                                             codeSpecialization;
8061                 map<string, string>                                                             fragments;
8062                 SpecConstants                                                                   passConstants;
8063
8064                 codeSpecialization["condition"]                                 = tests[idx].condition;
8065                 fragments["testfun"]                                                    = specConstantFunction.specialize(codeSpecialization);
8066                 fragments["decoration"]                                                 = specDecorations;
8067                 fragments["pre_main"]                                                   = specConstants;
8068
8069                 passConstants.append<float>(tests[idx].valueAsFloat);
8070
8071                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
8072         }
8073 }
8074
8075 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
8076 {
8077         RGBA inputColors[4] =  {
8078                 RGBA(0,         0,              0,              255),
8079                 RGBA(0,         0,              255,    255),
8080                 RGBA(0,         255,    0,              255),
8081                 RGBA(0,         255,    255,    255)
8082         };
8083
8084         RGBA expectedColors[4] =
8085         {
8086                 RGBA(255,        0,              0,              255),
8087                 RGBA(255,        0,              0,              255),
8088                 RGBA(255,        0,              0,              255),
8089                 RGBA(255,        0,              0,              255)
8090         };
8091
8092         struct DualFP16Possibility
8093         {
8094                 const char* name;
8095                 const char* input;
8096                 float           inputAsFloat;
8097                 const char* possibleOutput1;
8098                 const char* possibleOutput2;
8099         } tests[] = {
8100                 {
8101                         "positive_round_up_or_round_down",
8102                         "0x1.3003p8",
8103                         constructNormalizedFloat(8, 0x300300),
8104                         "0x1.304p8",
8105                         "0x1.3p8"
8106                 },
8107                 {
8108                         "negative_round_up_or_round_down",
8109                         "-0x1.6008p-7",
8110                         -constructNormalizedFloat(-7, 0x600800),
8111                         "-0x1.6p-7",
8112                         "-0x1.604p-7"
8113                 },
8114                 {
8115                         "carry_bit",
8116                         "0x1.01ep2",
8117                         constructNormalizedFloat(2, 0x01e000),
8118                         "0x1.01cp2",
8119                         "0x1.02p2"
8120                 },
8121                 {
8122                         "carry_to_exponent",
8123                         "0x1.ffep1",
8124                         constructNormalizedFloat(1, 0xffe000),
8125                         "0x1.ffcp1",
8126                         "0x1.0p2"
8127                 },
8128         };
8129         StringTemplate constants (
8130                 "%input_const = OpConstant %f32 ${input}\n"
8131                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8132                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8133                 );
8134
8135         StringTemplate specConstants (
8136                 "%input_const = OpSpecConstant %f32 0.\n"
8137                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8138                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8139         );
8140
8141         const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
8142
8143         const char* function  =
8144                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8145                 "%param1        = OpFunctionParameter %v4f32\n"
8146                 "%label_testfun = OpLabel\n"
8147                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8148                 // For the purposes of this test we assume that 0.f will always get
8149                 // faithfully passed through the pipeline stages.
8150                 "%b             = OpFAdd %f32 %input_const %a\n"
8151                 "%c             = OpQuantizeToF16 %f32 %b\n"
8152                 "%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
8153                 "%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
8154                 "%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
8155                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8156                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
8157                 "                 OpReturnValue %retval\n"
8158                 "OpFunctionEnd\n";
8159
8160         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8161                 map<string, string>                                                                     fragments;
8162                 map<string, string>                                                                     constantSpecialization;
8163
8164                 constantSpecialization["input"]                                         = tests[idx].input;
8165                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8166                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8167                 fragments["testfun"]                                                            = function;
8168                 fragments["pre_main"]                                                           = constants.specialize(constantSpecialization);
8169                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
8170         }
8171
8172         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8173                 map<string, string>                                                                     fragments;
8174                 map<string, string>                                                                     constantSpecialization;
8175                 SpecConstants                                                                           passConstants;
8176
8177                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8178                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8179                 fragments["testfun"]                                                            = function;
8180                 fragments["decoration"]                                                         = specDecorations;
8181                 fragments["pre_main"]                                                           = specConstants.specialize(constantSpecialization);
8182
8183                 passConstants.append<float>(tests[idx].inputAsFloat);
8184
8185                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
8186         }
8187 }
8188
8189 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
8190 {
8191         de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
8192         createOpQuantizeSingleOptionTests(opQuantizeTests.get());
8193         createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
8194         return opQuantizeTests.release();
8195 }
8196
8197 struct ShaderPermutation
8198 {
8199         deUint8 vertexPermutation;
8200         deUint8 geometryPermutation;
8201         deUint8 tesscPermutation;
8202         deUint8 tessePermutation;
8203         deUint8 fragmentPermutation;
8204 };
8205
8206 ShaderPermutation getShaderPermutation(deUint8 inputValue)
8207 {
8208         ShaderPermutation       permutation =
8209         {
8210                 static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
8211                 static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
8212                 static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
8213                 static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
8214                 static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
8215         };
8216         return permutation;
8217 }
8218
8219 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
8220 {
8221         RGBA                                                            defaultColors[4];
8222         RGBA                                                            invertedColors[4];
8223         de::MovePtr<tcu::TestCaseGroup>         moduleTests                     (new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
8224
8225         getDefaultColors(defaultColors);
8226         getInvertedDefaultColors(invertedColors);
8227
8228         // Combined module tests
8229         {
8230                 // Shader stages: vertex and fragment
8231                 {
8232                         const ShaderElement combinedPipeline[]  =
8233                         {
8234                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8235                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8236                         };
8237
8238                         addFunctionCaseWithPrograms<InstanceContext>(
8239                                 moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline,
8240                                 createInstanceContext(combinedPipeline, map<string, string>()));
8241                 }
8242
8243                 // Shader stages: vertex, geometry and fragment
8244                 {
8245                         const ShaderElement combinedPipeline[]  =
8246                         {
8247                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8248                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8249                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8250                         };
8251
8252                         addFunctionCaseWithPrograms<InstanceContext>(
8253                                 moduleTests.get(), "same_module_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8254                                 createInstanceContext(combinedPipeline, map<string, string>()));
8255                 }
8256
8257                 // Shader stages: vertex, tessellation control, tessellation evaluation and fragment
8258                 {
8259                         const ShaderElement combinedPipeline[]  =
8260                         {
8261                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8262                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8263                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8264                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8265                         };
8266
8267                         addFunctionCaseWithPrograms<InstanceContext>(
8268                                 moduleTests.get(), "same_module_tessc_tesse", "", createCombinedModule, runAndVerifyDefaultPipeline,
8269                                 createInstanceContext(combinedPipeline, map<string, string>()));
8270                 }
8271
8272                 // Shader stages: vertex, tessellation control, tessellation evaluation, geometry and fragment
8273                 {
8274                         const ShaderElement combinedPipeline[]  =
8275                         {
8276                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8277                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8278                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8279                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8280                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8281                         };
8282
8283                         addFunctionCaseWithPrograms<InstanceContext>(
8284                                 moduleTests.get(), "same_module_tessc_tesse_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8285                                 createInstanceContext(combinedPipeline, map<string, string>()));
8286                 }
8287         }
8288
8289         const char* numbers[] =
8290         {
8291                 "1", "2"
8292         };
8293
8294         for (deInt8 idx = 0; idx < 32; ++idx)
8295         {
8296                 ShaderPermutation                       permutation             = getShaderPermutation(idx);
8297                 string                                          name                    = string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
8298                 const ShaderElement                     pipeline[]              =
8299                 {
8300                         ShaderElement("vert",   string("vert") +        numbers[permutation.vertexPermutation],         VK_SHADER_STAGE_VERTEX_BIT),
8301                         ShaderElement("geom",   string("geom") +        numbers[permutation.geometryPermutation],       VK_SHADER_STAGE_GEOMETRY_BIT),
8302                         ShaderElement("tessc",  string("tessc") +       numbers[permutation.tesscPermutation],          VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8303                         ShaderElement("tesse",  string("tesse") +       numbers[permutation.tessePermutation],          VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8304                         ShaderElement("frag",   string("frag") +        numbers[permutation.fragmentPermutation],       VK_SHADER_STAGE_FRAGMENT_BIT)
8305                 };
8306
8307                 // If there are an even number of swaps, then it should be no-op.
8308                 // If there are an odd number, the color should be flipped.
8309                 if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
8310                 {
8311                         addFunctionCaseWithPrograms<InstanceContext>(
8312                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8313                                         createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
8314                 }
8315                 else
8316                 {
8317                         addFunctionCaseWithPrograms<InstanceContext>(
8318                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8319                                         createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
8320                 }
8321         }
8322         return moduleTests.release();
8323 }
8324
8325 std::string getUnusedVarTestNamePiece(const std::string& prefix, ShaderTask task)
8326 {
8327         switch (task)
8328         {
8329                 case SHADER_TASK_NONE:                  return "";
8330                 case SHADER_TASK_NORMAL:                return prefix + "_normal";
8331                 case SHADER_TASK_UNUSED_VAR:    return prefix + "_unused_var";
8332                 case SHADER_TASK_UNUSED_FUNC:   return prefix + "_unused_func";
8333                 default:                                                DE_ASSERT(DE_FALSE);
8334         }
8335         // unreachable
8336         return "";
8337 }
8338
8339 std::string getShaderTaskIndexName(ShaderTaskIndex index)
8340 {
8341         switch (index)
8342         {
8343         case SHADER_TASK_INDEX_VERTEX:                  return "vertex";
8344         case SHADER_TASK_INDEX_GEOMETRY:                return "geom";
8345         case SHADER_TASK_INDEX_TESS_CONTROL:    return "tessc";
8346         case SHADER_TASK_INDEX_TESS_EVAL:               return "tesse";
8347         case SHADER_TASK_INDEX_FRAGMENT:                return "frag";
8348         default:                                                                DE_ASSERT(DE_FALSE);
8349         }
8350         // unreachable
8351         return "";
8352 }
8353
8354 std::string getUnusedVarTestName(const ShaderTaskArray& shaderTasks, const VariableLocation& location)
8355 {
8356         std::string testName = location.toString();
8357
8358         for (size_t i = 0; i < DE_LENGTH_OF_ARRAY(shaderTasks); ++i)
8359         {
8360                 if (shaderTasks[i] != SHADER_TASK_NONE)
8361                 {
8362                         testName += "_" + getUnusedVarTestNamePiece(getShaderTaskIndexName((ShaderTaskIndex)i), shaderTasks[i]);
8363                 }
8364         }
8365
8366         return testName;
8367 }
8368
8369 tcu::TestCaseGroup* createUnusedVariableTests(tcu::TestContext& testCtx)
8370 {
8371         de::MovePtr<tcu::TestCaseGroup>         moduleTests                             (new tcu::TestCaseGroup(testCtx, "unused_variables", "Graphics shaders with unused variables"));
8372
8373         ShaderTaskArray                                         shaderCombinations[]    =
8374         {
8375                 // Vertex                                       Geometry                                        Tess. Control                           Tess. Evaluation                        Fragment
8376                 { SHADER_TASK_UNUSED_VAR,       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8377                 { SHADER_TASK_UNUSED_FUNC,      SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8378                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_VAR  },
8379                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_FUNC },
8380                 { SHADER_TASK_NORMAL,           SHADER_TASK_UNUSED_VAR,         SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8381                 { SHADER_TASK_NORMAL,           SHADER_TASK_UNUSED_FUNC,        SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8382                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_VAR,         SHADER_TASK_NORMAL,                     SHADER_TASK_NORMAL      },
8383                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_FUNC,        SHADER_TASK_NORMAL,                     SHADER_TASK_NORMAL      },
8384                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NORMAL,                     SHADER_TASK_UNUSED_VAR,         SHADER_TASK_NORMAL      },
8385                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NORMAL,                     SHADER_TASK_UNUSED_FUNC,        SHADER_TASK_NORMAL      }
8386         };
8387
8388         const VariableLocation                          testLocations[] =
8389         {
8390                 // Set          Binding
8391                 { 0,            5                       },
8392                 { 5,            5                       },
8393         };
8394
8395         for (size_t combNdx = 0; combNdx < DE_LENGTH_OF_ARRAY(shaderCombinations); ++combNdx)
8396         {
8397                 for (size_t locationNdx = 0; locationNdx < DE_LENGTH_OF_ARRAY(testLocations); ++locationNdx)
8398                 {
8399                         const ShaderTaskArray&  shaderTasks             = shaderCombinations[combNdx];
8400                         const VariableLocation& location                = testLocations[locationNdx];
8401                         std::string                             testName                = getUnusedVarTestName(shaderTasks, location);
8402
8403                         addFunctionCaseWithPrograms<UnusedVariableContext>(
8404                                 moduleTests.get(), testName, "", createUnusedVariableModules, runAndVerifyUnusedVariablePipeline,
8405                                 createUnusedVariableContext(shaderTasks, location));
8406                 }
8407         }
8408
8409         return moduleTests.release();
8410 }
8411
8412 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
8413 {
8414         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
8415         RGBA defaultColors[4];
8416         getDefaultColors(defaultColors);
8417         map<string, string> fragments;
8418         fragments["pre_main"] =
8419                 "%c_f32_5 = OpConstant %f32 5.\n";
8420
8421         // A loop with a single block. The Continue Target is the loop block
8422         // itself. In SPIR-V terms, the "loop construct" contains no blocks at all
8423         // -- the "continue construct" forms the entire loop.
8424         fragments["testfun"] =
8425                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8426                 "%param1 = OpFunctionParameter %v4f32\n"
8427
8428                 "%entry = OpLabel\n"
8429                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8430                 "OpBranch %loop\n"
8431
8432                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8433                 "%loop = OpLabel\n"
8434                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8435                 "%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
8436                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8437                 "%val = OpFAdd %f32 %val1 %delta\n"
8438                 "%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
8439                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8440                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8441                 "OpLoopMerge %exit %loop None\n"
8442                 "OpBranchConditional %again %loop %exit\n"
8443
8444                 "%exit = OpLabel\n"
8445                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8446                 "OpReturnValue %result\n"
8447
8448                 "OpFunctionEnd\n";
8449
8450         createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
8451
8452         // Body comprised of multiple basic blocks.
8453         const StringTemplate multiBlock(
8454                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8455                 "%param1 = OpFunctionParameter %v4f32\n"
8456
8457                 "%entry = OpLabel\n"
8458                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8459                 "OpBranch %loop\n"
8460
8461                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8462                 "%loop = OpLabel\n"
8463                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
8464                 "%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
8465                 "%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
8466                 // There are several possibilities for the Continue Target below.  Each
8467                 // will be specialized into a separate test case.
8468                 "OpLoopMerge %exit ${continue_target} None\n"
8469                 "OpBranch %if\n"
8470
8471                 "%if = OpLabel\n"
8472                 ";delta_next = (delta > 0) ? -1 : 1;\n"
8473                 "%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
8474                 "OpSelectionMerge %gather DontFlatten\n"
8475                 "OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
8476
8477                 "%odd = OpLabel\n"
8478                 "OpBranch %gather\n"
8479
8480                 "%even = OpLabel\n"
8481                 "OpBranch %gather\n"
8482
8483                 "%gather = OpLabel\n"
8484                 "%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
8485                 "%val = OpFAdd %f32 %val1 %delta\n"
8486                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8487                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8488                 "OpBranchConditional %again %loop %exit\n"
8489
8490                 "%exit = OpLabel\n"
8491                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8492                 "OpReturnValue %result\n"
8493
8494                 "OpFunctionEnd\n");
8495
8496         map<string, string> continue_target;
8497
8498         // The Continue Target is the loop block itself.
8499         continue_target["continue_target"] = "%loop";
8500         fragments["testfun"] = multiBlock.specialize(continue_target);
8501         createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
8502
8503         // The Continue Target is at the end of the loop.
8504         continue_target["continue_target"] = "%gather";
8505         fragments["testfun"] = multiBlock.specialize(continue_target);
8506         createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
8507
8508         // A loop with continue statement.
8509         fragments["testfun"] =
8510                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8511                 "%param1 = OpFunctionParameter %v4f32\n"
8512
8513                 "%entry = OpLabel\n"
8514                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8515                 "OpBranch %loop\n"
8516
8517                 ";adds 4, 3, and 1 to %val0 (skips 2)\n"
8518                 "%loop = OpLabel\n"
8519                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8520                 "%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
8521                 "OpLoopMerge %exit %continue None\n"
8522                 "OpBranch %if\n"
8523
8524                 "%if = OpLabel\n"
8525                 ";skip if %count==2\n"
8526                 "%eq2 = OpIEqual %bool %count %c_i32_2\n"
8527                 "OpSelectionMerge %continue DontFlatten\n"
8528                 "OpBranchConditional %eq2 %continue %body\n"
8529
8530                 "%body = OpLabel\n"
8531                 "%fcount = OpConvertSToF %f32 %count\n"
8532                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8533                 "OpBranch %continue\n"
8534
8535                 "%continue = OpLabel\n"
8536                 "%val = OpPhi %f32 %val2 %body %val1 %if\n"
8537                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8538                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8539                 "OpBranchConditional %again %loop %exit\n"
8540
8541                 "%exit = OpLabel\n"
8542                 "%same = OpFSub %f32 %val %c_f32_8\n"
8543                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8544                 "OpReturnValue %result\n"
8545                 "OpFunctionEnd\n";
8546         createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
8547
8548         // A loop with break.
8549         fragments["testfun"] =
8550                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8551                 "%param1 = OpFunctionParameter %v4f32\n"
8552
8553                 "%entry = OpLabel\n"
8554                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8555                 "%dot = OpDot %f32 %param1 %param1\n"
8556                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8557                 "%zero = OpConvertFToU %u32 %div\n"
8558                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8559                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8560                 "OpBranch %loop\n"
8561
8562                 ";adds 4 and 3 to %val0 (exits early)\n"
8563                 "%loop = OpLabel\n"
8564                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8565                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8566                 "OpLoopMerge %exit %continue None\n"
8567                 "OpBranch %if\n"
8568
8569                 "%if = OpLabel\n"
8570                 ";end loop if %count==%two\n"
8571                 "%above2 = OpSGreaterThan %bool %count %two\n"
8572                 "OpSelectionMerge %continue DontFlatten\n"
8573                 "OpBranchConditional %above2 %body %exit\n"
8574
8575                 "%body = OpLabel\n"
8576                 "%fcount = OpConvertSToF %f32 %count\n"
8577                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8578                 "OpBranch %continue\n"
8579
8580                 "%continue = OpLabel\n"
8581                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8582                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8583                 "OpBranchConditional %again %loop %exit\n"
8584
8585                 "%exit = OpLabel\n"
8586                 "%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
8587                 "%same = OpFSub %f32 %val_post %c_f32_7\n"
8588                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8589                 "OpReturnValue %result\n"
8590                 "OpFunctionEnd\n";
8591         createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
8592
8593         // A loop with return.
8594         fragments["testfun"] =
8595                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8596                 "%param1 = OpFunctionParameter %v4f32\n"
8597
8598                 "%entry = OpLabel\n"
8599                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8600                 "%dot = OpDot %f32 %param1 %param1\n"
8601                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8602                 "%zero = OpConvertFToU %u32 %div\n"
8603                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8604                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8605                 "OpBranch %loop\n"
8606
8607                 ";returns early without modifying %param1\n"
8608                 "%loop = OpLabel\n"
8609                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8610                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8611                 "OpLoopMerge %exit %continue None\n"
8612                 "OpBranch %if\n"
8613
8614                 "%if = OpLabel\n"
8615                 ";return if %count==%two\n"
8616                 "%above2 = OpSGreaterThan %bool %count %two\n"
8617                 "OpSelectionMerge %continue DontFlatten\n"
8618                 "OpBranchConditional %above2 %body %early_exit\n"
8619
8620                 "%early_exit = OpLabel\n"
8621                 "OpReturnValue %param1\n"
8622
8623                 "%body = OpLabel\n"
8624                 "%fcount = OpConvertSToF %f32 %count\n"
8625                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8626                 "OpBranch %continue\n"
8627
8628                 "%continue = OpLabel\n"
8629                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8630                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8631                 "OpBranchConditional %again %loop %exit\n"
8632
8633                 "%exit = OpLabel\n"
8634                 ";should never get here, so return an incorrect result\n"
8635                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
8636                 "OpReturnValue %result\n"
8637                 "OpFunctionEnd\n";
8638         createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
8639
8640         // Continue inside a switch block to break to enclosing loop's merge block.
8641         // Matches roughly the following GLSL code:
8642         // for (; keep_going; keep_going = false)
8643         // {
8644         //     switch (int(param1.x))
8645         //     {
8646         //         case 0: continue;
8647         //         case 1: continue;
8648         //         default: continue;
8649         //     }
8650         //     dead code: modify return value to invalid result.
8651         // }
8652         fragments["pre_main"] =
8653                 "%fp_bool = OpTypePointer Function %bool\n"
8654                 "%true = OpConstantTrue %bool\n"
8655                 "%false = OpConstantFalse %bool\n";
8656
8657         fragments["testfun"] =
8658                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8659                 "%param1 = OpFunctionParameter %v4f32\n"
8660
8661                 "%entry = OpLabel\n"
8662                 "%keep_going = OpVariable %fp_bool Function\n"
8663                 "%val_ptr = OpVariable %fp_f32 Function\n"
8664                 "%param1_x = OpCompositeExtract %f32 %param1 0\n"
8665                 "OpStore %keep_going %true\n"
8666                 "OpBranch %forloop_begin\n"
8667
8668                 "%forloop_begin = OpLabel\n"
8669                 "OpLoopMerge %forloop_merge %forloop_continue None\n"
8670                 "OpBranch %forloop\n"
8671
8672                 "%forloop = OpLabel\n"
8673                 "%for_condition = OpLoad %bool %keep_going\n"
8674                 "OpBranchConditional %for_condition %forloop_body %forloop_merge\n"
8675
8676                 "%forloop_body = OpLabel\n"
8677                 "OpStore %val_ptr %param1_x\n"
8678                 "%param1_x_int = OpConvertFToS %i32 %param1_x\n"
8679
8680                 "OpSelectionMerge %switch_merge None\n"
8681                 "OpSwitch %param1_x_int %default 0 %case_0 1 %case_1\n"
8682                 "%case_0 = OpLabel\n"
8683                 "OpBranch %forloop_continue\n"
8684                 "%case_1 = OpLabel\n"
8685                 "OpBranch %forloop_continue\n"
8686                 "%default = OpLabel\n"
8687                 "OpBranch %forloop_continue\n"
8688                 "%switch_merge = OpLabel\n"
8689                 ";should never get here, so change the return value to invalid result\n"
8690                 "OpStore %val_ptr %c_f32_1\n"
8691                 "OpBranch %forloop_continue\n"
8692
8693                 "%forloop_continue = OpLabel\n"
8694                 "OpStore %keep_going %false\n"
8695                 "OpBranch %forloop_begin\n"
8696                 "%forloop_merge = OpLabel\n"
8697
8698                 "%val = OpLoad %f32 %val_ptr\n"
8699                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8700                 "OpReturnValue %result\n"
8701                 "OpFunctionEnd\n";
8702         createTestsForAllStages("switch_continue", defaultColors, defaultColors, fragments, testGroup.get());
8703
8704         return testGroup.release();
8705 }
8706
8707 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
8708 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
8709 {
8710         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
8711         map<string, string> fragments;
8712
8713         // A barrier inside a function body.
8714         fragments["pre_main"] =
8715                 "%Workgroup = OpConstant %i32 2\n"
8716                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n";
8717         fragments["testfun"] =
8718                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8719                 "%param1 = OpFunctionParameter %v4f32\n"
8720                 "%label_testfun = OpLabel\n"
8721                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8722                 "OpReturnValue %param1\n"
8723                 "OpFunctionEnd\n";
8724         addTessCtrlTest(testGroup.get(), "in_function", fragments);
8725
8726         // Common setup code for the following tests.
8727         fragments["pre_main"] =
8728                 "%Workgroup = OpConstant %i32 2\n"
8729                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8730                 "%c_f32_5 = OpConstant %f32 5.\n";
8731         const string setupPercentZero =  // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
8732                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8733                 "%param1 = OpFunctionParameter %v4f32\n"
8734                 "%entry = OpLabel\n"
8735                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8736                 "%dot = OpDot %f32 %param1 %param1\n"
8737                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8738                 "%zero = OpConvertFToU %u32 %div\n";
8739
8740         // Barriers inside OpSwitch branches.
8741         fragments["testfun"] =
8742                 setupPercentZero +
8743                 "OpSelectionMerge %switch_exit None\n"
8744                 "OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
8745
8746                 "%case1 = OpLabel\n"
8747                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8748                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8749                 "%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8750                 "OpBranch %switch_exit\n"
8751
8752                 "%switch_default = OpLabel\n"
8753                 "%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8754                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8755                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8756                 "OpBranch %switch_exit\n"
8757
8758                 "%case0 = OpLabel\n"
8759                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8760                 "OpBranch %switch_exit\n"
8761
8762                 "%switch_exit = OpLabel\n"
8763                 "%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
8764                 "OpReturnValue %ret\n"
8765                 "OpFunctionEnd\n";
8766         addTessCtrlTest(testGroup.get(), "in_switch", fragments);
8767
8768         // Barriers inside if-then-else.
8769         fragments["testfun"] =
8770                 setupPercentZero +
8771                 "%eq0 = OpIEqual %bool %zero %c_u32_0\n"
8772                 "OpSelectionMerge %exit DontFlatten\n"
8773                 "OpBranchConditional %eq0 %then %else\n"
8774
8775                 "%else = OpLabel\n"
8776                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8777                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8778                 "%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8779                 "OpBranch %exit\n"
8780
8781                 "%then = OpLabel\n"
8782                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8783                 "OpBranch %exit\n"
8784                 "%exit = OpLabel\n"
8785                 "%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
8786                 "OpReturnValue %ret\n"
8787                 "OpFunctionEnd\n";
8788         addTessCtrlTest(testGroup.get(), "in_if", fragments);
8789
8790         // A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
8791         // http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
8792         fragments["testfun"] =
8793                 setupPercentZero +
8794                 "%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
8795                 "%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
8796                 "OpSelectionMerge %exit DontFlatten\n"
8797                 "OpBranchConditional %thread0 %then %else\n"
8798
8799                 "%else = OpLabel\n"
8800                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8801                 "OpBranch %exit\n"
8802
8803                 "%then = OpLabel\n"
8804                 "%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
8805                 "OpBranch %exit\n"
8806
8807                 "%exit = OpLabel\n"
8808                 "%val = OpPhi %f32 %val0 %else %val1 %then\n"
8809                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8810                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
8811                 "OpReturnValue %ret\n"
8812                 "OpFunctionEnd\n";
8813         addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
8814
8815         // A barrier inside a loop.
8816         fragments["pre_main"] =
8817                 "%Workgroup = OpConstant %i32 2\n"
8818                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8819                 "%c_f32_10 = OpConstant %f32 10.\n";
8820         fragments["testfun"] =
8821                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8822                 "%param1 = OpFunctionParameter %v4f32\n"
8823                 "%entry = OpLabel\n"
8824                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8825                 "OpBranch %loop\n"
8826
8827                 ";adds 4, 3, 2, and 1 to %val0\n"
8828                 "%loop = OpLabel\n"
8829                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8830                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8831                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8832                 "%fcount = OpConvertSToF %f32 %count\n"
8833                 "%val = OpFAdd %f32 %val1 %fcount\n"
8834                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8835                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8836                 "OpLoopMerge %exit %loop None\n"
8837                 "OpBranchConditional %again %loop %exit\n"
8838
8839                 "%exit = OpLabel\n"
8840                 "%same = OpFSub %f32 %val %c_f32_10\n"
8841                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8842                 "OpReturnValue %ret\n"
8843                 "OpFunctionEnd\n";
8844         addTessCtrlTest(testGroup.get(), "in_loop", fragments);
8845
8846         return testGroup.release();
8847 }
8848
8849 // Test for the OpFRem instruction.
8850 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
8851 {
8852         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
8853         map<string, string>                                     fragments;
8854         RGBA                                                            inputColors[4];
8855         RGBA                                                            outputColors[4];
8856
8857         fragments["pre_main"]                            =
8858                 "%c_f32_3 = OpConstant %f32 3.0\n"
8859                 "%c_f32_n3 = OpConstant %f32 -3.0\n"
8860                 "%c_f32_4 = OpConstant %f32 4.0\n"
8861                 "%c_f32_p75 = OpConstant %f32 0.75\n"
8862                 "%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
8863                 "%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
8864                 "%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
8865
8866         // The test does the following.
8867         // vec4 result = (param1 * 8.0) - 4.0;
8868         // return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
8869         fragments["testfun"]                             =
8870                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8871                 "%param1 = OpFunctionParameter %v4f32\n"
8872                 "%label_testfun = OpLabel\n"
8873                 "%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
8874                 "%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
8875                 "%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
8876                 "%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
8877                 "%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
8878                 "%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
8879                 "OpReturnValue %xy_0_1\n"
8880                 "OpFunctionEnd\n";
8881
8882
8883         inputColors[0]          = RGBA(16,      16,             0, 255);
8884         inputColors[1]          = RGBA(232, 232,        0, 255);
8885         inputColors[2]          = RGBA(232, 16,         0, 255);
8886         inputColors[3]          = RGBA(16,      232,    0, 255);
8887
8888         outputColors[0]         = RGBA(64,      64,             0, 255);
8889         outputColors[1]         = RGBA(255, 255,        0, 255);
8890         outputColors[2]         = RGBA(255, 64,         0, 255);
8891         outputColors[3]         = RGBA(64,      255,    0, 255);
8892
8893         createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
8894         return testGroup.release();
8895 }
8896
8897 // Test for the OpSRem instruction.
8898 tcu::TestCaseGroup* createOpSRemGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8899 {
8900         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "srem", "OpSRem"));
8901         map<string, string>                                     fragments;
8902
8903         fragments["pre_main"]                            =
8904                 "%c_f32_255 = OpConstant %f32 255.0\n"
8905                 "%c_i32_128 = OpConstant %i32 128\n"
8906                 "%c_i32_255 = OpConstant %i32 255\n"
8907                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8908                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8909                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8910
8911         // The test does the following.
8912         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8913         // ivec4 result = ivec4(srem(ints.x, ints.y), srem(ints.y, ints.z), srem(ints.z, ints.x), 255);
8914         // return float(result + 128) / 255.0;
8915         fragments["testfun"]                             =
8916                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8917                 "%param1 = OpFunctionParameter %v4f32\n"
8918                 "%label_testfun = OpLabel\n"
8919                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8920                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8921                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8922                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8923                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8924                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8925                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8926                 "%x_out = OpSRem %i32 %x_in %y_in\n"
8927                 "%y_out = OpSRem %i32 %y_in %z_in\n"
8928                 "%z_out = OpSRem %i32 %z_in %x_in\n"
8929                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8930                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8931                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8932                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8933                 "OpReturnValue %float_out\n"
8934                 "OpFunctionEnd\n";
8935
8936         const struct CaseParams
8937         {
8938                 const char*             name;
8939                 const char*             failMessageTemplate;    // customized status message
8940                 qpTestResult    failResult;                             // override status on failure
8941                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8942                 int                             results[4][3];                  // four (x, y, z) vectors of results
8943         } cases[] =
8944         {
8945                 {
8946                         "positive",
8947                         "${reason}",
8948                         QP_TEST_RESULT_FAIL,
8949                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                 // operands
8950                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                 // results
8951                 },
8952                 {
8953                         "all",
8954                         "Inconsistent results, but within specification: ${reason}",
8955                         negFailResult,                                                                                                                  // negative operands, not required by the spec
8956                         { { 5, 12, -17 }, { -5, -5, 7 }, { 75, 8, -81 }, { 25, -60, 100 } },    // operands
8957                         { { 5, 12,  -2 }, {  0, -5, 2 }, {  3, 8,  -6 }, { 25, -60,   0 } },    // results
8958                 },
8959         };
8960         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8961
8962         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8963         {
8964                 const CaseParams&       params                  = cases[caseNdx];
8965                 RGBA                            inputColors[4];
8966                 RGBA                            outputColors[4];
8967
8968                 for (int i = 0; i < 4; ++i)
8969                 {
8970                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8971                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8972                 }
8973
8974                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8975         }
8976
8977         return testGroup.release();
8978 }
8979
8980 // Test for the OpSMod instruction.
8981 tcu::TestCaseGroup* createOpSModGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8982 {
8983         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "smod", "OpSMod"));
8984         map<string, string>                                     fragments;
8985
8986         fragments["pre_main"]                            =
8987                 "%c_f32_255 = OpConstant %f32 255.0\n"
8988                 "%c_i32_128 = OpConstant %i32 128\n"
8989                 "%c_i32_255 = OpConstant %i32 255\n"
8990                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8991                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8992                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8993
8994         // The test does the following.
8995         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8996         // ivec4 result = ivec4(smod(ints.x, ints.y), smod(ints.y, ints.z), smod(ints.z, ints.x), 255);
8997         // return float(result + 128) / 255.0;
8998         fragments["testfun"]                             =
8999                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9000                 "%param1 = OpFunctionParameter %v4f32\n"
9001                 "%label_testfun = OpLabel\n"
9002                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
9003                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
9004                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
9005                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
9006                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
9007                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
9008                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
9009                 "%x_out = OpSMod %i32 %x_in %y_in\n"
9010                 "%y_out = OpSMod %i32 %y_in %z_in\n"
9011                 "%z_out = OpSMod %i32 %z_in %x_in\n"
9012                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
9013                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
9014                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
9015                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
9016                 "OpReturnValue %float_out\n"
9017                 "OpFunctionEnd\n";
9018
9019         const struct CaseParams
9020         {
9021                 const char*             name;
9022                 const char*             failMessageTemplate;    // customized status message
9023                 qpTestResult    failResult;                             // override status on failure
9024                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
9025                 int                             results[4][3];                  // four (x, y, z) vectors of results
9026         } cases[] =
9027         {
9028                 {
9029                         "positive",
9030                         "${reason}",
9031                         QP_TEST_RESULT_FAIL,
9032                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                         // operands
9033                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                         // results
9034                 },
9035                 {
9036                         "all",
9037                         "Inconsistent results, but within specification: ${reason}",
9038                         negFailResult,                                                                                                                          // negative operands, not required by the spec
9039                         { { 5, 12, -17 }, { -5, -5,  7 }, { 75,   8, -81 }, {  25, -60, 100 } },        // operands
9040                         { { 5, -5,   3 }, {  0,  2, -3 }, {  3, -73,  69 }, { -35,  40,   0 } },        // results
9041                 },
9042         };
9043         // If either operand is negative the result is undefined. Some implementations may still return correct values.
9044
9045         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
9046         {
9047                 const CaseParams&       params                  = cases[caseNdx];
9048                 RGBA                            inputColors[4];
9049                 RGBA                            outputColors[4];
9050
9051                 for (int i = 0; i < 4; ++i)
9052                 {
9053                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
9054                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
9055                 }
9056
9057                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
9058         }
9059         return testGroup.release();
9060 }
9061
9062 enum ConversionDataType
9063 {
9064         DATA_TYPE_SIGNED_8,
9065         DATA_TYPE_SIGNED_16,
9066         DATA_TYPE_SIGNED_32,
9067         DATA_TYPE_SIGNED_64,
9068         DATA_TYPE_UNSIGNED_8,
9069         DATA_TYPE_UNSIGNED_16,
9070         DATA_TYPE_UNSIGNED_32,
9071         DATA_TYPE_UNSIGNED_64,
9072         DATA_TYPE_FLOAT_16,
9073         DATA_TYPE_FLOAT_32,
9074         DATA_TYPE_FLOAT_64,
9075         DATA_TYPE_VEC2_SIGNED_16,
9076         DATA_TYPE_VEC2_SIGNED_32
9077 };
9078
9079 const string getBitWidthStr (ConversionDataType type)
9080 {
9081         switch (type)
9082         {
9083                 case DATA_TYPE_SIGNED_8:
9084                 case DATA_TYPE_UNSIGNED_8:
9085                         return "8";
9086
9087                 case DATA_TYPE_SIGNED_16:
9088                 case DATA_TYPE_UNSIGNED_16:
9089                 case DATA_TYPE_FLOAT_16:
9090                         return "16";
9091
9092                 case DATA_TYPE_SIGNED_32:
9093                 case DATA_TYPE_UNSIGNED_32:
9094                 case DATA_TYPE_FLOAT_32:
9095                 case DATA_TYPE_VEC2_SIGNED_16:
9096                         return "32";
9097
9098                 case DATA_TYPE_SIGNED_64:
9099                 case DATA_TYPE_UNSIGNED_64:
9100                 case DATA_TYPE_FLOAT_64:
9101                 case DATA_TYPE_VEC2_SIGNED_32:
9102                         return "64";
9103
9104                 default:
9105                         DE_ASSERT(false);
9106         }
9107         return "";
9108 }
9109
9110 const string getByteWidthStr (ConversionDataType type)
9111 {
9112         switch (type)
9113         {
9114                 case DATA_TYPE_SIGNED_8:
9115                 case DATA_TYPE_UNSIGNED_8:
9116                         return "1";
9117
9118                 case DATA_TYPE_SIGNED_16:
9119                 case DATA_TYPE_UNSIGNED_16:
9120                 case DATA_TYPE_FLOAT_16:
9121                         return "2";
9122
9123                 case DATA_TYPE_SIGNED_32:
9124                 case DATA_TYPE_UNSIGNED_32:
9125                 case DATA_TYPE_FLOAT_32:
9126                 case DATA_TYPE_VEC2_SIGNED_16:
9127                         return "4";
9128
9129                 case DATA_TYPE_SIGNED_64:
9130                 case DATA_TYPE_UNSIGNED_64:
9131                 case DATA_TYPE_FLOAT_64:
9132                 case DATA_TYPE_VEC2_SIGNED_32:
9133                         return "8";
9134
9135                 default:
9136                         DE_ASSERT(false);
9137         }
9138         return "";
9139 }
9140
9141 bool isSigned (ConversionDataType type)
9142 {
9143         switch (type)
9144         {
9145                 case DATA_TYPE_SIGNED_8:
9146                 case DATA_TYPE_SIGNED_16:
9147                 case DATA_TYPE_SIGNED_32:
9148                 case DATA_TYPE_SIGNED_64:
9149                 case DATA_TYPE_FLOAT_16:
9150                 case DATA_TYPE_FLOAT_32:
9151                 case DATA_TYPE_FLOAT_64:
9152                 case DATA_TYPE_VEC2_SIGNED_16:
9153                 case DATA_TYPE_VEC2_SIGNED_32:
9154                         return true;
9155
9156                 case DATA_TYPE_UNSIGNED_8:
9157                 case DATA_TYPE_UNSIGNED_16:
9158                 case DATA_TYPE_UNSIGNED_32:
9159                 case DATA_TYPE_UNSIGNED_64:
9160                         return false;
9161
9162                 default:
9163                         DE_ASSERT(false);
9164         }
9165         return false;
9166 }
9167
9168 bool isInt (ConversionDataType type)
9169 {
9170         switch (type)
9171         {
9172                 case DATA_TYPE_SIGNED_8:
9173                 case DATA_TYPE_SIGNED_16:
9174                 case DATA_TYPE_SIGNED_32:
9175                 case DATA_TYPE_SIGNED_64:
9176                 case DATA_TYPE_UNSIGNED_8:
9177                 case DATA_TYPE_UNSIGNED_16:
9178                 case DATA_TYPE_UNSIGNED_32:
9179                 case DATA_TYPE_UNSIGNED_64:
9180                         return true;
9181
9182                 case DATA_TYPE_FLOAT_16:
9183                 case DATA_TYPE_FLOAT_32:
9184                 case DATA_TYPE_FLOAT_64:
9185                 case DATA_TYPE_VEC2_SIGNED_16:
9186                 case DATA_TYPE_VEC2_SIGNED_32:
9187                         return false;
9188
9189                 default:
9190                         DE_ASSERT(false);
9191         }
9192         return false;
9193 }
9194
9195 bool isFloat (ConversionDataType type)
9196 {
9197         switch (type)
9198         {
9199                 case DATA_TYPE_SIGNED_8:
9200                 case DATA_TYPE_SIGNED_16:
9201                 case DATA_TYPE_SIGNED_32:
9202                 case DATA_TYPE_SIGNED_64:
9203                 case DATA_TYPE_UNSIGNED_8:
9204                 case DATA_TYPE_UNSIGNED_16:
9205                 case DATA_TYPE_UNSIGNED_32:
9206                 case DATA_TYPE_UNSIGNED_64:
9207                 case DATA_TYPE_VEC2_SIGNED_16:
9208                 case DATA_TYPE_VEC2_SIGNED_32:
9209                         return false;
9210
9211                 case DATA_TYPE_FLOAT_16:
9212                 case DATA_TYPE_FLOAT_32:
9213                 case DATA_TYPE_FLOAT_64:
9214                         return true;
9215
9216                 default:
9217                         DE_ASSERT(false);
9218         }
9219         return false;
9220 }
9221
9222 const string getTypeName (ConversionDataType type)
9223 {
9224         string prefix = isSigned(type) ? "" : "u";
9225
9226         if              (isInt(type))                                           return prefix + "int"   + getBitWidthStr(type);
9227         else if (isFloat(type))                                         return prefix + "float" + getBitWidthStr(type);
9228         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9229         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "i32vec2";
9230         else                                                                            DE_ASSERT(false);
9231
9232         return "";
9233 }
9234
9235 const string getTestName (ConversionDataType from, ConversionDataType to, const char* suffix)
9236 {
9237         const string fullSuffix(suffix == DE_NULL ? "" : string("_") + string(suffix));
9238
9239         return getTypeName(from) + "_to_" + getTypeName(to) + fullSuffix;
9240 }
9241
9242 const string getAsmTypeName (ConversionDataType type)
9243 {
9244         string prefix;
9245
9246         if              (isInt(type))                                           prefix = isSigned(type) ? "i" : "u";
9247         else if (isFloat(type))                                         prefix = "f";
9248         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9249         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "v2i32";
9250         else                                                                            DE_ASSERT(false);
9251
9252         return prefix + getBitWidthStr(type);
9253 }
9254
9255 template<typename T>
9256 BufferSp getSpecializedBuffer (deInt64 number)
9257 {
9258         return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
9259 }
9260
9261 BufferSp getBuffer (ConversionDataType type, deInt64 number)
9262 {
9263         switch (type)
9264         {
9265                 case DATA_TYPE_SIGNED_8:                return getSpecializedBuffer<deInt8>(number);
9266                 case DATA_TYPE_SIGNED_16:               return getSpecializedBuffer<deInt16>(number);
9267                 case DATA_TYPE_SIGNED_32:               return getSpecializedBuffer<deInt32>(number);
9268                 case DATA_TYPE_SIGNED_64:               return getSpecializedBuffer<deInt64>(number);
9269                 case DATA_TYPE_UNSIGNED_8:              return getSpecializedBuffer<deUint8>(number);
9270                 case DATA_TYPE_UNSIGNED_16:             return getSpecializedBuffer<deUint16>(number);
9271                 case DATA_TYPE_UNSIGNED_32:             return getSpecializedBuffer<deUint32>(number);
9272                 case DATA_TYPE_UNSIGNED_64:             return getSpecializedBuffer<deUint64>(number);
9273                 case DATA_TYPE_FLOAT_16:                return getSpecializedBuffer<deUint16>(number);
9274                 case DATA_TYPE_FLOAT_32:                return getSpecializedBuffer<deUint32>(number);
9275                 case DATA_TYPE_FLOAT_64:                return getSpecializedBuffer<deUint64>(number);
9276                 case DATA_TYPE_VEC2_SIGNED_16:  return getSpecializedBuffer<deUint32>(number);
9277                 case DATA_TYPE_VEC2_SIGNED_32:  return getSpecializedBuffer<deUint64>(number);
9278
9279                 default:                                                TCU_THROW(InternalError, "Unimplemented type passed");
9280         }
9281 }
9282
9283 bool usesInt8 (ConversionDataType from, ConversionDataType to)
9284 {
9285         return (from == DATA_TYPE_SIGNED_8 || to == DATA_TYPE_SIGNED_8 ||
9286                         from == DATA_TYPE_UNSIGNED_8 || to == DATA_TYPE_UNSIGNED_8);
9287 }
9288
9289 bool usesInt16 (ConversionDataType from, ConversionDataType to)
9290 {
9291         return (from == DATA_TYPE_SIGNED_16 || to == DATA_TYPE_SIGNED_16 ||
9292                         from == DATA_TYPE_UNSIGNED_16 || to == DATA_TYPE_UNSIGNED_16 ||
9293                         from == DATA_TYPE_VEC2_SIGNED_16 || to == DATA_TYPE_VEC2_SIGNED_16);
9294 }
9295
9296 bool usesInt32 (ConversionDataType from, ConversionDataType to)
9297 {
9298         return (from == DATA_TYPE_SIGNED_32 || to == DATA_TYPE_SIGNED_32 ||
9299                         from == DATA_TYPE_UNSIGNED_32 || to == DATA_TYPE_UNSIGNED_32 ||
9300                         from == DATA_TYPE_VEC2_SIGNED_32|| to == DATA_TYPE_VEC2_SIGNED_32);
9301 }
9302
9303 bool usesInt64 (ConversionDataType from, ConversionDataType to)
9304 {
9305         return (from == DATA_TYPE_SIGNED_64 || to == DATA_TYPE_SIGNED_64 ||
9306                         from == DATA_TYPE_UNSIGNED_64 || to == DATA_TYPE_UNSIGNED_64);
9307 }
9308
9309 bool usesFloat16 (ConversionDataType from, ConversionDataType to)
9310 {
9311         return (from == DATA_TYPE_FLOAT_16 || to == DATA_TYPE_FLOAT_16);
9312 }
9313
9314 bool usesFloat32 (ConversionDataType from, ConversionDataType to)
9315 {
9316         return (from == DATA_TYPE_FLOAT_32 || to == DATA_TYPE_FLOAT_32);
9317 }
9318
9319 bool usesFloat64 (ConversionDataType from, ConversionDataType to)
9320 {
9321         return (from == DATA_TYPE_FLOAT_64 || to == DATA_TYPE_FLOAT_64);
9322 }
9323
9324 void getVulkanFeaturesAndExtensions (ConversionDataType from, ConversionDataType to, VulkanFeatures& vulkanFeatures, vector<string>& extensions)
9325 {
9326         if (usesInt16(from, to) && !usesInt32(from, to))
9327                 vulkanFeatures.coreFeatures.shaderInt16 = DE_TRUE;
9328
9329         if (usesInt64(from, to))
9330                 vulkanFeatures.coreFeatures.shaderInt64 = DE_TRUE;
9331
9332         if (usesFloat64(from, to))
9333                 vulkanFeatures.coreFeatures.shaderFloat64 = DE_TRUE;
9334
9335         if (usesInt16(from, to) || usesFloat16(from, to))
9336         {
9337                 extensions.push_back("VK_KHR_16bit_storage");
9338                 vulkanFeatures.ext16BitStorage |= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
9339         }
9340
9341         if (usesFloat16(from, to) || usesInt8(from, to))
9342         {
9343                 extensions.push_back("VK_KHR_shader_float16_int8");
9344
9345                 if (usesFloat16(from, to))
9346                 {
9347                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
9348                 }
9349
9350                 if (usesInt8(from, to))
9351                 {
9352                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
9353
9354                         extensions.push_back("VK_KHR_8bit_storage");
9355                         vulkanFeatures.ext8BitStorage |= EXT8BITSTORAGEFEATURES_STORAGE_BUFFER;
9356                 }
9357         }
9358 }
9359
9360 struct ConvertCase
9361 {
9362         ConvertCase (const string& instruction, ConversionDataType from, ConversionDataType to, deInt64 number, bool separateOutput = false, deInt64 outputNumber = 0, const char* suffix = DE_NULL)
9363         : m_fromType            (from)
9364         , m_toType                      (to)
9365         , m_name                        (getTestName(from, to, suffix))
9366         , m_inputBuffer         (getBuffer(from, number))
9367         {
9368                 string caps;
9369                 string decl;
9370                 string exts;
9371
9372                 m_asmTypes["inputType"]         = getAsmTypeName(from);
9373                 m_asmTypes["outputType"]        = getAsmTypeName(to);
9374
9375                 if (separateOutput)
9376                         m_outputBuffer = getBuffer(to, outputNumber);
9377                 else
9378                         m_outputBuffer = getBuffer(to, number);
9379
9380                 if (usesInt8(from, to))
9381                 {
9382                         bool requiresInt8Capability = true;
9383                         if (instruction == "OpUConvert" || instruction == "OpSConvert")
9384                         {
9385                                 // Conversions between 8 and 32 bit are provided by SPV_KHR_8bit_storage. The rest requires explicit Int8
9386                                 if (usesInt32(from, to))
9387                                         requiresInt8Capability = false;
9388                         }
9389
9390                         caps += "OpCapability StorageBuffer8BitAccess\n";
9391                         if (requiresInt8Capability)
9392                                 caps += "OpCapability Int8\n";
9393
9394                         decl += "%i8         = OpTypeInt 8 1\n"
9395                                         "%u8         = OpTypeInt 8 0\n";
9396                         exts += "OpExtension \"SPV_KHR_8bit_storage\"\n";
9397                 }
9398
9399                 if (usesInt16(from, to))
9400                 {
9401                         bool requiresInt16Capability = true;
9402
9403                         if (instruction == "OpUConvert" || instruction == "OpSConvert" || instruction == "OpFConvert")
9404                         {
9405                                 // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9406                                 if (usesInt32(from, to) || usesFloat32(from, to))
9407                                         requiresInt16Capability = false;
9408                         }
9409
9410                         decl += "%i16        = OpTypeInt 16 1\n"
9411                                         "%u16        = OpTypeInt 16 0\n"
9412                                         "%i16vec2    = OpTypeVector %i16 2\n";
9413
9414                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9415                         if (requiresInt16Capability)
9416                                 caps += "OpCapability Int16\n";
9417                 }
9418
9419                 if (usesFloat16(from, to))
9420                 {
9421                         decl += "%f16        = OpTypeFloat 16\n";
9422
9423                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Float16
9424                         if (!(usesInt32(from, to) || usesFloat32(from, to)))
9425                                 caps += "OpCapability Float16\n";
9426                 }
9427
9428                 if (usesInt16(from, to) || usesFloat16(from, to))
9429                 {
9430                         caps += "OpCapability StorageUniformBufferBlock16\n";
9431                         exts += "OpExtension \"SPV_KHR_16bit_storage\"\n";
9432                 }
9433
9434                 if (usesInt64(from, to))
9435                 {
9436                         caps += "OpCapability Int64\n";
9437                         decl += "%i64        = OpTypeInt 64 1\n"
9438                                         "%u64        = OpTypeInt 64 0\n";
9439                 }
9440
9441                 if (usesFloat64(from, to))
9442                 {
9443                         caps += "OpCapability Float64\n";
9444                         decl += "%f64        = OpTypeFloat 64\n";
9445                 }
9446
9447                 m_asmTypes["datatype_capabilities"]             = caps;
9448                 m_asmTypes["datatype_additional_decl"]  = decl;
9449                 m_asmTypes["datatype_extensions"]               = exts;
9450         }
9451
9452         ConversionDataType              m_fromType;
9453         ConversionDataType              m_toType;
9454         string                                  m_name;
9455         map<string, string>             m_asmTypes;
9456         BufferSp                                m_inputBuffer;
9457         BufferSp                                m_outputBuffer;
9458 };
9459
9460 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
9461 {
9462         map<string, string> params = convertCase.m_asmTypes;
9463
9464         params["instruction"]   = instruction;
9465         params["inDecorator"]   = getByteWidthStr(convertCase.m_fromType);
9466         params["outDecorator"]  = getByteWidthStr(convertCase.m_toType);
9467
9468         const StringTemplate shader (
9469                 "OpCapability Shader\n"
9470                 "${datatype_capabilities}"
9471                 "${datatype_extensions:opt}"
9472                 "OpMemoryModel Logical GLSL450\n"
9473                 "OpEntryPoint GLCompute %main \"main\"\n"
9474                 "OpExecutionMode %main LocalSize 1 1 1\n"
9475                 "OpSource GLSL 430\n"
9476                 "OpName %main           \"main\"\n"
9477                 // Decorators
9478                 "OpDecorate %indata DescriptorSet 0\n"
9479                 "OpDecorate %indata Binding 0\n"
9480                 "OpDecorate %outdata DescriptorSet 0\n"
9481                 "OpDecorate %outdata Binding 1\n"
9482                 "OpDecorate %in_buf BufferBlock\n"
9483                 "OpDecorate %out_buf BufferBlock\n"
9484                 "OpMemberDecorate %in_buf 0 Offset 0\n"
9485                 "OpMemberDecorate %out_buf 0 Offset 0\n"
9486                 // Base types
9487                 "%void       = OpTypeVoid\n"
9488                 "%voidf      = OpTypeFunction %void\n"
9489                 "%u32        = OpTypeInt 32 0\n"
9490                 "%i32        = OpTypeInt 32 1\n"
9491                 "%f32        = OpTypeFloat 32\n"
9492                 "%v2i32      = OpTypeVector %i32 2\n"
9493                 "${datatype_additional_decl}"
9494                 "%uvec3      = OpTypeVector %u32 3\n"
9495                 // Derived types
9496                 "%in_ptr     = OpTypePointer Uniform %${inputType}\n"
9497                 "%out_ptr    = OpTypePointer Uniform %${outputType}\n"
9498                 "%in_buf     = OpTypeStruct %${inputType}\n"
9499                 "%out_buf    = OpTypeStruct %${outputType}\n"
9500                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
9501                 "%out_bufptr = OpTypePointer Uniform %out_buf\n"
9502                 "%indata     = OpVariable %in_bufptr Uniform\n"
9503                 "%outdata    = OpVariable %out_bufptr Uniform\n"
9504                 // Constants
9505                 "%zero       = OpConstant %i32 0\n"
9506                 // Main function
9507                 "%main       = OpFunction %void None %voidf\n"
9508                 "%label      = OpLabel\n"
9509                 "%inloc      = OpAccessChain %in_ptr %indata %zero\n"
9510                 "%outloc     = OpAccessChain %out_ptr %outdata %zero\n"
9511                 "%inval      = OpLoad %${inputType} %inloc\n"
9512                 "%conv       = ${instruction} %${outputType} %inval\n"
9513                 "              OpStore %outloc %conv\n"
9514                 "              OpReturn\n"
9515                 "              OpFunctionEnd\n"
9516         );
9517
9518         return shader.specialize(params);
9519 }
9520
9521 void createConvertCases (vector<ConvertCase>& testCases, const string& instruction)
9522 {
9523         if (instruction == "OpUConvert")
9524         {
9525                 // Convert unsigned int to unsigned int
9526                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_16,          42));
9527                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_32,          73));
9528                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_64,          121));
9529
9530                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_8,           33));
9531                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_32,          60653));
9532                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_64,          17991));
9533
9534                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_64,          904256275));
9535                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_16,          6275));
9536                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_8,           17));
9537
9538                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_32,          701256243));
9539                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_16,          4741));
9540                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_8,           65));
9541         }
9542         else if (instruction == "OpSConvert")
9543         {
9544                 // Sign extension int->int
9545                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_16,            -30));
9546                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_32,            55));
9547                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_64,            -3));
9548                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_32,            14669));
9549                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_64,            -3341));
9550                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_64,            973610259));
9551
9552                 // Truncate for int->int
9553                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_8,                     81));
9554                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_8,                     -93));
9555                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_8,                     3182748172687672ll,                                     true,   56));
9556                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_16,            12382));
9557                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_32,            -972812359));
9558                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_16,            -1067742499291926803ll,                         true,   -4371));
9559
9560                 // Sign extension for int->uint
9561                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_16,          56));
9562                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_32,          -47,                                                            true,   4294967249u));
9563                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_64,          -5,                                                                     true,   18446744073709551611ull));
9564                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_32,          14669));
9565                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_64,          -3341,                                                          true,   18446744073709548275ull));
9566                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_64,          973610259));
9567
9568                 // Truncate for int->uint
9569                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_8,           -25711,                                                         true,   145));
9570                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_8,           103));
9571                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_8,           -1067742499291926803ll,                         true,   61165));
9572                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_16,          12382));
9573                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_32,          -972812359,                                                     true,   3322154937u));
9574                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_16,          -1067742499291926803ll,                         true,   61165));
9575
9576                 // Sign extension for uint->int
9577                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_16,            71));
9578                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_32,            201,                                                            true,   -55));
9579                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_64,            188,                                                            true,   -68));
9580                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_32,            14669));
9581                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_64,            62195,                                                          true,   -3341));
9582                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_64,            973610259));
9583
9584                 // Truncate for uint->int
9585                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_8,                     67));
9586                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_8,                     133,                                                            true,   -123));
9587                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_8,                     836927654193256494ull,                          true,   46));
9588                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_16,            12382));
9589                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_32,            18446744072736739257ull,                        true,   -972812359));
9590                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_16,            17379001574417624813ull,                        true,   -4371));
9591
9592                 // Convert i16vec2 to i32vec2 and vice versa
9593                 // Unsigned values are used here to represent negative signed values and to allow defined shifting behaviour.
9594                 // The actual signed value -32123 is used here as uint16 value 33413 and uint32 value 4294935173
9595                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_16,       DATA_TYPE_VEC2_SIGNED_32,       (33413u << 16)                  | 27593,        true,   (4294935173ull << 32)   | 27593));
9596                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_32,       DATA_TYPE_VEC2_SIGNED_16,       (4294935173ull << 32)   | 27593,        true,   (33413u << 16)                  | 27593));
9597         }
9598         else if (instruction == "OpFConvert")
9599         {
9600                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9601                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_64,                     0x449a4000,                                                     true,   0x4093480000000000));
9602                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_32,                     0x4093480000000000,                                     true,   0x449a4000));
9603
9604                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_16,                     0x449a4000,                                                     true,   0x64D2));
9605                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_32,                     0x64D2,                                                         true,   0x449a4000));
9606
9607                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_64,                     0x64D2,                                                         true,   0x4093480000000000));
9608                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_16,                     0x4093480000000000,                                     true,   0x64D2));
9609         }
9610         else if (instruction == "OpConvertFToU")
9611         {
9612                 // Normal numbers from uint8 range
9613                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5020,                                                         true,   33,                                                                     "33"));
9614                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x42280000,                                                     true,   42,                                                                     "42"));
9615                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x4067800000000000ull,                          true,   188,                                                            "188"));
9616
9617                 // Maximum uint8 value
9618                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5BF8,                                                         true,   255,                                                            "max"));
9619                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x437F0000,                                                     true,   255,                                                            "max"));
9620                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x406FE00000000000ull,                          true,   255,                                                            "max"));
9621
9622                 // +0
9623                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x0000,                                                         true,   0,                                                                      "p0"));
9624                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x00000000,                                                     true,   0,                                                                      "p0"));
9625                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9626
9627                 // -0
9628                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x8000,                                                         true,   0,                                                                      "m0"));
9629                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x80000000,                                                     true,   0,                                                                      "m0"));
9630                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9631
9632                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9633                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x64D2,                                                         true,   1234,                                                           "1234"));
9634                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x64D2,                                                         true,   1234,                                                           "1234"));
9635                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x64D2,                                                         true,   1234,                                                           "1234"));
9636
9637                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9638                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x7BFF,                                                         true,   65504,                                                          "max"));
9639                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x7BFF,                                                         true,   65504,                                                          "max"));
9640                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x7BFF,                                                         true,   65504,                                                          "max"));
9641
9642                 // +0
9643                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x0000,                                                         true,   0,                                                                      "p0"));
9644                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x0000,                                                         true,   0,                                                                      "p0"));
9645                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x0000,                                                         true,   0,                                                                      "p0"));
9646
9647                 // -0
9648                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x8000,                                                         true,   0,                                                                      "m0"));
9649                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x8000,                                                         true,   0,                                                                      "m0"));
9650                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x8000,                                                         true,   0,                                                                      "m0"));
9651
9652                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_16,          0x449a4000,                                                     true,   1234));
9653                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_32,          0x449a4000,                                                     true,   1234));
9654                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_64,          0x449a4000,                                                     true,   1234));
9655                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_16,          0x4093480000000000,                                     true,   1234));
9656                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_32,          0x4093480000000000,                                     true,   1234));
9657                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_64,          0x4093480000000000,                                     true,   1234));
9658         }
9659         else if (instruction == "OpConvertUToF")
9660         {
9661                 // Normal numbers from uint8 range
9662                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     116,                                                            true,   0x5740,                                                         "116"));
9663                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     232,                                                            true,   0x43680000,                                                     "232"));
9664                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     164,                                                            true,   0x4064800000000000ull,                          "164"));
9665
9666                 // Maximum uint8 value
9667                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     255,                                                            true,   0x5BF8,                                                         "max"));
9668                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     255,                                                            true,   0x437F0000,                                                     "max"));
9669                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     255,                                                            true,   0x406FE00000000000ull,                          "max"));
9670
9671                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9672                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9673                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9674                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9675
9676                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9677                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9678                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9679                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9680
9681                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9682                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9683                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9684                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9685                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9686                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9687         }
9688         else if (instruction == "OpConvertFToS")
9689         {
9690                 // Normal numbers from int8 range
9691                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xC980,                                                         true,   -11,                                                            "m11"));
9692                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC2140000,                                                     true,   -37,                                                            "m37"));
9693                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC050800000000000ull,                          true,   -66,                                                            "m66"));
9694
9695                 // Minimum int8 value
9696                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xD800,                                                         true,   -128,                                                           "min"));
9697                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC3000000,                                                     true,   -128,                                                           "min"));
9698                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC060000000000000ull,                          true,   -128,                                                           "min"));
9699
9700                 // Maximum int8 value
9701                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x57F0,                                                         true,   127,                                                            "max"));
9702                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x42FE0000,                                                     true,   127,                                                            "max"));
9703                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x405FC00000000000ull,                          true,   127,                                                            "max"));
9704
9705                 // +0
9706                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x0000,                                                         true,   0,                                                                      "p0"));
9707                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x00000000,                                                     true,   0,                                                                      "p0"));
9708                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9709
9710                 // -0
9711                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x8000,                                                         true,   0,                                                                      "m0"));
9712                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x80000000,                                                     true,   0,                                                                      "m0"));
9713                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9714
9715                 // All hexadecimal values below represent -1234.0 as 32/64-bit IEEE 754 float
9716                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9717                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9718                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9719
9720                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9721                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xF800,                                                         true,   -32768,                                                         "min"));
9722                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xF800,                                                         true,   -32768,                                                         "min"));
9723                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xF800,                                                         true,   -32768,                                                         "min"));
9724
9725                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9726                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x77FF,                                                         true,   32752,                                                          "max"));
9727                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x77FF,                                                         true,   32752,                                                          "max"));
9728                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x77FF,                                                         true,   32752,                                                          "max"));
9729
9730                 // +0
9731                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x0000,                                                         true,   0,                                                                      "p0"));
9732                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x0000,                                                         true,   0,                                                                      "p0"));
9733                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x0000,                                                         true,   0,                                                                      "p0"));
9734
9735                 // -0
9736                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x8000,                                                         true,   0,                                                                      "m0"));
9737                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x8000,                                                         true,   0,                                                                      "m0"));
9738                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x8000,                                                         true,   0,                                                                      "m0"));
9739
9740                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc49a4000,                                                     true,   -1234));
9741                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_32,            0xc49a4000,                                                     true,   -1234));
9742                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_64,            0xc49a4000,                                                     true,   -1234));
9743                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_16,            0xc093480000000000,                                     true,   -1234));
9744                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_32,            0xc093480000000000,                                     true,   -1234));
9745                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_64,            0xc093480000000000,                                     true,   -1234));
9746                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0x453b9000,                                                     true,    3001,                                                          "p3001"));
9747                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc53b9000,                                                     true,   -3001,                                                          "m3001"));
9748         }
9749         else if (instruction == "OpConvertSToF")
9750         {
9751                 // Normal numbers from int8 range
9752                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -12,                                                            true,   0xCA00,                                                         "m21"));
9753                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -21,                                                            true,   0xC1A80000,                                                     "m21"));
9754                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -99,                                                            true,   0xC058C00000000000ull,                          "m99"));
9755
9756                 // Minimum int8 value
9757                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -128,                                                           true,   0xD800,                                                         "min"));
9758                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -128,                                                           true,   0xC3000000,                                                     "min"));
9759                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -128,                                                           true,   0xC060000000000000ull,                          "min"));
9760
9761                 // Maximum int8 value
9762                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     127,                                                            true,   0x57F0,                                                         "max"));
9763                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     127,                                                            true,   0x42FE0000,                                                     "max"));
9764                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     127,                                                            true,   0x405FC00000000000ull,                          "max"));
9765
9766                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9767                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9768                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9769                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9770
9771                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9772                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9773                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9774                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9775
9776                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9777                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9778                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9779                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9780
9781                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9782                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9783                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9784                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9785                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9786                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9787         }
9788         else
9789                 DE_FATAL("Unknown instruction");
9790 }
9791
9792 const map<string, string> getConvertCaseFragments (string instruction, const ConvertCase& convertCase)
9793 {
9794         map<string, string> params = convertCase.m_asmTypes;
9795         map<string, string> fragments;
9796
9797         params["instruction"] = instruction;
9798         params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
9799
9800         const StringTemplate decoration (
9801                 "      OpDecorate %SSBOi DescriptorSet 0\n"
9802                 "      OpDecorate %SSBOo DescriptorSet 0\n"
9803                 "      OpDecorate %SSBOi Binding 0\n"
9804                 "      OpDecorate %SSBOo Binding 1\n"
9805                 "      OpDecorate %s_SSBOi Block\n"
9806                 "      OpDecorate %s_SSBOo Block\n"
9807                 "OpMemberDecorate %s_SSBOi 0 Offset 0\n"
9808                 "OpMemberDecorate %s_SSBOo 0 Offset 0\n");
9809
9810         const StringTemplate pre_main (
9811                 "${datatype_additional_decl:opt}"
9812                 "    %ptr_in = OpTypePointer StorageBuffer %${inputType}\n"
9813                 "   %ptr_out = OpTypePointer StorageBuffer %${outputType}\n"
9814                 "   %s_SSBOi = OpTypeStruct %${inputType}\n"
9815                 "   %s_SSBOo = OpTypeStruct %${outputType}\n"
9816                 " %ptr_SSBOi = OpTypePointer StorageBuffer %s_SSBOi\n"
9817                 " %ptr_SSBOo = OpTypePointer StorageBuffer %s_SSBOo\n"
9818                 "     %SSBOi = OpVariable %ptr_SSBOi StorageBuffer\n"
9819                 "     %SSBOo = OpVariable %ptr_SSBOo StorageBuffer\n");
9820
9821         const StringTemplate testfun (
9822                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9823                 "%param     = OpFunctionParameter %v4f32\n"
9824                 "%label     = OpLabel\n"
9825                 "%iLoc      = OpAccessChain %ptr_in %SSBOi %c_u32_0\n"
9826                 "%oLoc      = OpAccessChain %ptr_out %SSBOo %c_u32_0\n"
9827                 "%valIn     = OpLoad %${inputType} %iLoc\n"
9828                 "%valOut    = ${instruction} %${outputType} %valIn\n"
9829                 "             OpStore %oLoc %valOut\n"
9830                 "             OpReturnValue %param\n"
9831                 "             OpFunctionEnd\n");
9832
9833         params["datatype_extensions"] =
9834                 params["datatype_extensions"] +
9835                 "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n";
9836
9837         fragments["capability"] = params["datatype_capabilities"];
9838         fragments["extension"]  = params["datatype_extensions"];
9839         fragments["decoration"] = decoration.specialize(params);
9840         fragments["pre_main"]   = pre_main.specialize(params);
9841         fragments["testfun"]    = testfun.specialize(params);
9842
9843         return fragments;
9844 }
9845
9846 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in compute shaders
9847 tcu::TestCaseGroup* createConvertComputeTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9848 {
9849         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9850         vector<ConvertCase>                                     testCases;
9851         createConvertCases(testCases, instruction);
9852
9853         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9854         {
9855                 ComputeShaderSpec spec;
9856                 spec.assembly                   = getConvertCaseShaderStr(instruction, *test);
9857                 spec.numWorkGroups              = IVec3(1, 1, 1);
9858                 spec.inputs.push_back   (test->m_inputBuffer);
9859                 spec.outputs.push_back  (test->m_outputBuffer);
9860
9861                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, spec.requestedVulkanFeatures, spec.extensions);
9862
9863                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "", spec));
9864         }
9865         return group.release();
9866 }
9867
9868 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in graphics shaders
9869 tcu::TestCaseGroup* createConvertGraphicsTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9870 {
9871         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9872         vector<ConvertCase>                                     testCases;
9873         createConvertCases(testCases, instruction);
9874
9875         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9876         {
9877                 map<string, string>     fragments               = getConvertCaseFragments(instruction, *test);
9878                 VulkanFeatures          vulkanFeatures;
9879                 GraphicsResources       resources;
9880                 vector<string>          extensions;
9881                 SpecConstants           noSpecConstants;
9882                 PushConstants           noPushConstants;
9883                 GraphicsInterfaces      noInterfaces;
9884                 tcu::RGBA                       defaultColors[4];
9885
9886                 getDefaultColors                        (defaultColors);
9887                 resources.inputs.push_back      (Resource(test->m_inputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9888                 resources.outputs.push_back     (Resource(test->m_outputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9889                 extensions.push_back            ("VK_KHR_storage_buffer_storage_class");
9890
9891                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, vulkanFeatures, extensions);
9892
9893                 vulkanFeatures.coreFeatures.vertexPipelineStoresAndAtomics      = true;
9894                 vulkanFeatures.coreFeatures.fragmentStoresAndAtomics            = true;
9895
9896                 createTestsForAllStages(
9897                         test->m_name, defaultColors, defaultColors, fragments, noSpecConstants,
9898                         noPushConstants, resources, noInterfaces, extensions, vulkanFeatures, group.get());
9899         }
9900         return group.release();
9901 }
9902
9903 // Constant-Creation Instructions: OpConstant, OpConstantComposite
9904 tcu::TestCaseGroup* createOpConstantFloat16Tests(tcu::TestContext& testCtx)
9905 {
9906         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstant", "OpConstant and OpConstantComposite instruction"));
9907         RGBA                                                    inputColors[4];
9908         RGBA                                                    outputColors[4];
9909         vector<string>                                  extensions;
9910         GraphicsResources                               resources;
9911         VulkanFeatures                                  features;
9912
9913         const char                                              functionStart[]  =
9914                 "%test_code             = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9915                 "%param1                = OpFunctionParameter %v4f32\n"
9916                 "%lbl                   = OpLabel\n";
9917
9918         const char                                              functionEnd[]           =
9919                 "%transformed_param_32  = OpFConvert %v4f32 %transformed_param\n"
9920                 "                         OpReturnValue %transformed_param_32\n"
9921                 "                         OpFunctionEnd\n";
9922
9923         struct NameConstantsCode
9924         {
9925                 string name;
9926                 string constants;
9927                 string code;
9928         };
9929
9930 #define FLOAT_16_COMMON_TYPES_AND_CONSTS \
9931                         "%f16                  = OpTypeFloat 16\n"                                                 \
9932                         "%c_f16_0              = OpConstant %f16 0.0\n"                                            \
9933                         "%c_f16_0_5            = OpConstant %f16 0.5\n"                                            \
9934                         "%c_f16_1              = OpConstant %f16 1.0\n"                                            \
9935                         "%v4f16                = OpTypeVector %f16 4\n"                                            \
9936                         "%fp_f16               = OpTypePointer Function %f16\n"                                    \
9937                         "%fp_v4f16             = OpTypePointer Function %v4f16\n"                                  \
9938                         "%c_v4f16_1_1_1_1      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n" \
9939                         "%a4f16                = OpTypeArray %f16 %c_u32_4\n"                                      \
9940
9941         NameConstantsCode                               tests[] =
9942         {
9943                 {
9944                         "vec4",
9945
9946                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9947                         "%cval                 = OpConstantComposite %v4f16 %c_f16_0_5 %c_f16_0_5 %c_f16_0_5 %c_f16_0\n",
9948                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9949                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %cval\n"
9950                 },
9951                 {
9952                         "struct",
9953
9954                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9955                         "%stype                = OpTypeStruct %v4f16 %f16\n"
9956                         "%fp_stype             = OpTypePointer Function %stype\n"
9957                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9958                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9959                         "%cvec                 = OpConstantComposite %v4f16 %f16_1_5 %f16_1_5 %f16_1_5 %c_f16_1\n"
9960                         "%cval                 = OpConstantComposite %stype %cvec %f16_n_1\n",
9961
9962                         "%v                    = OpVariable %fp_stype Function %cval\n"
9963                         "%vec_ptr              = OpAccessChain %fp_v4f16 %v %c_u32_0\n"
9964                         "%f16_ptr              = OpAccessChain %fp_f16 %v %c_u32_1\n"
9965                         "%vec_val              = OpLoad %v4f16 %vec_ptr\n"
9966                         "%f16_val              = OpLoad %f16 %f16_ptr\n"
9967                         "%tmp1                 = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_1 %f16_val\n" // vec4(-1)
9968                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9969                         "%tmp2                 = OpFAdd %v4f16 %tmp1 %param1_16\n" // param1 + vec4(-1)
9970                         "%transformed_param    = OpFAdd %v4f16 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
9971                 },
9972                 {
9973                         // [1|0|0|0.5] [x] = x + 0.5
9974                         // [0|1|0|0.5] [y] = y + 0.5
9975                         // [0|0|1|0.5] [z] = z + 0.5
9976                         // [0|0|0|1  ] [1] = 1
9977                         "matrix",
9978
9979                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9980                         "%mat4x4_f16           = OpTypeMatrix %v4f16 4\n"
9981                         "%v4f16_1_0_0_0        = OpConstantComposite %v4f16 %c_f16_1 %c_f16_0 %c_f16_0 %c_f16_0\n"
9982                         "%v4f16_0_1_0_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_1 %c_f16_0 %c_f16_0\n"
9983                         "%v4f16_0_0_1_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_1 %c_f16_0\n"
9984                         "%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"
9985                         "%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",
9986
9987                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9988                         "%transformed_param    = OpMatrixTimesVector %v4f16 %cval %param1_16\n"
9989                 },
9990                 {
9991                         "array",
9992
9993                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9994                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9995                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9996                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9997                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9998                         "%carr                 = OpConstantComposite %a4f16 %c_f16_0 %f16_n_1 %f16_1_5 %c_f16_0\n",
9999
10000                         "%v                    = OpVariable %fp_a4f16 Function %carr\n"
10001                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_0\n"
10002                         "%f1                   = OpAccessChain %fp_f16 %v %c_u32_1\n"
10003                         "%f2                   = OpAccessChain %fp_f16 %v %c_u32_2\n"
10004                         "%f3                   = OpAccessChain %fp_f16 %v %c_u32_3\n"
10005                         "%f_val                = OpLoad %f16 %f\n"
10006                         "%f1_val               = OpLoad %f16 %f1\n"
10007                         "%f2_val               = OpLoad %f16 %f2\n"
10008                         "%f3_val               = OpLoad %f16 %f3\n"
10009                         "%ftot1                = OpFAdd %f16 %f_val %f1_val\n"
10010                         "%ftot2                = OpFAdd %f16 %ftot1 %f2_val\n"
10011                         "%ftot3                = OpFAdd %f16 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
10012                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %ftot3\n"
10013                         "%param1_16            = OpFConvert %v4f16 %param1\n"
10014                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
10015                 },
10016                 {
10017                         //
10018                         // [
10019                         //   {
10020                         //      0.0,
10021                         //      [ 1.0, 1.0, 1.0, 1.0]
10022                         //   },
10023                         //   {
10024                         //      1.0,
10025                         //      [ 0.0, 0.5, 0.0, 0.0]
10026                         //   }, //     ^^^
10027                         //   {
10028                         //      0.0,
10029                         //      [ 1.0, 1.0, 1.0, 1.0]
10030                         //   }
10031                         // ]
10032                         "array_of_struct_of_array",
10033
10034                         FLOAT_16_COMMON_TYPES_AND_CONSTS
10035                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
10036                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
10037                         "%stype                = OpTypeStruct %f16 %a4f16\n"
10038                         "%a3stype              = OpTypeArray %stype %c_u32_3\n"
10039                         "%fp_a3stype           = OpTypePointer Function %a3stype\n"
10040                         "%ca4f16_0             = OpConstantComposite %a4f16 %c_f16_0 %c_f16_0_5 %c_f16_0 %c_f16_0\n"
10041                         "%ca4f16_1             = OpConstantComposite %a4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n"
10042                         "%cstype1              = OpConstantComposite %stype %c_f16_0 %ca4f16_1\n"
10043                         "%cstype2              = OpConstantComposite %stype %c_f16_1 %ca4f16_0\n"
10044                         "%carr                 = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
10045
10046                         "%v                    = OpVariable %fp_a3stype Function %carr\n"
10047                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
10048                         "%f_l                  = OpLoad %f16 %f\n"
10049                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %f_l\n"
10050                         "%param1_16            = OpFConvert %v4f16 %param1\n"
10051                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
10052                 }
10053         };
10054
10055         getHalfColorsFullAlpha(inputColors);
10056         outputColors[0] = RGBA(255, 255, 255, 255);
10057         outputColors[1] = RGBA(255, 127, 127, 255);
10058         outputColors[2] = RGBA(127, 255, 127, 255);
10059         outputColors[3] = RGBA(127, 127, 255, 255);
10060
10061         extensions.push_back("VK_KHR_16bit_storage");
10062         extensions.push_back("VK_KHR_shader_float16_int8");
10063         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10064
10065         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
10066         {
10067                 map<string, string> fragments;
10068
10069                 fragments["extension"]  = "OpExtension \"SPV_KHR_16bit_storage\"";
10070                 fragments["capability"] = "OpCapability Float16\n";
10071                 fragments["pre_main"]   = tests[testNdx].constants;
10072                 fragments["testfun"]    = string(functionStart) + tests[testNdx].code + functionEnd;
10073
10074                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, resources, extensions, opConstantCompositeTests.get(), features);
10075         }
10076         return opConstantCompositeTests.release();
10077 }
10078
10079 template<typename T>
10080 void finalizeTestsCreation (T&                                                  specResource,
10081                                                         const map<string, string>&      fragments,
10082                                                         tcu::TestContext&                       testCtx,
10083                                                         tcu::TestCaseGroup&                     testGroup,
10084                                                         const std::string&                      testName,
10085                                                         const VulkanFeatures&           vulkanFeatures,
10086                                                         const vector<string>&           extensions,
10087                                                         const IVec3&                            numWorkGroups);
10088
10089 template<>
10090 void finalizeTestsCreation (GraphicsResources&                  specResource,
10091                                                         const map<string, string>&      fragments,
10092                                                         tcu::TestContext&                       ,
10093                                                         tcu::TestCaseGroup&                     testGroup,
10094                                                         const std::string&                      testName,
10095                                                         const VulkanFeatures&           vulkanFeatures,
10096                                                         const vector<string>&           extensions,
10097                                                         const IVec3&                            )
10098 {
10099         RGBA defaultColors[4];
10100         getDefaultColors(defaultColors);
10101
10102         createTestsForAllStages(testName, defaultColors, defaultColors, fragments, specResource, extensions, &testGroup, vulkanFeatures);
10103 }
10104
10105 template<>
10106 void finalizeTestsCreation (ComputeShaderSpec&                  specResource,
10107                                                         const map<string, string>&      fragments,
10108                                                         tcu::TestContext&                       testCtx,
10109                                                         tcu::TestCaseGroup&                     testGroup,
10110                                                         const std::string&                      testName,
10111                                                         const VulkanFeatures&           vulkanFeatures,
10112                                                         const vector<string>&           extensions,
10113                                                         const IVec3&                            numWorkGroups)
10114 {
10115         specResource.numWorkGroups = numWorkGroups;
10116         specResource.requestedVulkanFeatures = vulkanFeatures;
10117         specResource.extensions = extensions;
10118
10119         specResource.assembly = makeComputeShaderAssembly(fragments);
10120
10121         testGroup.addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", specResource));
10122 }
10123
10124 template<class SpecResource>
10125 tcu::TestCaseGroup* createFloat16LogicalSet (tcu::TestContext& testCtx, const bool nanSupported)
10126 {
10127         const string                                            nan                                     = nanSupported ? "_nan" : "";
10128         const string                                            groupName                       = "logical" + nan;
10129         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Float 16 logical tests"));
10130
10131         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10132         const string                                            spvCapabilities         = string("OpCapability StorageUniformBufferBlock16\n") + (nanSupported ? "OpCapability SignedZeroInfNanPreserve\n" : "");
10133         const string                                            spvExtensions           = string("OpExtension \"SPV_KHR_16bit_storage\"\n") + (nanSupported ? "OpExtension \"SPV_KHR_float_controls\"\n" : "");
10134         const string                                            spvExecutionMode        = nanSupported ? "OpExecutionMode %BP_main SignedZeroInfNanPreserve 16\n" : "";
10135         const deUint32                                          numDataPoints           = 16;
10136         const vector<deFloat16>                         float16Data                     = getFloat16s(rnd, numDataPoints);
10137         const vector<deFloat16>                         float16Data1            = squarize(float16Data, 0);
10138         const vector<deFloat16>                         float16Data2            = squarize(float16Data, 1);
10139         const vector<deFloat16>                         float16DataVec1         = squarizeVector(float16Data, 0);
10140         const vector<deFloat16>                         float16DataVec2         = squarizeVector(float16Data, 1);
10141         const vector<deFloat16>                         float16OutDummy         (float16Data1.size(), 0);
10142         const vector<deFloat16>                         float16OutVecDummy      (float16DataVec1.size(), 0);
10143
10144         struct TestOp
10145         {
10146                 const char*             opCode;
10147                 VerifyIOFunc    verifyFuncNan;
10148                 VerifyIOFunc    verifyFuncNonNan;
10149                 const deUint32  argCount;
10150         };
10151
10152         const TestOp    testOps[]       =
10153         {
10154                 { "OpIsNan"                                             ,       compareFP16Logical<fp16isNan,                           true,  false, true>,    compareFP16Logical<fp16isNan,                           true,  false, false>,   1       },
10155                 { "OpIsInf"                                             ,       compareFP16Logical<fp16isInf,                           true,  false, true>,    compareFP16Logical<fp16isInf,                           true,  false, false>,   1       },
10156                 { "OpFOrdEqual"                                 ,       compareFP16Logical<fp16isEqual,                         false, true,  true>,    compareFP16Logical<fp16isEqual,                         false, true,  false>,   2       },
10157                 { "OpFUnordEqual"                               ,       compareFP16Logical<fp16isEqual,                         false, false, true>,    compareFP16Logical<fp16isEqual,                         false, false, false>,   2       },
10158                 { "OpFOrdNotEqual"                              ,       compareFP16Logical<fp16isUnequal,                       false, true,  true>,    compareFP16Logical<fp16isUnequal,                       false, true,  false>,   2       },
10159                 { "OpFUnordNotEqual"                    ,       compareFP16Logical<fp16isUnequal,                       false, false, true>,    compareFP16Logical<fp16isUnequal,                       false, false, false>,   2       },
10160                 { "OpFOrdLessThan"                              ,       compareFP16Logical<fp16isLess,                          false, true,  true>,    compareFP16Logical<fp16isLess,                          false, true,  false>,   2       },
10161                 { "OpFUnordLessThan"                    ,       compareFP16Logical<fp16isLess,                          false, false, true>,    compareFP16Logical<fp16isLess,                          false, false, false>,   2       },
10162                 { "OpFOrdGreaterThan"                   ,       compareFP16Logical<fp16isGreater,                       false, true,  true>,    compareFP16Logical<fp16isGreater,                       false, true,  false>,   2       },
10163                 { "OpFUnordGreaterThan"                 ,       compareFP16Logical<fp16isGreater,                       false, false, true>,    compareFP16Logical<fp16isGreater,                       false, false, false>,   2       },
10164                 { "OpFOrdLessThanEqual"                 ,       compareFP16Logical<fp16isLessOrEqual,           false, true,  true>,    compareFP16Logical<fp16isLessOrEqual,           false, true,  false>,   2       },
10165                 { "OpFUnordLessThanEqual"               ,       compareFP16Logical<fp16isLessOrEqual,           false, false, true>,    compareFP16Logical<fp16isLessOrEqual,           false, false, false>,   2       },
10166                 { "OpFOrdGreaterThanEqual"              ,       compareFP16Logical<fp16isGreaterOrEqual,        false, true,  true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, true,  false>,   2       },
10167                 { "OpFUnordGreaterThanEqual"    ,       compareFP16Logical<fp16isGreaterOrEqual,        false, false, true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, false, false>,   2       },
10168         };
10169
10170         { // scalar cases
10171                 const StringTemplate preMain
10172                 (
10173                         "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10174                         "      %f16 = OpTypeFloat 16\n"
10175                         "  %c_f16_0 = OpConstant %f16 0.0\n"
10176                         "  %c_f16_1 = OpConstant %f16 1.0\n"
10177                         "   %up_f16 = OpTypePointer Uniform %f16\n"
10178                         "   %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
10179                         "   %SSBO16 = OpTypeStruct %ra_f16\n"
10180                         "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10181                         "%ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
10182                         "%ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
10183                         " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10184                 );
10185
10186                 const StringTemplate decoration
10187                 (
10188                         "OpDecorate %ra_f16 ArrayStride 2\n"
10189                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
10190                         "OpDecorate %SSBO16 BufferBlock\n"
10191                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
10192                         "OpDecorate %ssbo_src0 Binding 0\n"
10193                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
10194                         "OpDecorate %ssbo_src1 Binding 1\n"
10195                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
10196                         "OpDecorate %ssbo_dst Binding 2\n"
10197                 );
10198
10199                 const StringTemplate testFun
10200                 (
10201                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10202                         "    %param = OpFunctionParameter %v4f32\n"
10203
10204                         "    %entry = OpLabel\n"
10205                         "        %i = OpVariable %fp_i32 Function\n"
10206                         "             OpStore %i %c_i32_0\n"
10207                         "             OpBranch %loop\n"
10208
10209                         "     %loop = OpLabel\n"
10210                         "    %i_cmp = OpLoad %i32 %i\n"
10211                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10212                         "             OpLoopMerge %merge %next None\n"
10213                         "             OpBranchConditional %lt %write %merge\n"
10214
10215                         "    %write = OpLabel\n"
10216                         "      %ndx = OpLoad %i32 %i\n"
10217
10218                         "     %src0 = OpAccessChain %up_f16 %ssbo_src0 %c_i32_0 %ndx\n"
10219                         " %val_src0 = OpLoad %f16 %src0\n"
10220
10221                         "${op_arg1_calc}"
10222
10223                         " %val_bdst = ${op_code} %bool %val_src0 ${op_arg1}\n"
10224                         "  %val_dst = OpSelect %f16 %val_bdst %c_f16_1 %c_f16_0\n"
10225                         "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10226                         "             OpStore %dst %val_dst\n"
10227                         "             OpBranch %next\n"
10228
10229                         "     %next = OpLabel\n"
10230                         "    %i_cur = OpLoad %i32 %i\n"
10231                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10232                         "             OpStore %i %i_new\n"
10233                         "             OpBranch %loop\n"
10234
10235                         "    %merge = OpLabel\n"
10236                         "             OpReturnValue %param\n"
10237
10238                         "             OpFunctionEnd\n"
10239                 );
10240
10241                 const StringTemplate arg1Calc
10242                 (
10243                         "     %src1 = OpAccessChain %up_f16 %ssbo_src1 %c_i32_0 %ndx\n"
10244                         " %val_src1 = OpLoad %f16 %src1\n"
10245                 );
10246
10247                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10248                 {
10249                         const size_t            iterations              = float16Data1.size();
10250                         const TestOp&           testOp                  = testOps[testOpsIdx];
10251                         const string            testName                = de::toLower(string(testOp.opCode)) + "_scalar";
10252                         SpecResource            specResource;
10253                         map<string, string>     specs;
10254                         VulkanFeatures          features;
10255                         map<string, string>     fragments;
10256                         vector<string>          extensions;
10257
10258                         specs["num_data_points"]        = de::toString(iterations);
10259                         specs["op_code"]                        = testOp.opCode;
10260                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10261                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10262
10263                         fragments["extension"]          = spvExtensions;
10264                         fragments["capability"]         = spvCapabilities;
10265                         fragments["execution_mode"]     = spvExecutionMode;
10266                         fragments["decoration"]         = decoration.specialize(specs);
10267                         fragments["pre_main"]           = preMain.specialize(specs);
10268                         fragments["testfun"]            = testFun.specialize(specs);
10269
10270                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10271                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10272                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10273                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10274
10275                         extensions.push_back("VK_KHR_16bit_storage");
10276                         extensions.push_back("VK_KHR_shader_float16_int8");
10277
10278                         if (nanSupported)
10279                         {
10280                                 extensions.push_back("VK_KHR_shader_float_controls");
10281
10282                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10283                         }
10284
10285                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10286                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10287
10288                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10289                 }
10290         }
10291         { // vector cases
10292                 const StringTemplate preMain
10293                 (
10294                         "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10295                         "     %v2bool = OpTypeVector %bool 2\n"
10296                         "        %f16 = OpTypeFloat 16\n"
10297                         "    %c_f16_0 = OpConstant %f16 0.0\n"
10298                         "    %c_f16_1 = OpConstant %f16 1.0\n"
10299                         "      %v2f16 = OpTypeVector %f16 2\n"
10300                         "%c_v2f16_0_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10301                         "%c_v2f16_1_1 = OpConstantComposite %v2f16 %c_f16_1 %c_f16_1\n"
10302                         "   %up_v2f16 = OpTypePointer Uniform %v2f16\n"
10303                         "   %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
10304                         "     %SSBO16 = OpTypeStruct %ra_v2f16\n"
10305                         "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10306                         "  %ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
10307                         "  %ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
10308                         "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10309                 );
10310
10311                 const StringTemplate decoration
10312                 (
10313                         "OpDecorate %ra_v2f16 ArrayStride 4\n"
10314                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
10315                         "OpDecorate %SSBO16 BufferBlock\n"
10316                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
10317                         "OpDecorate %ssbo_src0 Binding 0\n"
10318                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
10319                         "OpDecorate %ssbo_src1 Binding 1\n"
10320                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
10321                         "OpDecorate %ssbo_dst Binding 2\n"
10322                 );
10323
10324                 const StringTemplate testFun
10325                 (
10326                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10327                         "    %param = OpFunctionParameter %v4f32\n"
10328
10329                         "    %entry = OpLabel\n"
10330                         "        %i = OpVariable %fp_i32 Function\n"
10331                         "             OpStore %i %c_i32_0\n"
10332                         "             OpBranch %loop\n"
10333
10334                         "     %loop = OpLabel\n"
10335                         "    %i_cmp = OpLoad %i32 %i\n"
10336                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10337                         "             OpLoopMerge %merge %next None\n"
10338                         "             OpBranchConditional %lt %write %merge\n"
10339
10340                         "    %write = OpLabel\n"
10341                         "      %ndx = OpLoad %i32 %i\n"
10342
10343                         "     %src0 = OpAccessChain %up_v2f16 %ssbo_src0 %c_i32_0 %ndx\n"
10344                         " %val_src0 = OpLoad %v2f16 %src0\n"
10345
10346                         "${op_arg1_calc}"
10347
10348                         " %val_bdst = ${op_code} %v2bool %val_src0 ${op_arg1}\n"
10349                         "  %val_dst = OpSelect %v2f16 %val_bdst %c_v2f16_1_1 %c_v2f16_0_0\n"
10350                         "      %dst = OpAccessChain %up_v2f16 %ssbo_dst %c_i32_0 %ndx\n"
10351                         "             OpStore %dst %val_dst\n"
10352                         "             OpBranch %next\n"
10353
10354                         "     %next = OpLabel\n"
10355                         "    %i_cur = OpLoad %i32 %i\n"
10356                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10357                         "             OpStore %i %i_new\n"
10358                         "             OpBranch %loop\n"
10359
10360                         "    %merge = OpLabel\n"
10361                         "             OpReturnValue %param\n"
10362
10363                         "             OpFunctionEnd\n"
10364                 );
10365
10366                 const StringTemplate arg1Calc
10367                 (
10368                         "     %src1 = OpAccessChain %up_v2f16 %ssbo_src1 %c_i32_0 %ndx\n"
10369                         " %val_src1 = OpLoad %v2f16 %src1\n"
10370                 );
10371
10372                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10373                 {
10374                         const deUint32          itemsPerVec     = 2;
10375                         const size_t            iterations      = float16DataVec1.size() / itemsPerVec;
10376                         const TestOp&           testOp          = testOps[testOpsIdx];
10377                         const string            testName        = de::toLower(string(testOp.opCode)) + "_vector";
10378                         SpecResource            specResource;
10379                         map<string, string>     specs;
10380                         vector<string>          extensions;
10381                         VulkanFeatures          features;
10382                         map<string, string>     fragments;
10383
10384                         specs["num_data_points"]        = de::toString(iterations);
10385                         specs["op_code"]                        = testOp.opCode;
10386                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10387                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10388
10389                         fragments["extension"]          = spvExtensions;
10390                         fragments["capability"]         = spvCapabilities;
10391                         fragments["execution_mode"]     = spvExecutionMode;
10392                         fragments["decoration"]         = decoration.specialize(specs);
10393                         fragments["pre_main"]           = preMain.specialize(specs);
10394                         fragments["testfun"]            = testFun.specialize(specs);
10395
10396                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10397                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10398                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutVecDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10399                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10400
10401                         extensions.push_back("VK_KHR_16bit_storage");
10402                         extensions.push_back("VK_KHR_shader_float16_int8");
10403
10404                         if (nanSupported)
10405                         {
10406                                 extensions.push_back("VK_KHR_shader_float_controls");
10407
10408                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10409                         }
10410
10411                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10412                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10413
10414                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10415                 }
10416         }
10417
10418         return testGroup.release();
10419 }
10420
10421 bool compareFP16FunctionSetFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10422 {
10423         if (inputs.size() != 1 || outputAllocs.size() != 1)
10424                 return false;
10425
10426         vector<deUint8> input1Bytes;
10427
10428         inputs[0].getBytes(input1Bytes);
10429
10430         const deUint16* const   input1AsFP16    = (const deUint16*)&input1Bytes[0];
10431         const deUint16* const   outputAsFP16    = (const deUint16*)outputAllocs[0]->getHostPtr();
10432         std::string                             error;
10433
10434         for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deUint16); ++idx)
10435         {
10436                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
10437                 {
10438                         log << TestLog::Message << error << TestLog::EndMessage;
10439
10440                         return false;
10441                 }
10442         }
10443
10444         return true;
10445 }
10446
10447 template<class SpecResource>
10448 tcu::TestCaseGroup* createFloat16FuncSet (tcu::TestContext& testCtx)
10449 {
10450         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "function", "Float 16 function call related tests"));
10451
10452         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10453         const StringTemplate                            capabilities            ("OpCapability ${cap}\n");
10454         const deUint32                                          numDataPoints           = 256;
10455         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10456         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10457         map<string, string>                                     fragments;
10458
10459         struct TestType
10460         {
10461                 const deUint32  typeComponents;
10462                 const char*             typeName;
10463                 const char*             typeDecls;
10464         };
10465
10466         const TestType  testTypes[]     =
10467         {
10468                 {
10469                         1,
10470                         "f16",
10471                         ""
10472                 },
10473                 {
10474                         2,
10475                         "v2f16",
10476                         "      %v2f16 = OpTypeVector %f16 2\n"
10477                         "  %c_v2f16_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10478                 },
10479                 {
10480                         4,
10481                         "v4f16",
10482                         "      %v4f16 = OpTypeVector %f16 4\n"
10483                         "  %c_v4f16_0 = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_0 %c_f16_0\n"
10484                 },
10485         };
10486
10487         const StringTemplate preMain
10488         (
10489                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10490                 "     %v2bool = OpTypeVector %bool 2\n"
10491                 "        %f16 = OpTypeFloat 16\n"
10492                 "    %c_f16_0 = OpConstant %f16 0.0\n"
10493
10494                 "${type_decls}"
10495
10496                 "  %${tt}_fun = OpTypeFunction %${tt} %${tt}\n"
10497                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10498                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10499                 "     %SSBO16 = OpTypeStruct %ra_${tt}\n"
10500                 "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10501                 "   %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10502                 "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10503         );
10504
10505         const StringTemplate decoration
10506         (
10507                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10508                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10509                 "OpDecorate %SSBO16 BufferBlock\n"
10510                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10511                 "OpDecorate %ssbo_src Binding 0\n"
10512                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10513                 "OpDecorate %ssbo_dst Binding 1\n"
10514         );
10515
10516         const StringTemplate testFun
10517         (
10518                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10519                 "    %param = OpFunctionParameter %v4f32\n"
10520                 "    %entry = OpLabel\n"
10521
10522                 "        %i = OpVariable %fp_i32 Function\n"
10523                 "             OpStore %i %c_i32_0\n"
10524                 "             OpBranch %loop\n"
10525
10526                 "     %loop = OpLabel\n"
10527                 "    %i_cmp = OpLoad %i32 %i\n"
10528                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10529                 "             OpLoopMerge %merge %next None\n"
10530                 "             OpBranchConditional %lt %write %merge\n"
10531
10532                 "    %write = OpLabel\n"
10533                 "      %ndx = OpLoad %i32 %i\n"
10534
10535                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10536                 "  %val_src = OpLoad %${tt} %src\n"
10537
10538                 "  %val_dst = OpFunctionCall %${tt} %pass_fun %val_src\n"
10539                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10540                 "             OpStore %dst %val_dst\n"
10541                 "             OpBranch %next\n"
10542
10543                 "     %next = OpLabel\n"
10544                 "    %i_cur = OpLoad %i32 %i\n"
10545                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10546                 "             OpStore %i %i_new\n"
10547                 "             OpBranch %loop\n"
10548
10549                 "    %merge = OpLabel\n"
10550                 "             OpReturnValue %param\n"
10551
10552                 "             OpFunctionEnd\n"
10553
10554                 " %pass_fun = OpFunction %${tt} None %${tt}_fun\n"
10555                 "   %param0 = OpFunctionParameter %${tt}\n"
10556                 " %entry_pf = OpLabel\n"
10557                 "     %res0 = OpFAdd %${tt} %param0 %c_${tt}_0\n"
10558                 "             OpReturnValue %res0\n"
10559                 "             OpFunctionEnd\n"
10560         );
10561
10562         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10563         {
10564                 const TestType&         testType                = testTypes[testTypeIdx];
10565                 const string            testName                = testType.typeName;
10566                 const deUint32          itemsPerType    = testType.typeComponents;
10567                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10568                 const size_t            typeStride              = itemsPerType * sizeof(deFloat16);
10569                 SpecResource            specResource;
10570                 map<string, string>     specs;
10571                 VulkanFeatures          features;
10572                 vector<string>          extensions;
10573
10574                 specs["cap"]                            = "StorageUniformBufferBlock16";
10575                 specs["num_data_points"]        = de::toString(iterations);
10576                 specs["tt"]                                     = testType.typeName;
10577                 specs["tt_stride"]                      = de::toString(typeStride);
10578                 specs["type_decls"]                     = testType.typeDecls;
10579
10580                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10581                 fragments["capability"]         = capabilities.specialize(specs);
10582                 fragments["decoration"]         = decoration.specialize(specs);
10583                 fragments["pre_main"]           = preMain.specialize(specs);
10584                 fragments["testfun"]            = testFun.specialize(specs);
10585
10586                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10587                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10588                 specResource.verifyIO = compareFP16FunctionSetFunc;
10589
10590                 extensions.push_back("VK_KHR_16bit_storage");
10591                 extensions.push_back("VK_KHR_shader_float16_int8");
10592
10593                 features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10594                 features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10595
10596                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10597         }
10598
10599         return testGroup.release();
10600 }
10601
10602 struct getV_    { deUint32 inline operator()(deUint32 v) const  { return v;        } getV_(){} };
10603 struct getV0    { deUint32 inline operator()(deUint32 v) const  { return v & (~1); } getV0(){} };
10604 struct getV1    { deUint32 inline operator()(deUint32 v) const  { return v | ( 1); } getV1(){} };
10605
10606 template<deUint32 R, deUint32 N>
10607 inline static deUint32 getOffset(deUint32 x, deUint32 y, deUint32 n)
10608 {
10609         return N * ((R * y) + x) + n;
10610 }
10611
10612 template<deUint32 R, deUint32 N, class X0, class X1, class Y0, class Y1>
10613 struct getFDelta
10614 {
10615         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10616         {
10617                 DE_STATIC_ASSERT(R%2 == 0);
10618                 DE_ASSERT(flavor == 0);
10619                 DE_UNREF(flavor);
10620
10621                 const X0                        x0;
10622                 const X1                        x1;
10623                 const Y0                        y0;
10624                 const Y1                        y1;
10625                 const deFloat16         v0      = data[getOffset<R, N>(x0(x), y0(y), n)];
10626                 const deFloat16         v1      = data[getOffset<R, N>(x1(x), y1(y), n)];
10627                 const tcu::Float16      f0      = tcu::Float16(v0);
10628                 const tcu::Float16      f1      = tcu::Float16(v1);
10629                 const float                     d0      = f0.asFloat();
10630                 const float                     d1      = f1.asFloat();
10631                 const float                     d       = d1 - d0;
10632
10633                 return d;
10634         }
10635
10636         getFDelta(){}
10637 };
10638
10639 template<deUint32 F, class Class0, class Class1>
10640 struct getFOneOf
10641 {
10642         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10643         {
10644                 DE_ASSERT(flavor < F);
10645
10646                 if (flavor == 0)
10647                 {
10648                         Class0 c;
10649
10650                         return c(data, x, y, n, flavor);
10651                 }
10652                 else
10653                 {
10654                         Class1 c;
10655
10656                         return c(data, x, y, n, flavor - 1);
10657                 }
10658         }
10659
10660         getFOneOf(){}
10661 };
10662
10663 template<class FineX0, class FineX1, class FineY0, class FineY1>
10664 struct calcWidthOf4
10665 {
10666         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10667         {
10668                 DE_ASSERT(flavor < 4);
10669
10670                 const deUint32                                          flavorX = (flavor & 1) == 0 ? 0 : 1;
10671                 const deUint32                                          flavorY = (flavor & 2) == 0 ? 0 : 1;
10672                 const getFOneOf<2, FineX0, FineX1>      cx;
10673                 const getFOneOf<2, FineY0, FineY1>      cy;
10674                 float                                                           v               = 0;
10675
10676                 v += fabsf(cx(data, x, y, n, flavorX));
10677                 v += fabsf(cy(data, x, y, n, flavorY));
10678
10679                 return v;
10680         }
10681
10682         calcWidthOf4(){}
10683 };
10684
10685 template<deUint32 R, deUint32 N, class Derivative>
10686 bool compareDerivativeWithFlavor (const deFloat16* inputAsFP16, const deFloat16* outputAsFP16, deUint32 flavor, std::string& error)
10687 {
10688         const deUint32          numDataPointsByAxis     = R;
10689         const Derivative        derivativeFunc;
10690
10691         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10692         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10693         for (deUint32 n = 0; n < N; ++n)
10694         {
10695                 const float             expectedFloat   = derivativeFunc(inputAsFP16, x, y, n, flavor);
10696                 deFloat16               expected                = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_NEAREST_EVEN);
10697                 const deFloat16 output                  = outputAsFP16[getOffset<R, N>(x, y, n)];
10698
10699                 bool                    reportError             = !compare16BitFloat(expected, output, error);
10700
10701                 if (reportError)
10702                 {
10703                         expected        = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_ZERO);
10704                         reportError     = !compare16BitFloat(expected, output, error);
10705                 }
10706
10707                 if (reportError)
10708                 {
10709                         error = "subcase at " + de::toString(x) + "," + de::toString(y) + "," + de::toString(n) + ": " + error;
10710
10711                         return false;
10712                 }
10713         }
10714
10715         return true;
10716 }
10717
10718 template<deUint32 R, deUint32 N, deUint32 FLAVOUR_COUNT, class Derivative>
10719 bool compareDerivative (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10720 {
10721         if (inputs.size() != 1 || outputAllocs.size() != 1)
10722                 return false;
10723
10724         deUint32                        successfulRuns                  = FLAVOUR_COUNT;
10725         std::string                     results[FLAVOUR_COUNT];
10726         vector<deUint8>         inputBytes;
10727
10728         inputs[0].getBytes(inputBytes);
10729
10730         const deFloat16*        inputAsFP16             = reinterpret_cast<deFloat16* const>(&inputBytes.front());
10731         const deFloat16*        outputAsFP16    = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
10732
10733         DE_ASSERT(inputBytes.size() ==  R * R * N * sizeof(deFloat16));
10734
10735         for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; ++flavor)
10736                 if (compareDerivativeWithFlavor<R, N, Derivative> (inputAsFP16, outputAsFP16, flavor, results[flavor]))
10737                 {
10738                         break;
10739                 }
10740                 else
10741                 {
10742                         successfulRuns--;
10743                 }
10744
10745         if (successfulRuns == 0)
10746                 for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; flavor++)
10747                         log << TestLog::Message << "At flavor #" << flavor << " " << results[flavor] << TestLog::EndMessage;
10748
10749         return successfulRuns > 0;
10750 }
10751
10752 template<deUint32 R, deUint32 N>
10753 tcu::TestCaseGroup* createDerivativeTests (tcu::TestContext& testCtx)
10754 {
10755         typedef getFDelta<R, N, getV0, getV1, getV_, getV_> getFDxFine;
10756         typedef getFDelta<R, N, getV_, getV_, getV0, getV1> getFDyFine;
10757
10758         typedef getFDelta<R, N, getV0, getV1, getV0, getV0> getFdxCoarse0;
10759         typedef getFDelta<R, N, getV0, getV1, getV1, getV1> getFdxCoarse1;
10760         typedef getFDelta<R, N, getV0, getV0, getV0, getV1> getFdyCoarse0;
10761         typedef getFDelta<R, N, getV1, getV1, getV0, getV1> getFdyCoarse1;
10762         typedef getFOneOf<2, getFdxCoarse0, getFdxCoarse1> getFDxCoarse;
10763         typedef getFOneOf<2, getFdyCoarse0, getFdyCoarse1> getFDyCoarse;
10764
10765         typedef calcWidthOf4<getFDxFine, getFDxFine, getFDyFine, getFDyFine> getFWidthFine;
10766         typedef calcWidthOf4<getFdxCoarse0, getFdxCoarse1, getFdyCoarse0, getFdyCoarse1> getFWidthCoarse;
10767
10768         typedef getFOneOf<3, getFDxFine, getFDxCoarse> getFDx;
10769         typedef getFOneOf<3, getFDyFine, getFDyCoarse> getFDy;
10770         typedef getFOneOf<5, getFWidthFine, getFWidthCoarse> getFWidth;
10771
10772         const std::string                                       testGroupName           (std::string("derivative_") + de::toString(N));
10773         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Derivative instruction tests"));
10774
10775         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10776         const deUint32                                          numDataPointsByAxis     = R;
10777         const deUint32                                          numDataPoints           = N * numDataPointsByAxis * numDataPointsByAxis;
10778         vector<deFloat16>                                       float16InputX;
10779         vector<deFloat16>                                       float16InputY;
10780         vector<deFloat16>                                       float16InputW;
10781         vector<deFloat16>                                       float16OutputDummy      (numDataPoints, 0);
10782         RGBA                                                            defaultColors[4];
10783
10784         getDefaultColors(defaultColors);
10785
10786         float16InputX.reserve(numDataPoints);
10787         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10788         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10789         for (deUint32 n = 0; n < N; ++n)
10790         {
10791                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(x * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10792
10793                 if (y%2 == 0)
10794                         float16InputX.push_back(tcu::Float16(sin(arg)).bits());
10795                 else
10796                         float16InputX.push_back(tcu::Float16(cos(arg)).bits());
10797         }
10798
10799         float16InputY.reserve(numDataPoints);
10800         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10801         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10802         for (deUint32 n = 0; n < N; ++n)
10803         {
10804                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(y * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10805
10806                 if (x%2 == 0)
10807                         float16InputY.push_back(tcu::Float16(sin(arg)).bits());
10808                 else
10809                         float16InputY.push_back(tcu::Float16(cos(arg)).bits());
10810         }
10811
10812         const deFloat16 testNumbers[]   =
10813         {
10814                 tcu::Float16( 2.0  ).bits(),
10815                 tcu::Float16( 4.0  ).bits(),
10816                 tcu::Float16( 8.0  ).bits(),
10817                 tcu::Float16( 16.0 ).bits(),
10818                 tcu::Float16( 32.0 ).bits(),
10819                 tcu::Float16( 64.0 ).bits(),
10820                 tcu::Float16( 128.0).bits(),
10821                 tcu::Float16( 256.0).bits(),
10822                 tcu::Float16( 512.0).bits(),
10823                 tcu::Float16(-2.0  ).bits(),
10824                 tcu::Float16(-4.0  ).bits(),
10825                 tcu::Float16(-8.0  ).bits(),
10826                 tcu::Float16(-16.0 ).bits(),
10827                 tcu::Float16(-32.0 ).bits(),
10828                 tcu::Float16(-64.0 ).bits(),
10829                 tcu::Float16(-128.0).bits(),
10830                 tcu::Float16(-256.0).bits(),
10831                 tcu::Float16(-512.0).bits(),
10832         };
10833
10834         float16InputW.reserve(numDataPoints);
10835         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10836         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10837         for (deUint32 n = 0; n < N; ++n)
10838                 float16InputW.push_back(testNumbers[rnd.getInt(0, DE_LENGTH_OF_ARRAY(testNumbers) - 1)]);
10839
10840         struct TestOp
10841         {
10842                 const char*                     opCode;
10843                 vector<deFloat16>&      inputData;
10844                 VerifyIOFunc            verifyFunc;
10845         };
10846
10847         const TestOp    testOps[]       =
10848         {
10849                 { "OpDPdxFine"          ,       float16InputX   ,       compareDerivative<R, N, 1, getFDxFine           >       },
10850                 { "OpDPdyFine"          ,       float16InputY   ,       compareDerivative<R, N, 1, getFDyFine           >       },
10851                 { "OpFwidthFine"        ,       float16InputW   ,       compareDerivative<R, N, 1, getFWidthFine        >       },
10852                 { "OpDPdxCoarse"        ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10853                 { "OpDPdyCoarse"        ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10854                 { "OpFwidthCoarse"      ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10855                 { "OpDPdx"                      ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10856                 { "OpDPdy"                      ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10857                 { "OpFwidth"            ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10858         };
10859
10860         struct TestType
10861         {
10862                 const deUint32  typeComponents;
10863                 const char*             typeName;
10864                 const char*             typeDecls;
10865         };
10866
10867         const TestType  testTypes[]     =
10868         {
10869                 {
10870                         1,
10871                         "f16",
10872                         ""
10873                 },
10874                 {
10875                         2,
10876                         "v2f16",
10877                         "      %v2f16 = OpTypeVector %f16 2\n"
10878                 },
10879                 {
10880                         4,
10881                         "v4f16",
10882                         "      %v4f16 = OpTypeVector %f16 4\n"
10883                 },
10884         };
10885
10886         const deUint32  testTypeNdx     = (N == 1) ? 0
10887                                                                 : (N == 2) ? 1
10888                                                                 : (N == 4) ? 2
10889                                                                 : DE_LENGTH_OF_ARRAY(testTypes);
10890         const TestType& testType        =       testTypes[testTypeNdx];
10891
10892         DE_ASSERT(testTypeNdx < DE_LENGTH_OF_ARRAY(testTypes));
10893         DE_ASSERT(testType.typeComponents == N);
10894
10895         const StringTemplate preMain
10896         (
10897                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10898                 " %c_u32_xw = OpConstant %u32 ${items_by_x}\n"
10899                 "      %f16 = OpTypeFloat 16\n"
10900                 "${type_decls}"
10901                 " %up_${tt} = OpTypePointer Uniform %${tt}\n"
10902                 " %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10903                 "   %SSBO16 = OpTypeStruct %ra_${tt}\n"
10904                 "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10905                 " %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10906                 " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10907         );
10908
10909         const StringTemplate decoration
10910         (
10911                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10912                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10913                 "OpDecorate %SSBO16 BufferBlock\n"
10914                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10915                 "OpDecorate %ssbo_src Binding 0\n"
10916                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10917                 "OpDecorate %ssbo_dst Binding 1\n"
10918         );
10919
10920         const StringTemplate testFun
10921         (
10922                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10923                 "    %param = OpFunctionParameter %v4f32\n"
10924                 "    %entry = OpLabel\n"
10925
10926                 "  %loc_x_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_0\n"
10927                 "  %loc_y_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_1\n"
10928                 "      %x_c = OpLoad %f32 %loc_x_c\n"
10929                 "      %y_c = OpLoad %f32 %loc_y_c\n"
10930                 "    %x_idx = OpConvertFToU %u32 %x_c\n"
10931                 "    %y_idx = OpConvertFToU %u32 %y_c\n"
10932                 "    %ndx_y = OpIMul %u32 %y_idx %c_u32_xw\n"
10933                 "      %ndx = OpIAdd %u32 %ndx_y %x_idx\n"
10934
10935                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10936                 "  %val_src = OpLoad %${tt} %src\n"
10937                 "  %val_dst = ${op_code} %${tt} %val_src\n"
10938                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10939                 "             OpStore %dst %val_dst\n"
10940                 "             OpBranch %merge\n"
10941
10942                 "    %merge = OpLabel\n"
10943                 "             OpReturnValue %param\n"
10944
10945                 "             OpFunctionEnd\n"
10946         );
10947
10948         for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10949         {
10950                 const TestOp&           testOp                  = testOps[testOpsIdx];
10951                 const string            testName                = de::toLower(string(testOp.opCode));
10952                 const size_t            typeStride              = N * sizeof(deFloat16);
10953                 GraphicsResources       specResource;
10954                 map<string, string>     specs;
10955                 VulkanFeatures          features;
10956                 vector<string>          extensions;
10957                 map<string, string>     fragments;
10958                 SpecConstants           noSpecConstants;
10959                 PushConstants           noPushConstants;
10960                 GraphicsInterfaces      noInterfaces;
10961
10962                 specs["op_code"]                        = testOp.opCode;
10963                 specs["num_data_points"]        = de::toString(testOp.inputData.size() / N);
10964                 specs["items_by_x"]                     = de::toString(numDataPointsByAxis);
10965                 specs["tt"]                                     = testType.typeName;
10966                 specs["tt_stride"]                      = de::toString(typeStride);
10967                 specs["type_decls"]                     = testType.typeDecls;
10968
10969                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10970                 fragments["capability"]         = "OpCapability DerivativeControl\nOpCapability StorageUniformBufferBlock16\n";
10971                 fragments["decoration"]         = decoration.specialize(specs);
10972                 fragments["pre_main"]           = preMain.specialize(specs);
10973                 fragments["testfun"]            = testFun.specialize(specs);
10974
10975                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(testOp.inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10976                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10977                 specResource.verifyIO = testOp.verifyFunc;
10978
10979                 extensions.push_back("VK_KHR_16bit_storage");
10980                 extensions.push_back("VK_KHR_shader_float16_int8");
10981
10982                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10983                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10984
10985                 createTestForStage(VK_SHADER_STAGE_FRAGMENT_BIT, testName.c_str(), defaultColors, defaultColors, fragments, noSpecConstants,
10986                                                         noPushConstants, specResource, noInterfaces, extensions, features, testGroup.get(), QP_TEST_RESULT_FAIL, string(), true);
10987         }
10988
10989         return testGroup.release();
10990 }
10991
10992 bool compareFP16VectorExtractFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10993 {
10994         if (inputs.size() != 2 || outputAllocs.size() != 1)
10995                 return false;
10996
10997         vector<deUint8> input1Bytes;
10998         vector<deUint8> input2Bytes;
10999
11000         inputs[0].getBytes(input1Bytes);
11001         inputs[1].getBytes(input2Bytes);
11002
11003         DE_ASSERT(input1Bytes.size() > 0);
11004         DE_ASSERT(input2Bytes.size() > 0);
11005         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
11006
11007         const size_t                    iterations              = input2Bytes.size() / sizeof(deUint32);
11008         const size_t                    components              = input1Bytes.size() / (sizeof(deFloat16) * iterations);
11009         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
11010         const deUint32* const   inputIndices    = (const deUint32*)&input2Bytes[0];
11011         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11012         std::string                             error;
11013
11014         DE_ASSERT(components == 2 || components == 4);
11015         DE_ASSERT(input1Bytes.size() == iterations * components * sizeof(deFloat16));
11016
11017         for (size_t idx = 0; idx < iterations; ++idx)
11018         {
11019                 const deUint32  componentNdx    = inputIndices[idx];
11020
11021                 DE_ASSERT(componentNdx < components);
11022
11023                 const deFloat16 expected                = input1AsFP16[components * idx + componentNdx];
11024
11025                 if (!compare16BitFloat(expected, outputAsFP16[idx], error))
11026                 {
11027                         log << TestLog::Message << "At " << idx << error << TestLog::EndMessage;
11028
11029                         return false;
11030                 }
11031         }
11032
11033         return true;
11034 }
11035
11036 template<class SpecResource>
11037 tcu::TestCaseGroup* createFloat16VectorExtractSet (tcu::TestContext& testCtx)
11038 {
11039         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorextractdynamic", "OpVectorExtractDynamic tests"));
11040
11041         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
11042         const deUint32                                          numDataPoints           = 256;
11043         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
11044         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
11045
11046         struct TestType
11047         {
11048                 const deUint32  typeComponents;
11049                 const size_t    typeStride;
11050                 const char*             typeName;
11051                 const char*             typeDecls;
11052         };
11053
11054         const TestType  testTypes[]     =
11055         {
11056                 {
11057                         2,
11058                         2 * sizeof(deFloat16),
11059                         "v2f16",
11060                         "      %v2f16 = OpTypeVector %f16 2\n"
11061                 },
11062                 {
11063                         3,
11064                         4 * sizeof(deFloat16),
11065                         "v3f16",
11066                         "      %v3f16 = OpTypeVector %f16 3\n"
11067                 },
11068                 {
11069                         4,
11070                         4 * sizeof(deFloat16),
11071                         "v4f16",
11072                         "      %v4f16 = OpTypeVector %f16 4\n"
11073                 },
11074         };
11075
11076         const StringTemplate preMain
11077         (
11078                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11079                 "        %f16 = OpTypeFloat 16\n"
11080
11081                 "${type_decl}"
11082
11083                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
11084                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
11085                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
11086                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
11087
11088                 "     %up_u32 = OpTypePointer Uniform %u32\n"
11089                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
11090                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
11091                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
11092
11093                 "     %up_f16 = OpTypePointer Uniform %f16\n"
11094                 "     %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
11095                 "   %SSBO_DST = OpTypeStruct %ra_f16\n"
11096                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
11097
11098                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
11099                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
11100                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
11101         );
11102
11103         const StringTemplate decoration
11104         (
11105                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
11106                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
11107                 "OpDecorate %SSBO_SRC BufferBlock\n"
11108                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11109                 "OpDecorate %ssbo_src Binding 0\n"
11110
11111                 "OpDecorate %ra_u32 ArrayStride 4\n"
11112                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
11113                 "OpDecorate %SSBO_IDX BufferBlock\n"
11114                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
11115                 "OpDecorate %ssbo_idx Binding 1\n"
11116
11117                 "OpDecorate %ra_f16 ArrayStride 2\n"
11118                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
11119                 "OpDecorate %SSBO_DST BufferBlock\n"
11120                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11121                 "OpDecorate %ssbo_dst Binding 2\n"
11122         );
11123
11124         const StringTemplate testFun
11125         (
11126                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11127                 "    %param = OpFunctionParameter %v4f32\n"
11128                 "    %entry = OpLabel\n"
11129
11130                 "        %i = OpVariable %fp_i32 Function\n"
11131                 "             OpStore %i %c_i32_0\n"
11132
11133                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11134                 "             OpSelectionMerge %end_if None\n"
11135                 "             OpBranchConditional %will_run %run_test %end_if\n"
11136
11137                 " %run_test = OpLabel\n"
11138                 "             OpBranch %loop\n"
11139
11140                 "     %loop = OpLabel\n"
11141                 "    %i_cmp = OpLoad %i32 %i\n"
11142                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11143                 "             OpLoopMerge %merge %next None\n"
11144                 "             OpBranchConditional %lt %write %merge\n"
11145
11146                 "    %write = OpLabel\n"
11147                 "      %ndx = OpLoad %i32 %i\n"
11148
11149                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
11150                 "  %val_src = OpLoad %${tt} %src\n"
11151
11152                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
11153                 "  %val_idx = OpLoad %u32 %src_idx\n"
11154
11155                 "  %val_dst = OpVectorExtractDynamic %f16 %val_src %val_idx\n"
11156                 "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
11157
11158                 "             OpStore %dst %val_dst\n"
11159                 "             OpBranch %next\n"
11160
11161                 "     %next = OpLabel\n"
11162                 "    %i_cur = OpLoad %i32 %i\n"
11163                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11164                 "             OpStore %i %i_new\n"
11165                 "             OpBranch %loop\n"
11166
11167                 "    %merge = OpLabel\n"
11168                 "             OpBranch %end_if\n"
11169                 "   %end_if = OpLabel\n"
11170                 "             OpReturnValue %param\n"
11171
11172                 "             OpFunctionEnd\n"
11173         );
11174
11175         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
11176         {
11177                 const TestType&         testType                = testTypes[testTypeIdx];
11178                 const string            testName                = testType.typeName;
11179                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
11180                 const size_t            iterations              = float16InputData.size() / itemsPerType;
11181                 SpecResource            specResource;
11182                 map<string, string>     specs;
11183                 VulkanFeatures          features;
11184                 vector<deUint32>        inputDataNdx;
11185                 map<string, string>     fragments;
11186                 vector<string>          extensions;
11187
11188                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
11189                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
11190
11191                 specs["num_data_points"]        = de::toString(iterations);
11192                 specs["tt"]                                     = testType.typeName;
11193                 specs["tt_stride"]                      = de::toString(testType.typeStride);
11194                 specs["type_decl"]                      = testType.typeDecls;
11195
11196                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11197                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11198                 fragments["decoration"]         = decoration.specialize(specs);
11199                 fragments["pre_main"]           = preMain.specialize(specs);
11200                 fragments["testfun"]            = testFun.specialize(specs);
11201
11202                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11203                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11204                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11205                 specResource.verifyIO = compareFP16VectorExtractFunc;
11206
11207                 extensions.push_back("VK_KHR_16bit_storage");
11208                 extensions.push_back("VK_KHR_shader_float16_int8");
11209
11210                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11211                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11212
11213                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11214         }
11215
11216         return testGroup.release();
11217 }
11218
11219 template<deUint32 COMPONENTS_COUNT, deUint32 REPLACEMENT>
11220 bool compareFP16VectorInsertFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11221 {
11222         if (inputs.size() != 2 || outputAllocs.size() != 1)
11223                 return false;
11224
11225         vector<deUint8> input1Bytes;
11226         vector<deUint8> input2Bytes;
11227
11228         inputs[0].getBytes(input1Bytes);
11229         inputs[1].getBytes(input2Bytes);
11230
11231         DE_ASSERT(input1Bytes.size() > 0);
11232         DE_ASSERT(input2Bytes.size() > 0);
11233         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
11234
11235         const size_t                    iterations                      = input2Bytes.size() / sizeof(deUint32);
11236         const size_t                    componentsStride        = input1Bytes.size() / (sizeof(deFloat16) * iterations);
11237         const deFloat16* const  input1AsFP16            = (const deFloat16*)&input1Bytes[0];
11238         const deUint32* const   inputIndices            = (const deUint32*)&input2Bytes[0];
11239         const deFloat16* const  outputAsFP16            = (const deFloat16*)outputAllocs[0]->getHostPtr();
11240         const deFloat16                 magic                           = tcu::Float16(float(REPLACEMENT)).bits();
11241         std::string                             error;
11242
11243         DE_ASSERT(componentsStride == 2 || componentsStride == 4);
11244         DE_ASSERT(input1Bytes.size() == iterations * componentsStride * sizeof(deFloat16));
11245
11246         for (size_t idx = 0; idx < iterations; ++idx)
11247         {
11248                 const deFloat16*        inputVec                = &input1AsFP16[componentsStride * idx];
11249                 const deFloat16*        outputVec               = &outputAsFP16[componentsStride * idx];
11250                 const deUint32          replacedCompNdx = inputIndices[idx];
11251
11252                 DE_ASSERT(replacedCompNdx < COMPONENTS_COUNT);
11253
11254                 for (size_t compNdx = 0; compNdx < COMPONENTS_COUNT; ++compNdx)
11255                 {
11256                         const deFloat16 expected        = (compNdx == replacedCompNdx) ? magic : inputVec[compNdx];
11257
11258                         if (!compare16BitFloat(expected, outputVec[compNdx], error))
11259                         {
11260                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11261
11262                                 return false;
11263                         }
11264                 }
11265         }
11266
11267         return true;
11268 }
11269
11270 template<class SpecResource>
11271 tcu::TestCaseGroup* createFloat16VectorInsertSet (tcu::TestContext& testCtx)
11272 {
11273         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorinsertdynamic", "OpVectorInsertDynamic tests"));
11274
11275         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
11276         const deUint32                                          replacement                     = 42;
11277         const deUint32                                          numDataPoints           = 256;
11278         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
11279         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
11280
11281         struct TestType
11282         {
11283                 const deUint32  typeComponents;
11284                 const size_t    typeStride;
11285                 const char*             typeName;
11286                 const char*             typeDecls;
11287                 VerifyIOFunc    verifyIOFunc;
11288         };
11289
11290         const TestType  testTypes[]     =
11291         {
11292                 {
11293                         2,
11294                         2 * sizeof(deFloat16),
11295                         "v2f16",
11296                         "      %v2f16 = OpTypeVector %f16 2\n",
11297                         compareFP16VectorInsertFunc<2, replacement>
11298                 },
11299                 {
11300                         3,
11301                         4 * sizeof(deFloat16),
11302                         "v3f16",
11303                         "      %v3f16 = OpTypeVector %f16 3\n",
11304                         compareFP16VectorInsertFunc<3, replacement>
11305                 },
11306                 {
11307                         4,
11308                         4 * sizeof(deFloat16),
11309                         "v4f16",
11310                         "      %v4f16 = OpTypeVector %f16 4\n",
11311                         compareFP16VectorInsertFunc<4, replacement>
11312                 },
11313         };
11314
11315         const StringTemplate preMain
11316         (
11317                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11318                 "        %f16 = OpTypeFloat 16\n"
11319                 "  %c_f16_ins = OpConstant %f16 ${replacement}\n"
11320
11321                 "${type_decl}"
11322
11323                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
11324                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
11325                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
11326                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
11327
11328                 "     %up_u32 = OpTypePointer Uniform %u32\n"
11329                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
11330                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
11331                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
11332
11333                 "   %SSBO_DST = OpTypeStruct %ra_${tt}\n"
11334                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
11335
11336                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
11337                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
11338                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
11339         );
11340
11341         const StringTemplate decoration
11342         (
11343                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
11344                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
11345                 "OpDecorate %SSBO_SRC BufferBlock\n"
11346                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11347                 "OpDecorate %ssbo_src Binding 0\n"
11348
11349                 "OpDecorate %ra_u32 ArrayStride 4\n"
11350                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
11351                 "OpDecorate %SSBO_IDX BufferBlock\n"
11352                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
11353                 "OpDecorate %ssbo_idx Binding 1\n"
11354
11355                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
11356                 "OpDecorate %SSBO_DST BufferBlock\n"
11357                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11358                 "OpDecorate %ssbo_dst Binding 2\n"
11359         );
11360
11361         const StringTemplate testFun
11362         (
11363                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11364                 "    %param = OpFunctionParameter %v4f32\n"
11365                 "    %entry = OpLabel\n"
11366
11367                 "        %i = OpVariable %fp_i32 Function\n"
11368                 "             OpStore %i %c_i32_0\n"
11369
11370                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11371                 "             OpSelectionMerge %end_if None\n"
11372                 "             OpBranchConditional %will_run %run_test %end_if\n"
11373
11374                 " %run_test = OpLabel\n"
11375                 "             OpBranch %loop\n"
11376
11377                 "     %loop = OpLabel\n"
11378                 "    %i_cmp = OpLoad %i32 %i\n"
11379                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11380                 "             OpLoopMerge %merge %next None\n"
11381                 "             OpBranchConditional %lt %write %merge\n"
11382
11383                 "    %write = OpLabel\n"
11384                 "      %ndx = OpLoad %i32 %i\n"
11385
11386                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
11387                 "  %val_src = OpLoad %${tt} %src\n"
11388
11389                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
11390                 "  %val_idx = OpLoad %u32 %src_idx\n"
11391
11392                 "  %val_dst = OpVectorInsertDynamic %${tt} %val_src %c_f16_ins %val_idx\n"
11393                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
11394
11395                 "             OpStore %dst %val_dst\n"
11396                 "             OpBranch %next\n"
11397
11398                 "     %next = OpLabel\n"
11399                 "    %i_cur = OpLoad %i32 %i\n"
11400                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11401                 "             OpStore %i %i_new\n"
11402                 "             OpBranch %loop\n"
11403
11404                 "    %merge = OpLabel\n"
11405                 "             OpBranch %end_if\n"
11406                 "   %end_if = OpLabel\n"
11407                 "             OpReturnValue %param\n"
11408
11409                 "             OpFunctionEnd\n"
11410         );
11411
11412         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
11413         {
11414                 const TestType&         testType                = testTypes[testTypeIdx];
11415                 const string            testName                = testType.typeName;
11416                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
11417                 const size_t            iterations              = float16InputData.size() / itemsPerType;
11418                 SpecResource            specResource;
11419                 map<string, string>     specs;
11420                 VulkanFeatures          features;
11421                 vector<deUint32>        inputDataNdx;
11422                 map<string, string>     fragments;
11423                 vector<string>          extensions;
11424
11425                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
11426                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
11427
11428                 specs["num_data_points"]        = de::toString(iterations);
11429                 specs["tt"]                                     = testType.typeName;
11430                 specs["tt_stride"]                      = de::toString(testType.typeStride);
11431                 specs["type_decl"]                      = testType.typeDecls;
11432                 specs["replacement"]            = de::toString(replacement);
11433
11434                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11435                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11436                 fragments["decoration"]         = decoration.specialize(specs);
11437                 fragments["pre_main"]           = preMain.specialize(specs);
11438                 fragments["testfun"]            = testFun.specialize(specs);
11439
11440                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11441                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11442                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11443                 specResource.verifyIO = testType.verifyIOFunc;
11444
11445                 extensions.push_back("VK_KHR_16bit_storage");
11446                 extensions.push_back("VK_KHR_shader_float16_int8");
11447
11448                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11449                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11450
11451                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11452         }
11453
11454         return testGroup.release();
11455 }
11456
11457 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)
11458 {
11459         const size_t    compNdxCount    = (vec1Len + vec2Len + 1);
11460         const size_t    compNdxLimited  = iteration % (compNdxCount * compNdxCount);
11461         size_t                  comp;
11462
11463         switch (componentNdx)
11464         {
11465                 case 0: comp = compNdxLimited / compNdxCount; break;
11466                 case 1: comp = compNdxLimited % compNdxCount; break;
11467                 case 2: comp = 0; break;
11468                 case 3: comp = 1; break;
11469                 default: TCU_THROW(InternalError, "Impossible");
11470         }
11471
11472         if (comp >= vec1Len + vec2Len)
11473         {
11474                 validate = false;
11475                 return 0;
11476         }
11477         else
11478         {
11479                 validate = true;
11480                 return (comp < vec1Len) ? input1Vec[comp] : input2Vec[comp - vec1Len];
11481         }
11482 }
11483
11484 template<deUint32 DST_COMPONENTS_COUNT, deUint32 SRC0_COMPONENTS_COUNT, deUint32 SRC1_COMPONENTS_COUNT>
11485 bool compareFP16VectorShuffleFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11486 {
11487         DE_STATIC_ASSERT(DST_COMPONENTS_COUNT == 2 || DST_COMPONENTS_COUNT == 3 || DST_COMPONENTS_COUNT == 4);
11488         DE_STATIC_ASSERT(SRC0_COMPONENTS_COUNT == 2 || SRC0_COMPONENTS_COUNT == 3 || SRC0_COMPONENTS_COUNT == 4);
11489         DE_STATIC_ASSERT(SRC1_COMPONENTS_COUNT == 2 || SRC1_COMPONENTS_COUNT == 3 || SRC1_COMPONENTS_COUNT == 4);
11490
11491         if (inputs.size() != 2 || outputAllocs.size() != 1)
11492                 return false;
11493
11494         vector<deUint8> input1Bytes;
11495         vector<deUint8> input2Bytes;
11496
11497         inputs[0].getBytes(input1Bytes);
11498         inputs[1].getBytes(input2Bytes);
11499
11500         DE_ASSERT(input1Bytes.size() > 0);
11501         DE_ASSERT(input2Bytes.size() > 0);
11502         DE_ASSERT(input2Bytes.size() % sizeof(deFloat16) == 0);
11503
11504         const size_t                    componentsStrideDst             = (DST_COMPONENTS_COUNT == 3) ? 4 : DST_COMPONENTS_COUNT;
11505         const size_t                    componentsStrideSrc0    = (SRC0_COMPONENTS_COUNT == 3) ? 4 : SRC0_COMPONENTS_COUNT;
11506         const size_t                    componentsStrideSrc1    = (SRC1_COMPONENTS_COUNT == 3) ? 4 : SRC1_COMPONENTS_COUNT;
11507         const size_t                    iterations                              = input1Bytes.size() / (componentsStrideSrc0 * sizeof(deFloat16));
11508         const deFloat16* const  input1AsFP16                    = (const deFloat16*)&input1Bytes[0];
11509         const deFloat16* const  input2AsFP16                    = (const deFloat16*)&input2Bytes[0];
11510         const deFloat16* const  outputAsFP16                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11511         std::string                             error;
11512
11513         DE_ASSERT(input1Bytes.size() == iterations * componentsStrideSrc0 * sizeof(deFloat16));
11514         DE_ASSERT(input2Bytes.size() == iterations * componentsStrideSrc1 * sizeof(deFloat16));
11515
11516         for (size_t idx = 0; idx < iterations; ++idx)
11517         {
11518                 const deFloat16*        input1Vec       = &input1AsFP16[componentsStrideSrc0 * idx];
11519                 const deFloat16*        input2Vec       = &input2AsFP16[componentsStrideSrc1 * idx];
11520                 const deFloat16*        outputVec       = &outputAsFP16[componentsStrideDst * idx];
11521
11522                 for (size_t compNdx = 0; compNdx < DST_COMPONENTS_COUNT; ++compNdx)
11523                 {
11524                         bool            validate        = true;
11525                         deFloat16       expected        = getShuffledComponent(idx, compNdx, input1Vec, input2Vec, SRC0_COMPONENTS_COUNT, SRC1_COMPONENTS_COUNT, validate);
11526
11527                         if (validate && !compare16BitFloat(expected, outputVec[compNdx], error))
11528                         {
11529                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11530
11531                                 return false;
11532                         }
11533                 }
11534         }
11535
11536         return true;
11537 }
11538
11539 VerifyIOFunc getFloat16VectorShuffleVerifyIOFunc (deUint32 dstComponentsCount, deUint32 src0ComponentsCount, deUint32 src1ComponentsCount)
11540 {
11541         DE_ASSERT(dstComponentsCount <= 4);
11542         DE_ASSERT(src0ComponentsCount <= 4);
11543         DE_ASSERT(src1ComponentsCount <= 4);
11544         deUint32 funcCode = 100 * dstComponentsCount + 10 * src0ComponentsCount + src1ComponentsCount;
11545
11546         switch (funcCode)
11547         {
11548                 case 222:return compareFP16VectorShuffleFunc<2, 2, 2>;
11549                 case 223:return compareFP16VectorShuffleFunc<2, 2, 3>;
11550                 case 224:return compareFP16VectorShuffleFunc<2, 2, 4>;
11551                 case 232:return compareFP16VectorShuffleFunc<2, 3, 2>;
11552                 case 233:return compareFP16VectorShuffleFunc<2, 3, 3>;
11553                 case 234:return compareFP16VectorShuffleFunc<2, 3, 4>;
11554                 case 242:return compareFP16VectorShuffleFunc<2, 4, 2>;
11555                 case 243:return compareFP16VectorShuffleFunc<2, 4, 3>;
11556                 case 244:return compareFP16VectorShuffleFunc<2, 4, 4>;
11557                 case 322:return compareFP16VectorShuffleFunc<3, 2, 2>;
11558                 case 323:return compareFP16VectorShuffleFunc<3, 2, 3>;
11559                 case 324:return compareFP16VectorShuffleFunc<3, 2, 4>;
11560                 case 332:return compareFP16VectorShuffleFunc<3, 3, 2>;
11561                 case 333:return compareFP16VectorShuffleFunc<3, 3, 3>;
11562                 case 334:return compareFP16VectorShuffleFunc<3, 3, 4>;
11563                 case 342:return compareFP16VectorShuffleFunc<3, 4, 2>;
11564                 case 343:return compareFP16VectorShuffleFunc<3, 4, 3>;
11565                 case 344:return compareFP16VectorShuffleFunc<3, 4, 4>;
11566                 case 422:return compareFP16VectorShuffleFunc<4, 2, 2>;
11567                 case 423:return compareFP16VectorShuffleFunc<4, 2, 3>;
11568                 case 424:return compareFP16VectorShuffleFunc<4, 2, 4>;
11569                 case 432:return compareFP16VectorShuffleFunc<4, 3, 2>;
11570                 case 433:return compareFP16VectorShuffleFunc<4, 3, 3>;
11571                 case 434:return compareFP16VectorShuffleFunc<4, 3, 4>;
11572                 case 442:return compareFP16VectorShuffleFunc<4, 4, 2>;
11573                 case 443:return compareFP16VectorShuffleFunc<4, 4, 3>;
11574                 case 444:return compareFP16VectorShuffleFunc<4, 4, 4>;
11575                 default: TCU_THROW(InternalError, "Invalid number of components specified.");
11576         }
11577 }
11578
11579 template<class SpecResource>
11580 tcu::TestCaseGroup* createFloat16VectorShuffleSet (tcu::TestContext& testCtx)
11581 {
11582         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorshuffle", "OpVectorShuffle tests"));
11583         const int                                                       testSpecificSeed        = deStringHash(testGroup->getName());
11584         const int                                                       seed                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
11585         de::Random                                                      rnd                                     (seed);
11586         const deUint32                                          numDataPoints           = 128;
11587         map<string, string>                                     fragments;
11588
11589         struct TestType
11590         {
11591                 const deUint32  typeComponents;
11592                 const char*             typeName;
11593         };
11594
11595         const TestType  testTypes[]     =
11596         {
11597                 {
11598                         2,
11599                         "v2f16",
11600                 },
11601                 {
11602                         3,
11603                         "v3f16",
11604                 },
11605                 {
11606                         4,
11607                         "v4f16",
11608                 },
11609         };
11610
11611         const StringTemplate preMain
11612         (
11613                 "    %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11614                 "     %c_i32_cc = OpConstant %i32 ${case_count}\n"
11615                 "          %f16 = OpTypeFloat 16\n"
11616                 "        %v2f16 = OpTypeVector %f16 2\n"
11617                 "        %v3f16 = OpTypeVector %f16 3\n"
11618                 "        %v4f16 = OpTypeVector %f16 4\n"
11619
11620                 "     %up_v2f16 = OpTypePointer Uniform %v2f16\n"
11621                 "     %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
11622                 "   %SSBO_v2f16 = OpTypeStruct %ra_v2f16\n"
11623                 "%up_SSBO_v2f16 = OpTypePointer Uniform %SSBO_v2f16\n"
11624
11625                 "     %up_v3f16 = OpTypePointer Uniform %v3f16\n"
11626                 "     %ra_v3f16 = OpTypeArray %v3f16 %c_i32_ndp\n"
11627                 "   %SSBO_v3f16 = OpTypeStruct %ra_v3f16\n"
11628                 "%up_SSBO_v3f16 = OpTypePointer Uniform %SSBO_v3f16\n"
11629
11630                 "     %up_v4f16 = OpTypePointer Uniform %v4f16\n"
11631                 "     %ra_v4f16 = OpTypeArray %v4f16 %c_i32_ndp\n"
11632                 "   %SSBO_v4f16 = OpTypeStruct %ra_v4f16\n"
11633                 "%up_SSBO_v4f16 = OpTypePointer Uniform %SSBO_v4f16\n"
11634
11635                 "        %fun_t = OpTypeFunction %${tt_dst} %${tt_src0} %${tt_src1} %i32\n"
11636
11637                 "    %ssbo_src0 = OpVariable %up_SSBO_${tt_src0} Uniform\n"
11638                 "    %ssbo_src1 = OpVariable %up_SSBO_${tt_src1} Uniform\n"
11639                 "     %ssbo_dst = OpVariable %up_SSBO_${tt_dst} Uniform\n"
11640         );
11641
11642         const StringTemplate decoration
11643         (
11644                 "OpDecorate %ra_v2f16 ArrayStride 4\n"
11645                 "OpDecorate %ra_v3f16 ArrayStride 8\n"
11646                 "OpDecorate %ra_v4f16 ArrayStride 8\n"
11647
11648                 "OpMemberDecorate %SSBO_v2f16 0 Offset 0\n"
11649                 "OpDecorate %SSBO_v2f16 BufferBlock\n"
11650
11651                 "OpMemberDecorate %SSBO_v3f16 0 Offset 0\n"
11652                 "OpDecorate %SSBO_v3f16 BufferBlock\n"
11653
11654                 "OpMemberDecorate %SSBO_v4f16 0 Offset 0\n"
11655                 "OpDecorate %SSBO_v4f16 BufferBlock\n"
11656
11657                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
11658                 "OpDecorate %ssbo_src0 Binding 0\n"
11659                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
11660                 "OpDecorate %ssbo_src1 Binding 1\n"
11661                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11662                 "OpDecorate %ssbo_dst Binding 2\n"
11663         );
11664
11665         const StringTemplate testFun
11666         (
11667                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11668                 "    %param = OpFunctionParameter %v4f32\n"
11669                 "    %entry = OpLabel\n"
11670
11671                 "        %i = OpVariable %fp_i32 Function\n"
11672                 "             OpStore %i %c_i32_0\n"
11673
11674                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11675                 "             OpSelectionMerge %end_if None\n"
11676                 "             OpBranchConditional %will_run %run_test %end_if\n"
11677
11678                 " %run_test = OpLabel\n"
11679                 "             OpBranch %loop\n"
11680
11681                 "     %loop = OpLabel\n"
11682                 "    %i_cmp = OpLoad %i32 %i\n"
11683                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11684                 "             OpLoopMerge %merge %next None\n"
11685                 "             OpBranchConditional %lt %write %merge\n"
11686
11687                 "    %write = OpLabel\n"
11688                 "      %ndx = OpLoad %i32 %i\n"
11689                 "     %src0 = OpAccessChain %up_${tt_src0} %ssbo_src0 %c_i32_0 %ndx\n"
11690                 " %val_src0 = OpLoad %${tt_src0} %src0\n"
11691                 "     %src1 = OpAccessChain %up_${tt_src1} %ssbo_src1 %c_i32_0 %ndx\n"
11692                 " %val_src1 = OpLoad %${tt_src1} %src1\n"
11693                 "  %val_dst = OpFunctionCall %${tt_dst} %sw_fun %val_src0 %val_src1 %ndx\n"
11694                 "      %dst = OpAccessChain %up_${tt_dst} %ssbo_dst %c_i32_0 %ndx\n"
11695                 "             OpStore %dst %val_dst\n"
11696                 "             OpBranch %next\n"
11697
11698                 "     %next = OpLabel\n"
11699                 "    %i_cur = OpLoad %i32 %i\n"
11700                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11701                 "             OpStore %i %i_new\n"
11702                 "             OpBranch %loop\n"
11703
11704                 "    %merge = OpLabel\n"
11705                 "             OpBranch %end_if\n"
11706                 "   %end_if = OpLabel\n"
11707                 "             OpReturnValue %param\n"
11708                 "             OpFunctionEnd\n"
11709                 "\n"
11710
11711                 "   %sw_fun = OpFunction %${tt_dst} None %fun_t\n"
11712                 "%sw_param0 = OpFunctionParameter %${tt_src0}\n"
11713                 "%sw_param1 = OpFunctionParameter %${tt_src1}\n"
11714                 "%sw_paramn = OpFunctionParameter %i32\n"
11715                 " %sw_entry = OpLabel\n"
11716                 "   %modulo = OpSMod %i32 %sw_paramn %c_i32_cc\n"
11717                 "             OpSelectionMerge %switch_e None\n"
11718                 "             OpSwitch %modulo %default ${case_list}\n"
11719                 "${case_bodies}"
11720                 "%default   = OpLabel\n"
11721                 "             OpUnreachable\n" // Unreachable default case for switch statement
11722                 "%switch_e  = OpLabel\n"
11723                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11724                 "             OpFunctionEnd\n"
11725         );
11726
11727         const StringTemplate testCaseBody
11728         (
11729                 "%case_${case_ndx}    = OpLabel\n"
11730                 "%val_dst_${case_ndx} = OpVectorShuffle %${tt_dst} %sw_param0 %sw_param1 ${shuffle}\n"
11731                 "             OpReturnValue %val_dst_${case_ndx}\n"
11732         );
11733
11734         for (deUint32 dstTypeIdx = 0; dstTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++dstTypeIdx)
11735         {
11736                 const TestType& dstType                 = testTypes[dstTypeIdx];
11737
11738                 for (deUint32 comp0Idx = 0; comp0Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp0Idx)
11739                 {
11740                         const TestType& src0Type        = testTypes[comp0Idx];
11741
11742                         for (deUint32 comp1Idx = 0; comp1Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp1Idx)
11743                         {
11744                                 const TestType&                 src1Type                        = testTypes[comp1Idx];
11745                                 const deUint32                  input0Stride            = (src0Type.typeComponents == 3) ? 4 : src0Type.typeComponents;
11746                                 const deUint32                  input1Stride            = (src1Type.typeComponents == 3) ? 4 : src1Type.typeComponents;
11747                                 const deUint32                  outputStride            = (dstType.typeComponents == 3) ? 4 : dstType.typeComponents;
11748                                 const vector<deFloat16> float16Input0Data       = getFloat16s(rnd, input0Stride * numDataPoints);
11749                                 const vector<deFloat16> float16Input1Data       = getFloat16s(rnd, input1Stride * numDataPoints);
11750                                 const vector<deFloat16> float16OutputDummy      (outputStride * numDataPoints, 0);
11751                                 const string                    testName                        = de::toString(dstType.typeComponents) + de::toString(src0Type.typeComponents) + de::toString(src1Type.typeComponents);
11752                                 deUint32                                caseCount                       = 0;
11753                                 SpecResource                    specResource;
11754                                 map<string, string>             specs;
11755                                 vector<string>                  extensions;
11756                                 VulkanFeatures                  features;
11757                                 string                                  caseBodies;
11758                                 string                                  caseList;
11759
11760                                 // Generate case
11761                                 {
11762                                         vector<string>  componentList;
11763
11764                                         // Generate component possible indices for OpVectorShuffle for components 0 and 1 in output vector
11765                                         {
11766                                                 deUint32                caseNo          = 0;
11767
11768                                                 for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < src0Type.typeComponents; ++comp0IdxLocal)
11769                                                         componentList.push_back(de::toString(caseNo++));
11770                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < src1Type.typeComponents; ++comp1IdxLocal)
11771                                                         componentList.push_back(de::toString(caseNo++));
11772                                                 componentList.push_back("0xFFFFFFFF");
11773                                         }
11774
11775                                         for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < componentList.size(); ++comp0IdxLocal)
11776                                         {
11777                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < componentList.size(); ++comp1IdxLocal)
11778                                                 {
11779                                                         map<string, string>     specCase;
11780                                                         string                          shuffle         = componentList[comp0IdxLocal] + " " + componentList[comp1IdxLocal];
11781
11782                                                         for (deUint32 compIdx = 2; compIdx < dstType.typeComponents; ++compIdx)
11783                                                                 shuffle += " " + de::toString(compIdx - 2);
11784
11785                                                         specCase["case_ndx"]    = de::toString(caseCount);
11786                                                         specCase["shuffle"]             = shuffle;
11787                                                         specCase["tt_dst"]              = dstType.typeName;
11788
11789                                                         caseBodies      += testCaseBody.specialize(specCase);
11790                                                         caseList        += de::toString(caseCount) + " %case_" + de::toString(caseCount) + " ";
11791
11792                                                         caseCount++;
11793                                                 }
11794                                         }
11795                                 }
11796
11797                                 specs["num_data_points"]        = de::toString(numDataPoints);
11798                                 specs["tt_dst"]                         = dstType.typeName;
11799                                 specs["tt_src0"]                        = src0Type.typeName;
11800                                 specs["tt_src1"]                        = src1Type.typeName;
11801                                 specs["case_bodies"]            = caseBodies;
11802                                 specs["case_list"]                      = caseList;
11803                                 specs["case_count"]                     = de::toString(caseCount);
11804
11805                                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11806                                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11807                                 fragments["decoration"]         = decoration.specialize(specs);
11808                                 fragments["pre_main"]           = preMain.specialize(specs);
11809                                 fragments["testfun"]            = testFun.specialize(specs);
11810
11811                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input0Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11812                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input1Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11813                                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11814                                 specResource.verifyIO = getFloat16VectorShuffleVerifyIOFunc(dstType.typeComponents, src0Type.typeComponents, src1Type.typeComponents);
11815
11816                                 extensions.push_back("VK_KHR_16bit_storage");
11817                                 extensions.push_back("VK_KHR_shader_float16_int8");
11818
11819                                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11820                                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11821
11822                                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11823                         }
11824                 }
11825         }
11826
11827         return testGroup.release();
11828 }
11829
11830 bool compareFP16CompositeFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11831 {
11832         if (inputs.size() != 1 || outputAllocs.size() != 1)
11833                 return false;
11834
11835         vector<deUint8> input1Bytes;
11836
11837         inputs[0].getBytes(input1Bytes);
11838
11839         DE_ASSERT(input1Bytes.size() > 0);
11840         DE_ASSERT(input1Bytes.size() % sizeof(deFloat16) == 0);
11841
11842         const size_t                    iterations              = input1Bytes.size() / sizeof(deFloat16);
11843         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
11844         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11845         const deFloat16                 exceptionValue  = tcu::Float16(-1.0).bits();
11846         std::string                             error;
11847
11848         for (size_t idx = 0; idx < iterations; ++idx)
11849         {
11850                 if (input1AsFP16[idx] == exceptionValue)
11851                         continue;
11852
11853                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
11854                 {
11855                         log << TestLog::Message << "At " << idx << ":" << error << TestLog::EndMessage;
11856
11857                         return false;
11858                 }
11859         }
11860
11861         return true;
11862 }
11863
11864 template<class SpecResource>
11865 tcu::TestCaseGroup* createFloat16CompositeConstructSet (tcu::TestContext& testCtx)
11866 {
11867         de::MovePtr<tcu::TestCaseGroup>         testGroup                               (new tcu::TestCaseGroup(testCtx, "opcompositeconstruct", "OpCompositeConstruct tests"));
11868         const deUint32                                          numElements                             = 8;
11869         const string                                            testName                                = "struct";
11870         const deUint32                                          structItemsCount                = 88;
11871         const deUint32                                          exceptionIndices[]              = { 1, 7, 15, 17, 25, 33, 51, 55, 59, 63, 67, 71, 84, 85, 86, 87 };
11872         const deFloat16                                         exceptionValue                  = tcu::Float16(-1.0).bits();
11873         const deUint32                                          fieldModifier                   = 2;
11874         const deUint32                                          fieldModifiedMulIndex   = 60;
11875         const deUint32                                          fieldModifiedAddIndex   = 66;
11876
11877         const StringTemplate preMain
11878         (
11879                 "    %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11880                 "          %f16 = OpTypeFloat 16\n"
11881                 "        %v2f16 = OpTypeVector %f16 2\n"
11882                 "        %v3f16 = OpTypeVector %f16 3\n"
11883                 "        %v4f16 = OpTypeVector %f16 4\n"
11884                 "    %c_f16_mod = OpConstant %f16 ${field_modifier}\n"
11885
11886                 "${consts}"
11887
11888                 "      %c_u32_5 = OpConstant %u32 5\n"
11889
11890                 " %f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11891                 " %v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11892                 " %v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11893                 " %v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11894                 " %v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11895                 " %struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11896                 " %struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11897                 " %st_test      = OpTypeStruct %f16 %v2f16 %v3f16 %v4f16 %f16arr3 %struct16arr3 %v2f16arr5 %f16 %v3f16arr5 %v4f16arr3\n"
11898
11899                 "        %up_st = OpTypePointer Uniform %st_test\n"
11900                 "        %ra_st = OpTypeArray %st_test %c_i32_ndp\n"
11901                 "      %SSBO_st = OpTypeStruct %ra_st\n"
11902                 "   %up_SSBO_st = OpTypePointer Uniform %SSBO_st\n"
11903
11904                 "     %ssbo_dst = OpVariable %up_SSBO_st Uniform\n"
11905         );
11906
11907         const StringTemplate decoration
11908         (
11909                 "OpDecorate %SSBO_st BufferBlock\n"
11910                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11911                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11912                 "OpDecorate %ssbo_dst Binding 1\n"
11913
11914                 "OpMemberDecorate %SSBO_st 0 Offset 0\n"
11915
11916                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11917                 "OpMemberDecorate %struct16 0 Offset 0\n"
11918                 "OpMemberDecorate %struct16 1 Offset 4\n"
11919                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11920                 "OpDecorate %f16arr3 ArrayStride 2\n"
11921                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11922                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11923                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11924
11925                 "OpMemberDecorate %st_test 0 Offset 0\n"
11926                 "OpMemberDecorate %st_test 1 Offset 4\n"
11927                 "OpMemberDecorate %st_test 2 Offset 8\n"
11928                 "OpMemberDecorate %st_test 3 Offset 16\n"
11929                 "OpMemberDecorate %st_test 4 Offset 24\n"
11930                 "OpMemberDecorate %st_test 5 Offset 32\n"
11931                 "OpMemberDecorate %st_test 6 Offset 80\n"
11932                 "OpMemberDecorate %st_test 7 Offset 100\n"
11933                 "OpMemberDecorate %st_test 8 Offset 104\n"
11934                 "OpMemberDecorate %st_test 9 Offset 144\n"
11935         );
11936
11937         const StringTemplate testFun
11938         (
11939                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11940                 "     %param = OpFunctionParameter %v4f32\n"
11941                 "     %entry = OpLabel\n"
11942
11943                 "         %i = OpVariable %fp_i32 Function\n"
11944                 "              OpStore %i %c_i32_0\n"
11945
11946                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11947                 "              OpSelectionMerge %end_if None\n"
11948                 "              OpBranchConditional %will_run %run_test %end_if\n"
11949
11950                 "  %run_test = OpLabel\n"
11951                 "              OpBranch %loop\n"
11952
11953                 "      %loop = OpLabel\n"
11954                 "     %i_cmp = OpLoad %i32 %i\n"
11955                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11956                 "              OpLoopMerge %merge %next None\n"
11957                 "              OpBranchConditional %lt %write %merge\n"
11958
11959                 "     %write = OpLabel\n"
11960                 "       %ndx = OpLoad %i32 %i\n"
11961
11962                 "      %fld1 = OpCompositeConstruct %v2f16 %c_f16_2 %c_f16_3\n"
11963                 "      %fld2 = OpCompositeConstruct %v3f16 %c_f16_4 %c_f16_5 %c_f16_6\n"
11964                 "      %fld3 = OpCompositeConstruct %v4f16 %c_f16_8 %c_f16_9 %c_f16_10 %c_f16_11\n"
11965
11966                 "      %fld4 = OpCompositeConstruct %f16arr3 %c_f16_12 %c_f16_13 %c_f16_14\n"
11967
11968                 "%fld5_0_1_0 = OpCompositeConstruct %v2f16 %c_f16_18 %c_f16_19\n"
11969                 "%fld5_0_1_1 = OpCompositeConstruct %v2f16 %c_f16_20 %c_f16_21\n"
11970                 "%fld5_0_1_2 = OpCompositeConstruct %v2f16 %c_f16_22 %c_f16_23\n"
11971                 "  %fld5_0_1 = OpCompositeConstruct %v2f16arr3 %fld5_0_1_0 %fld5_0_1_1 %fld5_0_1_2\n"
11972                 "    %fld5_0 = OpCompositeConstruct %struct16 %c_f16_16 %fld5_0_1\n"
11973
11974                 "%fld5_1_1_0 = OpCompositeConstruct %v2f16 %c_f16_26 %c_f16_27\n"
11975                 "%fld5_1_1_1 = OpCompositeConstruct %v2f16 %c_f16_28 %c_f16_29\n"
11976                 "%fld5_1_1_2 = OpCompositeConstruct %v2f16 %c_f16_30 %c_f16_31\n"
11977                 "  %fld5_1_1 = OpCompositeConstruct %v2f16arr3 %fld5_1_1_0 %fld5_1_1_1 %fld5_1_1_2\n"
11978                 "    %fld5_1 = OpCompositeConstruct %struct16 %c_f16_24 %fld5_1_1\n"
11979
11980                 "%fld5_2_1_0 = OpCompositeConstruct %v2f16 %c_f16_34 %c_f16_35\n"
11981                 "%fld5_2_1_1 = OpCompositeConstruct %v2f16 %c_f16_36 %c_f16_37\n"
11982                 "%fld5_2_1_2 = OpCompositeConstruct %v2f16 %c_f16_38 %c_f16_39\n"
11983                 "  %fld5_2_1 = OpCompositeConstruct %v2f16arr3 %fld5_2_1_0 %fld5_2_1_1 %fld5_2_1_2\n"
11984                 "    %fld5_2 = OpCompositeConstruct %struct16 %c_f16_32 %fld5_2_1\n"
11985
11986                 "      %fld5 = OpCompositeConstruct %struct16arr3 %fld5_0 %fld5_1 %fld5_2\n"
11987
11988                 "    %fld6_0 = OpCompositeConstruct %v2f16 %c_f16_40 %c_f16_41\n"
11989                 "    %fld6_1 = OpCompositeConstruct %v2f16 %c_f16_42 %c_f16_43\n"
11990                 "    %fld6_2 = OpCompositeConstruct %v2f16 %c_f16_44 %c_f16_45\n"
11991                 "    %fld6_3 = OpCompositeConstruct %v2f16 %c_f16_46 %c_f16_47\n"
11992                 "    %fld6_4 = OpCompositeConstruct %v2f16 %c_f16_48 %c_f16_49\n"
11993                 "      %fld6 = OpCompositeConstruct %v2f16arr5 %fld6_0 %fld6_1 %fld6_2 %fld6_3 %fld6_4\n"
11994
11995                 "      %fndx = OpConvertSToF %f16 %ndx\n"
11996                 "  %fld8_2a0 = OpFMul %f16 %fndx %c_f16_mod\n"
11997                 "  %fld8_3b1 = OpFAdd %f16 %fndx %c_f16_mod\n"
11998
11999                 "   %fld8_2a = OpCompositeConstruct %v2f16 %fld8_2a0 %c_f16_61\n"
12000                 "   %fld8_3b = OpCompositeConstruct %v2f16 %c_f16_65 %fld8_3b1\n"
12001                 "    %fld8_0 = OpCompositeConstruct %v3f16 %c_f16_52 %c_f16_53 %c_f16_54\n"
12002                 "    %fld8_1 = OpCompositeConstruct %v3f16 %c_f16_56 %c_f16_57 %c_f16_58\n"
12003                 "    %fld8_2 = OpCompositeConstruct %v3f16 %fld8_2a %c_f16_62\n"
12004                 "    %fld8_3 = OpCompositeConstruct %v3f16 %c_f16_64 %fld8_3b\n"
12005                 "    %fld8_4 = OpCompositeConstruct %v3f16 %c_f16_68 %c_f16_69 %c_f16_70\n"
12006                 "      %fld8 = OpCompositeConstruct %v3f16arr5 %fld8_0 %fld8_1 %fld8_2 %fld8_3 %fld8_4\n"
12007
12008                 "    %fld9_0 = OpCompositeConstruct %v4f16 %c_f16_72 %c_f16_73 %c_f16_74 %c_f16_75\n"
12009                 "    %fld9_1 = OpCompositeConstruct %v4f16 %c_f16_76 %c_f16_77 %c_f16_78 %c_f16_79\n"
12010                 "    %fld9_2 = OpCompositeConstruct %v4f16 %c_f16_80 %c_f16_81 %c_f16_82 %c_f16_83\n"
12011                 "      %fld9 = OpCompositeConstruct %v4f16arr3 %fld9_0 %fld9_1 %fld9_2\n"
12012
12013                 "    %st_val = OpCompositeConstruct %st_test %c_f16_0 %fld1 %fld2 %fld3 %fld4 %fld5 %fld6 %c_f16_50 %fld8 %fld9\n"
12014                 "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %ndx\n"
12015                 "              OpStore %dst %st_val\n"
12016
12017                 "              OpBranch %next\n"
12018
12019                 "      %next = OpLabel\n"
12020                 "     %i_cur = OpLoad %i32 %i\n"
12021                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
12022                 "              OpStore %i %i_new\n"
12023                 "              OpBranch %loop\n"
12024
12025                 "     %merge = OpLabel\n"
12026                 "              OpBranch %end_if\n"
12027                 "    %end_if = OpLabel\n"
12028                 "              OpReturnValue %param\n"
12029                 "              OpFunctionEnd\n"
12030         );
12031
12032         {
12033                 SpecResource            specResource;
12034                 map<string, string>     specs;
12035                 VulkanFeatures          features;
12036                 map<string, string>     fragments;
12037                 vector<string>          extensions;
12038                 vector<deFloat16>       expectedOutput;
12039                 string                          consts;
12040
12041                 for (deUint32 elementNdx = 0; elementNdx < numElements; ++elementNdx)
12042                 {
12043                         vector<deFloat16>       expectedIterationOutput;
12044
12045                         for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
12046                                 expectedIterationOutput.push_back(tcu::Float16(float(structItemNdx)).bits());
12047
12048                         for (deUint32 structItemNdx = 0; structItemNdx < DE_LENGTH_OF_ARRAY(exceptionIndices); ++structItemNdx)
12049                                 expectedIterationOutput[exceptionIndices[structItemNdx]] = exceptionValue;
12050
12051                         expectedIterationOutput[fieldModifiedMulIndex] = tcu::Float16(float(elementNdx * fieldModifier)).bits();
12052                         expectedIterationOutput[fieldModifiedAddIndex] = tcu::Float16(float(elementNdx + fieldModifier)).bits();
12053
12054                         expectedOutput.insert(expectedOutput.end(), expectedIterationOutput.begin(), expectedIterationOutput.end());
12055                 }
12056
12057                 for (deUint32 i = 0; i < structItemsCount; ++i)
12058                         consts += "     %c_f16_" + de::toString(i) + " = OpConstant %f16 "  + de::toString(i) + "\n";
12059
12060                 specs["num_elements"]           = de::toString(numElements);
12061                 specs["struct_item_size"]       = de::toString(structItemsCount * sizeof(deFloat16));
12062                 specs["field_modifier"]         = de::toString(fieldModifier);
12063                 specs["consts"]                         = consts;
12064
12065                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
12066                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
12067                 fragments["decoration"]         = decoration.specialize(specs);
12068                 fragments["pre_main"]           = preMain.specialize(specs);
12069                 fragments["testfun"]            = testFun.specialize(specs);
12070
12071                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12072                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12073                 specResource.verifyIO = compareFP16CompositeFunc;
12074
12075                 extensions.push_back("VK_KHR_16bit_storage");
12076                 extensions.push_back("VK_KHR_shader_float16_int8");
12077
12078                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
12079                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
12080
12081                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
12082         }
12083
12084         return testGroup.release();
12085 }
12086
12087 template<class SpecResource>
12088 tcu::TestCaseGroup* createFloat16CompositeInsertExtractSet (tcu::TestContext& testCtx, const char* op)
12089 {
12090         de::MovePtr<tcu::TestCaseGroup>         testGroup               (new tcu::TestCaseGroup(testCtx, de::toLower(op).c_str(), op));
12091         const deFloat16                                         exceptionValue  = tcu::Float16(-1.0).bits();
12092         const string                                            opName                  (op);
12093         const deUint32                                          opIndex                 = (opName == "OpCompositeInsert") ? 0
12094                                                                                                                 : (opName == "OpCompositeExtract") ? 1
12095                                                                                                                 : -1;
12096
12097         const StringTemplate preMain
12098         (
12099                 "   %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
12100                 "         %f16 = OpTypeFloat 16\n"
12101                 "       %v2f16 = OpTypeVector %f16 2\n"
12102                 "       %v3f16 = OpTypeVector %f16 3\n"
12103                 "       %v4f16 = OpTypeVector %f16 4\n"
12104                 "    %c_f16_na = OpConstant %f16 -1.0\n"
12105                 "     %c_u32_5 = OpConstant %u32 5\n"
12106
12107                 "%f16arr3      = OpTypeArray %f16 %c_u32_3\n"
12108                 "%v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
12109                 "%v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
12110                 "%v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
12111                 "%v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
12112                 "%struct16     = OpTypeStruct %f16 %v2f16arr3\n"
12113                 "%struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
12114                 "%st_test      = OpTypeStruct %${field_type}\n"
12115
12116                 "      %up_f16 = OpTypePointer Uniform %f16\n"
12117                 "       %up_st = OpTypePointer Uniform %st_test\n"
12118                 "      %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
12119                 "       %ra_st = OpTypeArray %st_test %c_i32_1\n"
12120
12121                 "${op_premain_decls}"
12122
12123                 " %up_SSBO_src = OpTypePointer Uniform %SSBO_src\n"
12124                 " %up_SSBO_dst = OpTypePointer Uniform %SSBO_dst\n"
12125
12126                 "    %ssbo_src = OpVariable %up_SSBO_src Uniform\n"
12127                 "    %ssbo_dst = OpVariable %up_SSBO_dst Uniform\n"
12128         );
12129
12130         const StringTemplate decoration
12131         (
12132                 "OpDecorate %SSBO_src BufferBlock\n"
12133                 "OpDecorate %SSBO_dst BufferBlock\n"
12134                 "OpDecorate %ra_f16 ArrayStride 2\n"
12135                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
12136                 "OpDecorate %ssbo_src DescriptorSet 0\n"
12137                 "OpDecorate %ssbo_src Binding 0\n"
12138                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
12139                 "OpDecorate %ssbo_dst Binding 1\n"
12140
12141                 "OpMemberDecorate %SSBO_src 0 Offset 0\n"
12142                 "OpMemberDecorate %SSBO_dst 0 Offset 0\n"
12143
12144                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
12145                 "OpMemberDecorate %struct16 0 Offset 0\n"
12146                 "OpMemberDecorate %struct16 1 Offset 4\n"
12147                 "OpDecorate %struct16arr3 ArrayStride 16\n"
12148                 "OpDecorate %f16arr3 ArrayStride 2\n"
12149                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
12150                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
12151                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
12152
12153                 "OpMemberDecorate %st_test 0 Offset 0\n"
12154         );
12155
12156         const StringTemplate testFun
12157         (
12158                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
12159                 "     %param = OpFunctionParameter %v4f32\n"
12160                 "     %entry = OpLabel\n"
12161
12162                 "         %i = OpVariable %fp_i32 Function\n"
12163                 "              OpStore %i %c_i32_0\n"
12164
12165                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
12166                 "              OpSelectionMerge %end_if None\n"
12167                 "              OpBranchConditional %will_run %run_test %end_if\n"
12168
12169                 "  %run_test = OpLabel\n"
12170                 "              OpBranch %loop\n"
12171
12172                 "      %loop = OpLabel\n"
12173                 "     %i_cmp = OpLoad %i32 %i\n"
12174                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
12175                 "              OpLoopMerge %merge %next None\n"
12176                 "              OpBranchConditional %lt %write %merge\n"
12177
12178                 "     %write = OpLabel\n"
12179                 "       %ndx = OpLoad %i32 %i\n"
12180
12181                 "${op_sw_fun_call}"
12182
12183                 "              OpStore %dst %val_dst\n"
12184                 "              OpBranch %next\n"
12185
12186                 "      %next = OpLabel\n"
12187                 "     %i_cur = OpLoad %i32 %i\n"
12188                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
12189                 "              OpStore %i %i_new\n"
12190                 "              OpBranch %loop\n"
12191
12192                 "     %merge = OpLabel\n"
12193                 "              OpBranch %end_if\n"
12194                 "    %end_if = OpLabel\n"
12195                 "              OpReturnValue %param\n"
12196                 "              OpFunctionEnd\n"
12197
12198                 "${op_sw_fun_header}"
12199                 " %sw_param = OpFunctionParameter %st_test\n"
12200                 "%sw_paramn = OpFunctionParameter %i32\n"
12201                 " %sw_entry = OpLabel\n"
12202                 "             OpSelectionMerge %switch_e None\n"
12203                 "             OpSwitch %sw_paramn %default ${case_list}\n"
12204
12205                 "${case_bodies}"
12206
12207                 "%default   = OpLabel\n"
12208                 "             OpReturnValue ${op_case_default_value}\n"
12209                 "%switch_e  = OpLabel\n"
12210                 "             OpUnreachable\n" // Unreachable merge block for switch statement
12211                 "             OpFunctionEnd\n"
12212         );
12213
12214         const StringTemplate testCaseBody
12215         (
12216                 "%case_${case_ndx}    = OpLabel\n"
12217                 "%val_ret_${case_ndx} = ${op_name} ${op_args_part} ${access_path}\n"
12218                 "             OpReturnValue %val_ret_${case_ndx}\n"
12219         );
12220
12221         struct OpParts
12222         {
12223                 const char*     premainDecls;
12224                 const char*     swFunCall;
12225                 const char*     swFunHeader;
12226                 const char*     caseDefaultValue;
12227                 const char*     argsPartial;
12228         };
12229
12230         OpParts                                                         opPartsArray[]                  =
12231         {
12232                 // OpCompositeInsert
12233                 {
12234                         "       %fun_t = OpTypeFunction %st_test %f16 %st_test %i32\n"
12235                         "    %SSBO_src = OpTypeStruct %ra_f16\n"
12236                         "    %SSBO_dst = OpTypeStruct %ra_st\n",
12237
12238                         "       %src = OpAccessChain %up_f16 %ssbo_src %c_i32_0 %ndx\n"
12239                         "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %c_i32_0\n"
12240                         "   %val_new = OpLoad %f16 %src\n"
12241                         "   %val_old = OpLoad %st_test %dst\n"
12242                         "   %val_dst = OpFunctionCall %st_test %sw_fun %val_new %val_old %ndx\n",
12243
12244                         "   %sw_fun = OpFunction %st_test None %fun_t\n"
12245                         "%sw_paramv = OpFunctionParameter %f16\n",
12246
12247                         "%sw_param",
12248
12249                         "%st_test %sw_paramv %sw_param",
12250                 },
12251                 // OpCompositeExtract
12252                 {
12253                         "       %fun_t = OpTypeFunction %f16 %st_test %i32\n"
12254                         "    %SSBO_src = OpTypeStruct %ra_st\n"
12255                         "    %SSBO_dst = OpTypeStruct %ra_f16\n",
12256
12257                         "       %src = OpAccessChain %up_st %ssbo_src %c_i32_0 %c_i32_0\n"
12258                         "       %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
12259                         "   %val_src = OpLoad %st_test %src\n"
12260                         "   %val_dst = OpFunctionCall %f16 %sw_fun %val_src %ndx\n",
12261
12262                         "   %sw_fun = OpFunction %f16 None %fun_t\n",
12263
12264                         "%c_f16_na",
12265
12266                         "%f16 %sw_param",
12267                 },
12268         };
12269
12270         DE_ASSERT(opIndex >= 0 && opIndex < DE_LENGTH_OF_ARRAY(opPartsArray));
12271
12272         const char*     accessPathF16[] =
12273         {
12274                 "0",                    // %f16
12275                 DE_NULL,
12276         };
12277         const char*     accessPathV2F16[] =
12278         {
12279                 "0 0",                  // %v2f16
12280                 "0 1",
12281         };
12282         const char*     accessPathV3F16[] =
12283         {
12284                 "0 0",                  // %v3f16
12285                 "0 1",
12286                 "0 2",
12287                 DE_NULL,
12288         };
12289         const char*     accessPathV4F16[] =
12290         {
12291                 "0 0",                  // %v4f16"
12292                 "0 1",
12293                 "0 2",
12294                 "0 3",
12295         };
12296         const char*     accessPathF16Arr3[] =
12297         {
12298                 "0 0",                  // %f16arr3
12299                 "0 1",
12300                 "0 2",
12301                 DE_NULL,
12302         };
12303         const char*     accessPathStruct16Arr3[] =
12304         {
12305                 "0 0 0",                // %struct16arr3
12306                 DE_NULL,
12307                 "0 0 1 0 0",
12308                 "0 0 1 0 1",
12309                 "0 0 1 1 0",
12310                 "0 0 1 1 1",
12311                 "0 0 1 2 0",
12312                 "0 0 1 2 1",
12313                 "0 1 0",
12314                 DE_NULL,
12315                 "0 1 1 0 0",
12316                 "0 1 1 0 1",
12317                 "0 1 1 1 0",
12318                 "0 1 1 1 1",
12319                 "0 1 1 2 0",
12320                 "0 1 1 2 1",
12321                 "0 2 0",
12322                 DE_NULL,
12323                 "0 2 1 0 0",
12324                 "0 2 1 0 1",
12325                 "0 2 1 1 0",
12326                 "0 2 1 1 1",
12327                 "0 2 1 2 0",
12328                 "0 2 1 2 1",
12329         };
12330         const char*     accessPathV2F16Arr5[] =
12331         {
12332                 "0 0 0",                // %v2f16arr5
12333                 "0 0 1",
12334                 "0 1 0",
12335                 "0 1 1",
12336                 "0 2 0",
12337                 "0 2 1",
12338                 "0 3 0",
12339                 "0 3 1",
12340                 "0 4 0",
12341                 "0 4 1",
12342         };
12343         const char*     accessPathV3F16Arr5[] =
12344         {
12345                 "0 0 0",                // %v3f16arr5
12346                 "0 0 1",
12347                 "0 0 2",
12348                 DE_NULL,
12349                 "0 1 0",
12350                 "0 1 1",
12351                 "0 1 2",
12352                 DE_NULL,
12353                 "0 2 0",
12354                 "0 2 1",
12355                 "0 2 2",
12356                 DE_NULL,
12357                 "0 3 0",
12358                 "0 3 1",
12359                 "0 3 2",
12360                 DE_NULL,
12361                 "0 4 0",
12362                 "0 4 1",
12363                 "0 4 2",
12364                 DE_NULL,
12365         };
12366         const char*     accessPathV4F16Arr3[] =
12367         {
12368                 "0 0 0",                // %v4f16arr3
12369                 "0 0 1",
12370                 "0 0 2",
12371                 "0 0 3",
12372                 "0 1 0",
12373                 "0 1 1",
12374                 "0 1 2",
12375                 "0 1 3",
12376                 "0 2 0",
12377                 "0 2 1",
12378                 "0 2 2",
12379                 "0 2 3",
12380                 DE_NULL,
12381                 DE_NULL,
12382                 DE_NULL,
12383                 DE_NULL,
12384         };
12385
12386         struct TypeTestParameters
12387         {
12388                 const char*             name;
12389                 size_t                  accessPathLength;
12390                 const char**    accessPath;
12391         };
12392
12393         const TypeTestParameters typeTestParameters[] =
12394         {
12395                 {       "f16",                  DE_LENGTH_OF_ARRAY(accessPathF16),                      accessPathF16                   },
12396                 {       "v2f16",                DE_LENGTH_OF_ARRAY(accessPathV2F16),            accessPathV2F16                 },
12397                 {       "v3f16",                DE_LENGTH_OF_ARRAY(accessPathV3F16),            accessPathV3F16                 },
12398                 {       "v4f16",                DE_LENGTH_OF_ARRAY(accessPathV4F16),            accessPathV4F16                 },
12399                 {       "f16arr3",              DE_LENGTH_OF_ARRAY(accessPathF16Arr3),          accessPathF16Arr3               },
12400                 {       "v2f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV2F16Arr5),        accessPathV2F16Arr5             },
12401                 {       "v3f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV3F16Arr5),        accessPathV3F16Arr5             },
12402                 {       "v4f16arr3",    DE_LENGTH_OF_ARRAY(accessPathV4F16Arr3),        accessPathV4F16Arr3             },
12403                 {       "struct16arr3", DE_LENGTH_OF_ARRAY(accessPathStruct16Arr3),     accessPathStruct16Arr3  },
12404         };
12405
12406         for (size_t typeTestNdx = 0; typeTestNdx < DE_LENGTH_OF_ARRAY(typeTestParameters); ++typeTestNdx)
12407         {
12408                 const OpParts           opParts                         = opPartsArray[opIndex];
12409                 const string            testName                        = typeTestParameters[typeTestNdx].name;
12410                 const size_t            structItemsCount        = typeTestParameters[typeTestNdx].accessPathLength;
12411                 const char**            accessPath                      = typeTestParameters[typeTestNdx].accessPath;
12412                 SpecResource            specResource;
12413                 map<string, string>     specs;
12414                 VulkanFeatures          features;
12415                 map<string, string>     fragments;
12416                 vector<string>          extensions;
12417                 vector<deFloat16>       inputFP16;
12418                 vector<deFloat16>       dummyFP16Output;
12419
12420                 // Generate values for input
12421                 inputFP16.reserve(structItemsCount);
12422                 for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
12423                         inputFP16.push_back((accessPath[structItemNdx] == DE_NULL) ? exceptionValue : tcu::Float16(float(structItemNdx)).bits());
12424
12425                 dummyFP16Output.resize(structItemsCount);
12426
12427                 // Generate cases for OpSwitch
12428                 {
12429                         string  caseBodies;
12430                         string  caseList;
12431
12432                         for (deUint32 caseNdx = 0; caseNdx < structItemsCount; ++caseNdx)
12433                                 if (accessPath[caseNdx] != DE_NULL)
12434                                 {
12435                                         map<string, string>     specCase;
12436
12437                                         specCase["case_ndx"]            = de::toString(caseNdx);
12438                                         specCase["access_path"]         = accessPath[caseNdx];
12439                                         specCase["op_args_part"]        = opParts.argsPartial;
12440                                         specCase["op_name"]                     = opName;
12441
12442                                         caseBodies      += testCaseBody.specialize(specCase);
12443                                         caseList        += de::toString(caseNdx) + " %case_" + de::toString(caseNdx) + " ";
12444                                 }
12445
12446                         specs["case_bodies"]    = caseBodies;
12447                         specs["case_list"]              = caseList;
12448                 }
12449
12450                 specs["num_elements"]                   = de::toString(structItemsCount);
12451                 specs["field_type"]                             = typeTestParameters[typeTestNdx].name;
12452                 specs["struct_item_size"]               = de::toString(structItemsCount * sizeof(deFloat16));
12453                 specs["op_premain_decls"]               = opParts.premainDecls;
12454                 specs["op_sw_fun_call"]                 = opParts.swFunCall;
12455                 specs["op_sw_fun_header"]               = opParts.swFunHeader;
12456                 specs["op_case_default_value"]  = opParts.caseDefaultValue;
12457
12458                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
12459                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
12460                 fragments["decoration"]         = decoration.specialize(specs);
12461                 fragments["pre_main"]           = preMain.specialize(specs);
12462                 fragments["testfun"]            = testFun.specialize(specs);
12463
12464                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputFP16)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12465                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(dummyFP16Output)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12466                 specResource.verifyIO = compareFP16CompositeFunc;
12467
12468                 extensions.push_back("VK_KHR_16bit_storage");
12469                 extensions.push_back("VK_KHR_shader_float16_int8");
12470
12471                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
12472                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
12473
12474                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
12475         }
12476
12477         return testGroup.release();
12478 }
12479
12480 struct fp16PerComponent
12481 {
12482         fp16PerComponent()
12483                 : flavor(0)
12484                 , floatFormat16 (-14, 15, 10, true)
12485                 , outCompCount(0)
12486                 , argCompCount(3, 0)
12487         {
12488         }
12489
12490         bool                    callOncePerComponent    ()                                                                      { return true; }
12491         deUint32                getComponentValidity    ()                                                                      { return static_cast<deUint32>(-1); }
12492
12493         virtual double  getULPs                                 (vector<const deFloat16*>&)                     { return 1.0; }
12494         virtual double  getMin                                  (double value, double ulps)                     { return value - floatFormat16.ulp(deAbs(value), ulps); }
12495         virtual double  getMax                                  (double value, double ulps)                     { return value + floatFormat16.ulp(deAbs(value), ulps); }
12496
12497         virtual size_t  getFlavorCount                  ()                                                                      { return flavorNames.empty() ? 1 : flavorNames.size(); }
12498         virtual void    setFlavor                               (size_t flavorNo)                                       { DE_ASSERT(flavorNo < getFlavorCount()); flavor = flavorNo; }
12499         virtual size_t  getFlavor                               ()                                                                      { return flavor; }
12500         virtual string  getCurrentFlavorName    ()                                                                      { return flavorNames.empty() ? string("") : flavorNames[getFlavor()]; }
12501
12502         virtual void    setOutCompCount                 (size_t compCount)                                      { outCompCount = compCount; }
12503         virtual size_t  getOutCompCount                 ()                                                                      { return outCompCount; }
12504
12505         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)        { argCompCount[argNo] = compCount; }
12506         virtual size_t  getArgCompCount                 (size_t argNo)                                          { return argCompCount[argNo]; }
12507
12508 protected:
12509         size_t                          flavor;
12510         tcu::FloatFormat        floatFormat16;
12511         size_t                          outCompCount;
12512         vector<size_t>          argCompCount;
12513         vector<string>          flavorNames;
12514 };
12515
12516 struct fp16OpFNegate : public fp16PerComponent
12517 {
12518         template <class fp16type>
12519         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12520         {
12521                 const fp16type  x               (*in[0]);
12522                 const double    d               (x.asDouble());
12523                 const double    result  (0.0 - d);
12524
12525                 out[0] = fp16type(result).bits();
12526                 min[0] = getMin(result, getULPs(in));
12527                 max[0] = getMax(result, getULPs(in));
12528
12529                 return true;
12530         }
12531 };
12532
12533 struct fp16Round : public fp16PerComponent
12534 {
12535         fp16Round() : fp16PerComponent()
12536         {
12537                 flavorNames.push_back("Floor(x+0.5)");
12538                 flavorNames.push_back("Floor(x-0.5)");
12539                 flavorNames.push_back("RoundEven");
12540         }
12541
12542         template<class fp16type>
12543         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12544         {
12545                 const fp16type  x               (*in[0]);
12546                 const double    d               (x.asDouble());
12547                 double                  result  (0.0);
12548
12549                 switch (flavor)
12550                 {
12551                         case 0:         result = deRound(d);            break;
12552                         case 1:         result = deFloor(d - 0.5);      break;
12553                         case 2:         result = deRoundEven(d);        break;
12554                         default:        TCU_THROW(InternalError, "Invalid flavor specified");
12555                 }
12556
12557                 out[0] = fp16type(result).bits();
12558                 min[0] = getMin(result, getULPs(in));
12559                 max[0] = getMax(result, getULPs(in));
12560
12561                 return true;
12562         }
12563 };
12564
12565 struct fp16RoundEven : public fp16PerComponent
12566 {
12567         template<class fp16type>
12568         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12569         {
12570                 const fp16type  x               (*in[0]);
12571                 const double    d               (x.asDouble());
12572                 const double    result  (deRoundEven(d));
12573
12574                 out[0] = fp16type(result).bits();
12575                 min[0] = getMin(result, getULPs(in));
12576                 max[0] = getMax(result, getULPs(in));
12577
12578                 return true;
12579         }
12580 };
12581
12582 struct fp16Trunc : public fp16PerComponent
12583 {
12584         template<class fp16type>
12585         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12586         {
12587                 const fp16type  x               (*in[0]);
12588                 const double    d               (x.asDouble());
12589                 const double    result  (deTrunc(d));
12590
12591                 out[0] = fp16type(result).bits();
12592                 min[0] = getMin(result, getULPs(in));
12593                 max[0] = getMax(result, getULPs(in));
12594
12595                 return true;
12596         }
12597 };
12598
12599 struct fp16FAbs : public fp16PerComponent
12600 {
12601         template<class fp16type>
12602         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12603         {
12604                 const fp16type  x               (*in[0]);
12605                 const double    d               (x.asDouble());
12606                 const double    result  (deAbs(d));
12607
12608                 out[0] = fp16type(result).bits();
12609                 min[0] = getMin(result, getULPs(in));
12610                 max[0] = getMax(result, getULPs(in));
12611
12612                 return true;
12613         }
12614 };
12615
12616 struct fp16FSign : public fp16PerComponent
12617 {
12618         template<class fp16type>
12619         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12620         {
12621                 const fp16type  x               (*in[0]);
12622                 const double    d               (x.asDouble());
12623                 const double    result  (deSign(d));
12624
12625                 if (x.isNaN())
12626                         return false;
12627
12628                 out[0] = fp16type(result).bits();
12629                 min[0] = getMin(result, getULPs(in));
12630                 max[0] = getMax(result, getULPs(in));
12631
12632                 return true;
12633         }
12634 };
12635
12636 struct fp16Floor : public fp16PerComponent
12637 {
12638         template<class fp16type>
12639         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12640         {
12641                 const fp16type  x               (*in[0]);
12642                 const double    d               (x.asDouble());
12643                 const double    result  (deFloor(d));
12644
12645                 out[0] = fp16type(result).bits();
12646                 min[0] = getMin(result, getULPs(in));
12647                 max[0] = getMax(result, getULPs(in));
12648
12649                 return true;
12650         }
12651 };
12652
12653 struct fp16Ceil : public fp16PerComponent
12654 {
12655         template<class fp16type>
12656         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12657         {
12658                 const fp16type  x               (*in[0]);
12659                 const double    d               (x.asDouble());
12660                 const double    result  (deCeil(d));
12661
12662                 out[0] = fp16type(result).bits();
12663                 min[0] = getMin(result, getULPs(in));
12664                 max[0] = getMax(result, getULPs(in));
12665
12666                 return true;
12667         }
12668 };
12669
12670 struct fp16Fract : public fp16PerComponent
12671 {
12672         template<class fp16type>
12673         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12674         {
12675                 const fp16type  x               (*in[0]);
12676                 const double    d               (x.asDouble());
12677                 const double    result  (deFrac(d));
12678
12679                 out[0] = fp16type(result).bits();
12680                 min[0] = getMin(result, getULPs(in));
12681                 max[0] = getMax(result, getULPs(in));
12682
12683                 return true;
12684         }
12685 };
12686
12687 struct fp16Radians : public fp16PerComponent
12688 {
12689         virtual double getULPs (vector<const deFloat16*>& in)
12690         {
12691                 DE_UNREF(in);
12692
12693                 return 2.5;
12694         }
12695
12696         template<class fp16type>
12697         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12698         {
12699                 const fp16type  x               (*in[0]);
12700                 const float             d               (x.asFloat());
12701                 const float             result  (deFloatRadians(d));
12702
12703                 out[0] = fp16type(result).bits();
12704                 min[0] = getMin(result, getULPs(in));
12705                 max[0] = getMax(result, getULPs(in));
12706
12707                 return true;
12708         }
12709 };
12710
12711 struct fp16Degrees : public fp16PerComponent
12712 {
12713         virtual double getULPs (vector<const deFloat16*>& in)
12714         {
12715                 DE_UNREF(in);
12716
12717                 return 2.5;
12718         }
12719
12720         template<class fp16type>
12721         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12722         {
12723                 const fp16type  x               (*in[0]);
12724                 const float             d               (x.asFloat());
12725                 const float             result  (deFloatDegrees(d));
12726
12727                 out[0] = fp16type(result).bits();
12728                 min[0] = getMin(result, getULPs(in));
12729                 max[0] = getMax(result, getULPs(in));
12730
12731                 return true;
12732         }
12733 };
12734
12735 struct fp16Sin : public fp16PerComponent
12736 {
12737         template<class fp16type>
12738         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12739         {
12740                 const fp16type  x                       (*in[0]);
12741                 const double    d                       (x.asDouble());
12742                 const double    result          (deSin(d));
12743                 const double    unspecUlp       (16.0);
12744                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12745
12746                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12747                         return false;
12748
12749                 out[0] = fp16type(result).bits();
12750                 min[0] = result - err;
12751                 max[0] = result + err;
12752
12753                 return true;
12754         }
12755 };
12756
12757 struct fp16Cos : public fp16PerComponent
12758 {
12759         template<class fp16type>
12760         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12761         {
12762                 const fp16type  x                       (*in[0]);
12763                 const double    d                       (x.asDouble());
12764                 const double    result          (deCos(d));
12765                 const double    unspecUlp       (16.0);
12766                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12767
12768                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12769                         return false;
12770
12771                 out[0] = fp16type(result).bits();
12772                 min[0] = result - err;
12773                 max[0] = result + err;
12774
12775                 return true;
12776         }
12777 };
12778
12779 struct fp16Tan : public fp16PerComponent
12780 {
12781         template<class fp16type>
12782         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12783         {
12784                 const fp16type  x               (*in[0]);
12785                 const double    d               (x.asDouble());
12786                 const double    result  (deTan(d));
12787
12788                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12789                         return false;
12790
12791                 out[0] = fp16type(result).bits();
12792                 {
12793                         const double    err                     = deLdExp(1.0, -7);
12794                         const double    s1                      = deSin(d) + err;
12795                         const double    s2                      = deSin(d) - err;
12796                         const double    c1                      = deCos(d) + err;
12797                         const double    c2                      = deCos(d) - err;
12798                         const double    edgeVals[]      = {s1/c1, s1/c2, s2/c1, s2/c2};
12799                         double                  edgeLeft        = out[0];
12800                         double                  edgeRight       = out[0];
12801
12802                         if (deSign(c1 * c2) < 0.0)
12803                         {
12804                                 edgeLeft        = -std::numeric_limits<double>::infinity();
12805                                 edgeRight       = +std::numeric_limits<double>::infinity();
12806                         }
12807                         else
12808                         {
12809                                 edgeLeft        = *std::min_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12810                                 edgeRight       = *std::max_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12811                         }
12812
12813                         min[0] = edgeLeft;
12814                         max[0] = edgeRight;
12815                 }
12816
12817                 return true;
12818         }
12819 };
12820
12821 struct fp16Asin : public fp16PerComponent
12822 {
12823         template<class fp16type>
12824         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12825         {
12826                 const fp16type  x               (*in[0]);
12827                 const double    d               (x.asDouble());
12828                 const double    result  (deAsin(d));
12829                 const double    error   (deAtan2(d, sqrt(1.0 - d * d)));
12830
12831                 if (!x.isNaN() && deAbs(d) > 1.0)
12832                         return false;
12833
12834                 out[0] = fp16type(result).bits();
12835                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12836                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12837
12838                 return true;
12839         }
12840 };
12841
12842 struct fp16Acos : public fp16PerComponent
12843 {
12844         template<class fp16type>
12845         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12846         {
12847                 const fp16type  x               (*in[0]);
12848                 const double    d               (x.asDouble());
12849                 const double    result  (deAcos(d));
12850                 const double    error   (deAtan2(sqrt(1.0 - d * d), d));
12851
12852                 if (!x.isNaN() && deAbs(d) > 1.0)
12853                         return false;
12854
12855                 out[0] = fp16type(result).bits();
12856                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12857                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12858
12859                 return true;
12860         }
12861 };
12862
12863 struct fp16Atan : public fp16PerComponent
12864 {
12865         virtual double getULPs(vector<const deFloat16*>& in)
12866         {
12867                 DE_UNREF(in);
12868
12869                 return 2 * 5.0; // This is not a precision test. Value is not from spec
12870         }
12871
12872         template<class fp16type>
12873         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12874         {
12875                 const fp16type  x               (*in[0]);
12876                 const double    d               (x.asDouble());
12877                 const double    result  (deAtanOver(d));
12878
12879                 out[0] = fp16type(result).bits();
12880                 min[0] = getMin(result, getULPs(in));
12881                 max[0] = getMax(result, getULPs(in));
12882
12883                 return true;
12884         }
12885 };
12886
12887 struct fp16Sinh : public fp16PerComponent
12888 {
12889         fp16Sinh() : fp16PerComponent()
12890         {
12891                 flavorNames.push_back("Double");
12892                 flavorNames.push_back("ExpFP16");
12893         }
12894
12895         template<class fp16type>
12896         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12897         {
12898                 const fp16type  x               (*in[0]);
12899                 const double    d               (x.asDouble());
12900                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12901                 double                  result  (0.0);
12902                 double                  error   (0.0);
12903
12904                 if (getFlavor() == 0)
12905                 {
12906                         result  = deSinh(d);
12907                         error   = floatFormat16.ulp(deAbs(result), ulps);
12908                 }
12909                 else if (getFlavor() == 1)
12910                 {
12911                         const fp16type  epx     (deExp(d));
12912                         const fp16type  enx     (deExp(-d));
12913                         const fp16type  esx     (epx.asDouble() - enx.asDouble());
12914                         const fp16type  sx2     (esx.asDouble() / 2.0);
12915
12916                         result  = sx2.asDouble();
12917                         error   = deAbs(floatFormat16.ulp(epx.asDouble(), ulps)) + deAbs(floatFormat16.ulp(enx.asDouble(), ulps));
12918                 }
12919                 else
12920                 {
12921                         TCU_THROW(InternalError, "Unknown flavor");
12922                 }
12923
12924                 out[0] = fp16type(result).bits();
12925                 min[0] = result - error;
12926                 max[0] = result + error;
12927
12928                 return true;
12929         }
12930 };
12931
12932 struct fp16Cosh : public fp16PerComponent
12933 {
12934         fp16Cosh() : fp16PerComponent()
12935         {
12936                 flavorNames.push_back("Double");
12937                 flavorNames.push_back("ExpFP16");
12938         }
12939
12940         template<class fp16type>
12941         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12942         {
12943                 const fp16type  x               (*in[0]);
12944                 const double    d               (x.asDouble());
12945                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12946                 double                  result  (0.0);
12947
12948                 if (getFlavor() == 0)
12949                 {
12950                         result = deCosh(d);
12951                 }
12952                 else if (getFlavor() == 1)
12953                 {
12954                         const fp16type  epx     (deExp(d));
12955                         const fp16type  enx     (deExp(-d));
12956                         const fp16type  esx     (epx.asDouble() + enx.asDouble());
12957                         const fp16type  sx2     (esx.asDouble() / 2.0);
12958
12959                         result = sx2.asDouble();
12960                 }
12961                 else
12962                 {
12963                         TCU_THROW(InternalError, "Unknown flavor");
12964                 }
12965
12966                 out[0] = fp16type(result).bits();
12967                 min[0] = result - floatFormat16.ulp(deAbs(result), ulps);
12968                 max[0] = result + floatFormat16.ulp(deAbs(result), ulps);
12969
12970                 return true;
12971         }
12972 };
12973
12974 struct fp16Tanh : public fp16PerComponent
12975 {
12976         fp16Tanh() : fp16PerComponent()
12977         {
12978                 flavorNames.push_back("Tanh");
12979                 flavorNames.push_back("SinhCosh");
12980                 flavorNames.push_back("SinhCoshFP16");
12981                 flavorNames.push_back("PolyFP16");
12982         }
12983
12984         virtual double getULPs (vector<const deFloat16*>& in)
12985         {
12986                 const tcu::Float16      x       (*in[0]);
12987                 const double            d       (x.asDouble());
12988
12989                 return 2 * (1.0 + 2 * deAbs(d)); // This is not a precision test. Value is not from spec
12990         }
12991
12992         template<class fp16type>
12993         inline double calcPoly (const fp16type& espx, const fp16type& esnx, const fp16type& ecpx, const fp16type& ecnx)
12994         {
12995                 const fp16type  esx     (espx.asDouble() - esnx.asDouble());
12996                 const fp16type  sx2     (esx.asDouble() / 2.0);
12997                 const fp16type  ecx     (ecpx.asDouble() + ecnx.asDouble());
12998                 const fp16type  cx2     (ecx.asDouble() / 2.0);
12999                 const fp16type  tg      (sx2.asDouble() / cx2.asDouble());
13000                 const double    rez     (tg.asDouble());
13001
13002                 return rez;
13003         }
13004
13005         template<class fp16type>
13006         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13007         {
13008                 const fp16type  x               (*in[0]);
13009                 const double    d               (x.asDouble());
13010                 double                  result  (0.0);
13011
13012                 if (getFlavor() == 0)
13013                 {
13014                         result  = deTanh(d);
13015                         min[0]  = getMin(result, getULPs(in));
13016                         max[0]  = getMax(result, getULPs(in));
13017                 }
13018                 else if (getFlavor() == 1)
13019                 {
13020                         result  = deSinh(d) / deCosh(d);
13021                         min[0]  = getMin(result, getULPs(in));
13022                         max[0]  = getMax(result, getULPs(in));
13023                 }
13024                 else if (getFlavor() == 2)
13025                 {
13026                         const fp16type  s       (deSinh(d));
13027                         const fp16type  c       (deCosh(d));
13028
13029                         result  = s.asDouble() / c.asDouble();
13030                         min[0]  = getMin(result, getULPs(in));
13031                         max[0]  = getMax(result, getULPs(in));
13032                 }
13033                 else if (getFlavor() == 3)
13034                 {
13035                         const double    ulps    (getULPs(in));
13036                         const double    epxm    (deExp( d));
13037                         const double    enxm    (deExp(-d));
13038                         const double    epxmerr = floatFormat16.ulp(epxm, ulps);
13039                         const double    enxmerr = floatFormat16.ulp(enxm, ulps);
13040                         const fp16type  epx[]   = { fp16type(epxm - epxmerr), fp16type(epxm + epxmerr) };
13041                         const fp16type  enx[]   = { fp16type(enxm - enxmerr), fp16type(enxm + enxmerr) };
13042                         const fp16type  epxm16  (epxm);
13043                         const fp16type  enxm16  (enxm);
13044                         vector<double>  tgs;
13045
13046                         for (size_t spNdx = 0; spNdx < DE_LENGTH_OF_ARRAY(epx); ++spNdx)
13047                         for (size_t snNdx = 0; snNdx < DE_LENGTH_OF_ARRAY(enx); ++snNdx)
13048                         for (size_t cpNdx = 0; cpNdx < DE_LENGTH_OF_ARRAY(epx); ++cpNdx)
13049                         for (size_t cnNdx = 0; cnNdx < DE_LENGTH_OF_ARRAY(enx); ++cnNdx)
13050                         {
13051                                 const double tgh = calcPoly(epx[spNdx], enx[snNdx], epx[cpNdx], enx[cnNdx]);
13052
13053                                 tgs.push_back(tgh);
13054                         }
13055
13056                         result = calcPoly(epxm16, enxm16, epxm16, enxm16);
13057                         min[0] = *std::min_element(tgs.begin(), tgs.end());
13058                         max[0] = *std::max_element(tgs.begin(), tgs.end());
13059                 }
13060                 else
13061                 {
13062                         TCU_THROW(InternalError, "Unknown flavor");
13063                 }
13064
13065                 out[0] = fp16type(result).bits();
13066
13067                 return true;
13068         }
13069 };
13070
13071 struct fp16Asinh : public fp16PerComponent
13072 {
13073         fp16Asinh() : fp16PerComponent()
13074         {
13075                 flavorNames.push_back("Double");
13076                 flavorNames.push_back("PolyFP16Wiki");
13077                 flavorNames.push_back("PolyFP16Abs");
13078         }
13079
13080         virtual double getULPs (vector<const deFloat16*>& in)
13081         {
13082                 DE_UNREF(in);
13083
13084                 return 256.0; // This is not a precision test. Value is not from spec
13085         }
13086
13087         template<class fp16type>
13088         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13089         {
13090                 const fp16type  x               (*in[0]);
13091                 const double    d               (x.asDouble());
13092                 double                  result  (0.0);
13093
13094                 if (getFlavor() == 0)
13095                 {
13096                         result = deAsinh(d);
13097                 }
13098                 else if (getFlavor() == 1)
13099                 {
13100                         const fp16type  x2              (d * d);
13101                         const fp16type  x2p1    (x2.asDouble() + 1.0);
13102                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
13103                         const fp16type  sxsq    (d + sq.asDouble());
13104                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
13105
13106                         if (lsxsq.isInf())
13107                                 return false;
13108
13109                         result = lsxsq.asDouble();
13110                 }
13111                 else if (getFlavor() == 2)
13112                 {
13113                         const fp16type  x2              (d * d);
13114                         const fp16type  x2p1    (x2.asDouble() + 1.0);
13115                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
13116                         const fp16type  sxsq    (deAbs(d) + sq.asDouble());
13117                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
13118
13119                         result = deSign(d) * lsxsq.asDouble();
13120                 }
13121                 else
13122                 {
13123                         TCU_THROW(InternalError, "Unknown flavor");
13124                 }
13125
13126                 out[0] = fp16type(result).bits();
13127                 min[0] = getMin(result, getULPs(in));
13128                 max[0] = getMax(result, getULPs(in));
13129
13130                 return true;
13131         }
13132 };
13133
13134 struct fp16Acosh : public fp16PerComponent
13135 {
13136         fp16Acosh() : fp16PerComponent()
13137         {
13138                 flavorNames.push_back("Double");
13139                 flavorNames.push_back("PolyFP16");
13140         }
13141
13142         virtual double getULPs (vector<const deFloat16*>& in)
13143         {
13144                 DE_UNREF(in);
13145
13146                 return 16.0; // This is not a precision test. Value is not from spec
13147         }
13148
13149         template<class fp16type>
13150         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13151         {
13152                 const fp16type  x               (*in[0]);
13153                 const double    d               (x.asDouble());
13154                 double                  result  (0.0);
13155
13156                 if (!x.isNaN() && d < 1.0)
13157                         return false;
13158
13159                 if (getFlavor() == 0)
13160                 {
13161                         result = deAcosh(d);
13162                 }
13163                 else if (getFlavor() == 1)
13164                 {
13165                         const fp16type  x2              (d * d);
13166                         const fp16type  x2m1    (x2.asDouble() - 1.0);
13167                         const fp16type  sq              (deSqrt(x2m1.asDouble()));
13168                         const fp16type  sxsq    (d + sq.asDouble());
13169                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
13170
13171                         result = lsxsq.asDouble();
13172                 }
13173                 else
13174                 {
13175                         TCU_THROW(InternalError, "Unknown flavor");
13176                 }
13177
13178                 out[0] = fp16type(result).bits();
13179                 min[0] = getMin(result, getULPs(in));
13180                 max[0] = getMax(result, getULPs(in));
13181
13182                 return true;
13183         }
13184 };
13185
13186 struct fp16Atanh : public fp16PerComponent
13187 {
13188         fp16Atanh() : fp16PerComponent()
13189         {
13190                 flavorNames.push_back("Double");
13191                 flavorNames.push_back("PolyFP16");
13192         }
13193
13194         template<class fp16type>
13195         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13196         {
13197                 const fp16type  x               (*in[0]);
13198                 const double    d               (x.asDouble());
13199                 double                  result  (0.0);
13200
13201                 if (deAbs(d) >= 1.0)
13202                         return false;
13203
13204                 if (getFlavor() == 0)
13205                 {
13206                         const double    ulps    (16.0); // This is not a precision test. Value is not from spec
13207
13208                         result = deAtanh(d);
13209                         min[0] = getMin(result, ulps);
13210                         max[0] = getMax(result, ulps);
13211                 }
13212                 else if (getFlavor() == 1)
13213                 {
13214                         const fp16type  x1a             (1.0 + d);
13215                         const fp16type  x1b             (1.0 - d);
13216                         const fp16type  x1d             (x1a.asDouble() / x1b.asDouble());
13217                         const fp16type  lx1d    (deLog(x1d.asDouble()));
13218                         const fp16type  lx1d2   (0.5 * lx1d.asDouble());
13219                         const double    error   (2 * (de::inRange(deAbs(x1d.asDouble()), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(x1d.asDouble()), 3.0)));
13220
13221                         result = lx1d2.asDouble();
13222                         min[0] = result - error;
13223                         max[0] = result + error;
13224                 }
13225                 else
13226                 {
13227                         TCU_THROW(InternalError, "Unknown flavor");
13228                 }
13229
13230                 out[0] = fp16type(result).bits();
13231
13232                 return true;
13233         }
13234 };
13235
13236 struct fp16Exp : public fp16PerComponent
13237 {
13238         template<class fp16type>
13239         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13240         {
13241                 const fp16type  x               (*in[0]);
13242                 const double    d               (x.asDouble());
13243                 const double    ulps    (10.0 * (1.0 + 2.0 * deAbs(d)));
13244                 const double    result  (deExp(d));
13245
13246                 out[0] = fp16type(result).bits();
13247                 min[0] = getMin(result, ulps);
13248                 max[0] = getMax(result, ulps);
13249
13250                 return true;
13251         }
13252 };
13253
13254 struct fp16Log : public fp16PerComponent
13255 {
13256         template<class fp16type>
13257         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13258         {
13259                 const fp16type  x               (*in[0]);
13260                 const double    d               (x.asDouble());
13261                 const double    result  (deLog(d));
13262                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13263
13264                 if (d <= 0.0)
13265                         return false;
13266
13267                 out[0] = fp16type(result).bits();
13268                 min[0] = result - error;
13269                 max[0] = result + error;
13270
13271                 return true;
13272         }
13273 };
13274
13275 struct fp16Exp2 : public fp16PerComponent
13276 {
13277         template<class fp16type>
13278         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13279         {
13280                 const fp16type  x               (*in[0]);
13281                 const double    d               (x.asDouble());
13282                 const double    result  (deExp2(d));
13283                 const double    ulps    (1.0 + 2.0 * deAbs(fp16type(in[0][0]).asDouble()));
13284
13285                 out[0] = fp16type(result).bits();
13286                 min[0] = getMin(result, ulps);
13287                 max[0] = getMax(result, ulps);
13288
13289                 return true;
13290         }
13291 };
13292
13293 struct fp16Log2 : public fp16PerComponent
13294 {
13295         template<class fp16type>
13296         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13297         {
13298                 const fp16type  x               (*in[0]);
13299                 const double    d               (x.asDouble());
13300                 const double    result  (deLog2(d));
13301                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13302
13303                 if (d <= 0.0)
13304                         return false;
13305
13306                 out[0] = fp16type(result).bits();
13307                 min[0] = result - error;
13308                 max[0] = result + error;
13309
13310                 return true;
13311         }
13312 };
13313
13314 struct fp16Sqrt : public fp16PerComponent
13315 {
13316         virtual double getULPs (vector<const deFloat16*>& in)
13317         {
13318                 DE_UNREF(in);
13319
13320                 return 6.0;
13321         }
13322
13323         template<class fp16type>
13324         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13325         {
13326                 const fp16type  x               (*in[0]);
13327                 const double    d               (x.asDouble());
13328                 const double    result  (deSqrt(d));
13329
13330                 if (!x.isNaN() && d < 0.0)
13331                         return false;
13332
13333                 out[0] = fp16type(result).bits();
13334                 min[0] = getMin(result, getULPs(in));
13335                 max[0] = getMax(result, getULPs(in));
13336
13337                 return true;
13338         }
13339 };
13340
13341 struct fp16InverseSqrt : public fp16PerComponent
13342 {
13343         virtual double getULPs (vector<const deFloat16*>& in)
13344         {
13345                 DE_UNREF(in);
13346
13347                 return 2.0;
13348         }
13349
13350         template<class fp16type>
13351         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13352         {
13353                 const fp16type  x               (*in[0]);
13354                 const double    d               (x.asDouble());
13355                 const double    result  (1.0/deSqrt(d));
13356
13357                 if (!x.isNaN() && d <= 0.0)
13358                         return false;
13359
13360                 out[0] = fp16type(result).bits();
13361                 min[0] = getMin(result, getULPs(in));
13362                 max[0] = getMax(result, getULPs(in));
13363
13364                 return true;
13365         }
13366 };
13367
13368 struct fp16ModfFrac : public fp16PerComponent
13369 {
13370         template<class fp16type>
13371         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13372         {
13373                 const fp16type  x               (*in[0]);
13374                 const double    d               (x.asDouble());
13375                 double                  i               (0.0);
13376                 const double    result  (deModf(d, &i));
13377
13378                 if (x.isInf() || x.isNaN())
13379                         return false;
13380
13381                 out[0] = fp16type(result).bits();
13382                 min[0] = getMin(result, getULPs(in));
13383                 max[0] = getMax(result, getULPs(in));
13384
13385                 return true;
13386         }
13387 };
13388
13389 struct fp16ModfInt : public fp16PerComponent
13390 {
13391         template<class fp16type>
13392         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13393         {
13394                 const fp16type  x               (*in[0]);
13395                 const double    d               (x.asDouble());
13396                 double                  i               (0.0);
13397                 const double    dummy   (deModf(d, &i));
13398                 const double    result  (i);
13399
13400                 DE_UNREF(dummy);
13401
13402                 if (x.isInf() || x.isNaN())
13403                         return false;
13404
13405                 out[0] = fp16type(result).bits();
13406                 min[0] = getMin(result, getULPs(in));
13407                 max[0] = getMax(result, getULPs(in));
13408
13409                 return true;
13410         }
13411 };
13412
13413 struct fp16FrexpS : public fp16PerComponent
13414 {
13415         template<class fp16type>
13416         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13417         {
13418                 const fp16type  x               (*in[0]);
13419                 const double    d               (x.asDouble());
13420                 int                             e               (0);
13421                 const double    result  (deFrExp(d, &e));
13422
13423                 if (x.isNaN() || x.isInf())
13424                         return false;
13425
13426                 out[0] = fp16type(result).bits();
13427                 min[0] = getMin(result, getULPs(in));
13428                 max[0] = getMax(result, getULPs(in));
13429
13430                 return true;
13431         }
13432 };
13433
13434 struct fp16FrexpE : public fp16PerComponent
13435 {
13436         template<class fp16type>
13437         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13438         {
13439                 const fp16type  x               (*in[0]);
13440                 const double    d               (x.asDouble());
13441                 int                             e               (0);
13442                 const double    dummy   (deFrExp(d, &e));
13443                 const double    result  (static_cast<double>(e));
13444
13445                 DE_UNREF(dummy);
13446
13447                 if (x.isNaN() || x.isInf())
13448                         return false;
13449
13450                 out[0] = fp16type(result).bits();
13451                 min[0] = getMin(result, getULPs(in));
13452                 max[0] = getMax(result, getULPs(in));
13453
13454                 return true;
13455         }
13456 };
13457
13458 struct fp16OpFAdd : public fp16PerComponent
13459 {
13460         template<class fp16type>
13461         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13462         {
13463                 const fp16type  x               (*in[0]);
13464                 const fp16type  y               (*in[1]);
13465                 const double    xd              (x.asDouble());
13466                 const double    yd              (y.asDouble());
13467                 const double    result  (xd + yd);
13468
13469                 out[0] = fp16type(result).bits();
13470                 min[0] = getMin(result, getULPs(in));
13471                 max[0] = getMax(result, getULPs(in));
13472
13473                 return true;
13474         }
13475 };
13476
13477 struct fp16OpFSub : public fp16PerComponent
13478 {
13479         template<class fp16type>
13480         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13481         {
13482                 const fp16type  x               (*in[0]);
13483                 const fp16type  y               (*in[1]);
13484                 const double    xd              (x.asDouble());
13485                 const double    yd              (y.asDouble());
13486                 const double    result  (xd - yd);
13487
13488                 out[0] = fp16type(result).bits();
13489                 min[0] = getMin(result, getULPs(in));
13490                 max[0] = getMax(result, getULPs(in));
13491
13492                 return true;
13493         }
13494 };
13495
13496 struct fp16OpFMul : public fp16PerComponent
13497 {
13498         template<class fp16type>
13499         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13500         {
13501                 const fp16type  x               (*in[0]);
13502                 const fp16type  y               (*in[1]);
13503                 const double    xd              (x.asDouble());
13504                 const double    yd              (y.asDouble());
13505                 const double    result  (xd * yd);
13506
13507                 out[0] = fp16type(result).bits();
13508                 min[0] = getMin(result, getULPs(in));
13509                 max[0] = getMax(result, getULPs(in));
13510
13511                 return true;
13512         }
13513 };
13514
13515 struct fp16OpFDiv : public fp16PerComponent
13516 {
13517         fp16OpFDiv() : fp16PerComponent()
13518         {
13519                 flavorNames.push_back("DirectDiv");
13520                 flavorNames.push_back("InverseDiv");
13521         }
13522
13523         template<class fp16type>
13524         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13525         {
13526                 const fp16type  x                       (*in[0]);
13527                 const fp16type  y                       (*in[1]);
13528                 const double    xd                      (x.asDouble());
13529                 const double    yd                      (y.asDouble());
13530                 const double    unspecUlp       (16.0);
13531                 const double    ulpCnt          (de::inRange(deAbs(yd), deLdExp(1, -14), deLdExp(1, 14)) ? 2.5 : unspecUlp);
13532                 double                  result          (0.0);
13533
13534                 if (y.isZero())
13535                         return false;
13536
13537                 if (getFlavor() == 0)
13538                 {
13539                         result = (xd / yd);
13540                 }
13541                 else if (getFlavor() == 1)
13542                 {
13543                         const double    invyd   (1.0 / yd);
13544                         const fp16type  invy    (invyd);
13545
13546                         result = (xd * invy.asDouble());
13547                 }
13548                 else
13549                 {
13550                         TCU_THROW(InternalError, "Unknown flavor");
13551                 }
13552
13553                 out[0] = fp16type(result).bits();
13554                 min[0] = getMin(result, ulpCnt);
13555                 max[0] = getMax(result, ulpCnt);
13556
13557                 return true;
13558         }
13559 };
13560
13561 struct fp16Atan2 : public fp16PerComponent
13562 {
13563         fp16Atan2() : fp16PerComponent()
13564         {
13565                 flavorNames.push_back("DoubleCalc");
13566                 flavorNames.push_back("DoubleCalc_PI");
13567         }
13568
13569         virtual double getULPs(vector<const deFloat16*>& in)
13570         {
13571                 DE_UNREF(in);
13572
13573                 return 2 * 5.0; // This is not a precision test. Value is not from spec
13574         }
13575
13576         template<class fp16type>
13577         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13578         {
13579                 const fp16type  x               (*in[0]);
13580                 const fp16type  y               (*in[1]);
13581                 const double    xd              (x.asDouble());
13582                 const double    yd              (y.asDouble());
13583                 double                  result  (0.0);
13584
13585                 if (x.isZero() && y.isZero())
13586                         return false;
13587
13588                 if (getFlavor() == 0)
13589                 {
13590                         result  = deAtan2(xd, yd);
13591                 }
13592                 else if (getFlavor() == 1)
13593                 {
13594                         const double    ulps    (2.0 * 5.0); // This is not a precision test. Value is not from spec
13595                         const double    eps             (floatFormat16.ulp(DE_PI_DOUBLE, ulps));
13596
13597                         result  = deAtan2(xd, yd);
13598
13599                         if (de::inRange(deAbs(result), DE_PI_DOUBLE - eps, DE_PI_DOUBLE + eps))
13600                                 result  = -result;
13601                 }
13602                 else
13603                 {
13604                         TCU_THROW(InternalError, "Unknown flavor");
13605                 }
13606
13607                 out[0] = fp16type(result).bits();
13608                 min[0] = getMin(result, getULPs(in));
13609                 max[0] = getMax(result, getULPs(in));
13610
13611                 return true;
13612         }
13613 };
13614
13615 struct fp16Pow : public fp16PerComponent
13616 {
13617         fp16Pow() : fp16PerComponent()
13618         {
13619                 flavorNames.push_back("Pow");
13620                 flavorNames.push_back("PowLog2");
13621                 flavorNames.push_back("PowLog2FP16");
13622         }
13623
13624         template<class fp16type>
13625         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13626         {
13627                 const fp16type  x               (*in[0]);
13628                 const fp16type  y               (*in[1]);
13629                 const double    xd              (x.asDouble());
13630                 const double    yd              (y.asDouble());
13631                 const double    logxeps (de::inRange(deAbs(xd), 0.5, 2.0) ? deLdExp(1.0, -7) : floatFormat16.ulp(deLog2(xd), 3.0));
13632                 const double    ulps1   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) - logxeps)));
13633                 const double    ulps2   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) + logxeps)));
13634                 const double    ulps    (deMax(deAbs(ulps1), deAbs(ulps2)));
13635                 double                  result  (0.0);
13636
13637                 if (xd < 0.0)
13638                         return false;
13639
13640                 if (x.isZero() && yd <= 0.0)
13641                         return false;
13642
13643                 if (getFlavor() == 0)
13644                 {
13645                         result = dePow(xd, yd);
13646                 }
13647                 else if (getFlavor() == 1)
13648                 {
13649                         const double    l2d     (deLog2(xd));
13650                         const double    e2d     (deExp2(yd * l2d));
13651
13652                         result = e2d;
13653                 }
13654                 else if (getFlavor() == 2)
13655                 {
13656                         const double    l2d     (deLog2(xd));
13657                         const fp16type  l2      (l2d);
13658                         const double    e2d     (deExp2(yd * l2.asDouble()));
13659                         const fp16type  e2      (e2d);
13660
13661                         result = e2.asDouble();
13662                 }
13663                 else
13664                 {
13665                         TCU_THROW(InternalError, "Unknown flavor");
13666                 }
13667
13668                 out[0] = fp16type(result).bits();
13669                 min[0] = getMin(result, ulps);
13670                 max[0] = getMax(result, ulps);
13671
13672                 return true;
13673         }
13674 };
13675
13676 struct fp16FMin : public fp16PerComponent
13677 {
13678         template<class fp16type>
13679         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13680         {
13681                 const fp16type  x               (*in[0]);
13682                 const fp16type  y               (*in[1]);
13683                 const double    xd              (x.asDouble());
13684                 const double    yd              (y.asDouble());
13685                 const double    result  (deMin(xd, yd));
13686
13687                 if (x.isNaN() || y.isNaN())
13688                         return false;
13689
13690                 out[0] = fp16type(result).bits();
13691                 min[0] = getMin(result, getULPs(in));
13692                 max[0] = getMax(result, getULPs(in));
13693
13694                 return true;
13695         }
13696 };
13697
13698 struct fp16FMax : public fp16PerComponent
13699 {
13700         template<class fp16type>
13701         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13702         {
13703                 const fp16type  x               (*in[0]);
13704                 const fp16type  y               (*in[1]);
13705                 const double    xd              (x.asDouble());
13706                 const double    yd              (y.asDouble());
13707                 const double    result  (deMax(xd, yd));
13708
13709                 if (x.isNaN() || y.isNaN())
13710                         return false;
13711
13712                 out[0] = fp16type(result).bits();
13713                 min[0] = getMin(result, getULPs(in));
13714                 max[0] = getMax(result, getULPs(in));
13715
13716                 return true;
13717         }
13718 };
13719
13720 struct fp16Step : public fp16PerComponent
13721 {
13722         template<class fp16type>
13723         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13724         {
13725                 const fp16type  edge    (*in[0]);
13726                 const fp16type  x               (*in[1]);
13727                 const double    edged   (edge.asDouble());
13728                 const double    xd              (x.asDouble());
13729                 const double    result  (deStep(edged, xd));
13730
13731                 out[0] = fp16type(result).bits();
13732                 min[0] = getMin(result, getULPs(in));
13733                 max[0] = getMax(result, getULPs(in));
13734
13735                 return true;
13736         }
13737 };
13738
13739 struct fp16Ldexp : public fp16PerComponent
13740 {
13741         template<class fp16type>
13742         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13743         {
13744                 const fp16type  x               (*in[0]);
13745                 const fp16type  y               (*in[1]);
13746                 const double    xd              (x.asDouble());
13747                 const int               yd              (static_cast<int>(deTrunc(y.asDouble())));
13748                 const double    result  (deLdExp(xd, yd));
13749
13750                 if (y.isNaN() || y.isInf() || y.isDenorm() || yd < -14 || yd > 15)
13751                         return false;
13752
13753                 // Spec: "If this product is too large to be represented in the floating-point type, the result is undefined."
13754                 if (fp16type(result).isInf())
13755                         return false;
13756
13757                 out[0] = fp16type(result).bits();
13758                 min[0] = getMin(result, getULPs(in));
13759                 max[0] = getMax(result, getULPs(in));
13760
13761                 return true;
13762         }
13763 };
13764
13765 struct fp16FClamp : public fp16PerComponent
13766 {
13767         template<class fp16type>
13768         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13769         {
13770                 const fp16type  x               (*in[0]);
13771                 const fp16type  minVal  (*in[1]);
13772                 const fp16type  maxVal  (*in[2]);
13773                 const double    xd              (x.asDouble());
13774                 const double    minVald (minVal.asDouble());
13775                 const double    maxVald (maxVal.asDouble());
13776                 const double    result  (deClamp(xd, minVald, maxVald));
13777
13778                 if (minVal.isNaN() || maxVal.isNaN() || minVald > maxVald)
13779                         return false;
13780
13781                 out[0] = fp16type(result).bits();
13782                 min[0] = getMin(result, getULPs(in));
13783                 max[0] = getMax(result, getULPs(in));
13784
13785                 return true;
13786         }
13787 };
13788
13789 struct fp16FMix : public fp16PerComponent
13790 {
13791         fp16FMix() : fp16PerComponent()
13792         {
13793                 flavorNames.push_back("DoubleCalc");
13794                 flavorNames.push_back("EmulatingFP16");
13795                 flavorNames.push_back("EmulatingFP16YminusX");
13796         }
13797
13798         template<class fp16type>
13799         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13800         {
13801                 const fp16type  x               (*in[0]);
13802                 const fp16type  y               (*in[1]);
13803                 const fp16type  a               (*in[2]);
13804                 const double    ulps    (8.0); // This is not a precision test. Value is not from spec
13805                 double                  result  (0.0);
13806
13807                 if (getFlavor() == 0)
13808                 {
13809                         const double    xd              (x.asDouble());
13810                         const double    yd              (y.asDouble());
13811                         const double    ad              (a.asDouble());
13812                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13813                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13814                         const double    eps             (xeps + yeps);
13815
13816                         result = deMix(xd, yd, ad);
13817                         min[0] = result - eps;
13818                         max[0] = result + eps;
13819                 }
13820                 else if (getFlavor() == 1)
13821                 {
13822                         const double    xd              (x.asDouble());
13823                         const double    yd              (y.asDouble());
13824                         const double    ad              (a.asDouble());
13825                         const fp16type  am              (1.0 - ad);
13826                         const double    amd             (am.asDouble());
13827                         const fp16type  xam             (xd * amd);
13828                         const double    xamd    (xam.asDouble());
13829                         const fp16type  ya              (yd * ad);
13830                         const double    yad             (ya.asDouble());
13831                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13832                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13833                         const double    eps             (xeps + yeps);
13834
13835                         result = xamd + yad;
13836                         min[0] = result - eps;
13837                         max[0] = result + eps;
13838                 }
13839                 else if (getFlavor() == 2)
13840                 {
13841                         const double    xd              (x.asDouble());
13842                         const double    yd              (y.asDouble());
13843                         const double    ad              (a.asDouble());
13844                         const fp16type  ymx             (yd - xd);
13845                         const double    ymxd    (ymx.asDouble());
13846                         const fp16type  ymxa    (ymxd * ad);
13847                         const double    ymxad   (ymxa.asDouble());
13848                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13849                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13850                         const double    eps             (xeps + yeps);
13851
13852                         result = xd + ymxad;
13853                         min[0] = result - eps;
13854                         max[0] = result + eps;
13855                 }
13856                 else
13857                 {
13858                         TCU_THROW(InternalError, "Unknown flavor");
13859                 }
13860
13861                 out[0] = fp16type(result).bits();
13862
13863                 return true;
13864         }
13865 };
13866
13867 struct fp16SmoothStep : public fp16PerComponent
13868 {
13869         fp16SmoothStep() : fp16PerComponent()
13870         {
13871                 flavorNames.push_back("FloatCalc");
13872                 flavorNames.push_back("EmulatingFP16");
13873                 flavorNames.push_back("EmulatingFP16WClamp");
13874         }
13875
13876         virtual double getULPs(vector<const deFloat16*>& in)
13877         {
13878                 DE_UNREF(in);
13879
13880                 return 4.0; // This is not a precision test. Value is not from spec
13881         }
13882
13883         template<class fp16type>
13884         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13885         {
13886                 const fp16type  edge0   (*in[0]);
13887                 const fp16type  edge1   (*in[1]);
13888                 const fp16type  x               (*in[2]);
13889                 double                  result  (0.0);
13890
13891                 if (edge0.isNaN() || edge1.isNaN() || x.isNaN() || edge0.asDouble() >= edge1.asDouble())
13892                         return false;
13893
13894                 if (edge0.isInf() || edge1.isInf() || x.isInf())
13895                         return false;
13896
13897                 if (getFlavor() == 0)
13898                 {
13899                         const float     edge0d  (edge0.asFloat());
13900                         const float     edge1d  (edge1.asFloat());
13901                         const float     xd              (x.asFloat());
13902                         const float     sstep   (deFloatSmoothStep(edge0d, edge1d, xd));
13903
13904                         result = sstep;
13905                 }
13906                 else if (getFlavor() == 1)
13907                 {
13908                         const double    edge0d  (edge0.asDouble());
13909                         const double    edge1d  (edge1.asDouble());
13910                         const double    xd              (x.asDouble());
13911
13912                         if (xd <= edge0d)
13913                                 result = 0.0;
13914                         else if (xd >= edge1d)
13915                                 result = 1.0;
13916                         else
13917                         {
13918                                 const fp16type  a       (xd - edge0d);
13919                                 const fp16type  b       (edge1d - edge0d);
13920                                 const fp16type  t       (a.asDouble() / b.asDouble());
13921                                 const fp16type  t2      (2.0 * t.asDouble());
13922                                 const fp16type  t3      (3.0 - t2.asDouble());
13923                                 const fp16type  t4      (t.asDouble() * t3.asDouble());
13924                                 const fp16type  t5      (t.asDouble() * t4.asDouble());
13925
13926                                 result = t5.asDouble();
13927                         }
13928                 }
13929                 else if (getFlavor() == 2)
13930                 {
13931                         const double    edge0d  (edge0.asDouble());
13932                         const double    edge1d  (edge1.asDouble());
13933                         const double    xd              (x.asDouble());
13934                         const fp16type  a       (xd - edge0d);
13935                         const fp16type  b       (edge1d - edge0d);
13936                         const fp16type  bi      (1.0 / b.asDouble());
13937                         const fp16type  t0      (a.asDouble() * bi.asDouble());
13938                         const double    tc      (deClamp(t0.asDouble(), 0.0, 1.0));
13939                         const fp16type  t       (tc);
13940                         const fp16type  t2      (2.0 * t.asDouble());
13941                         const fp16type  t3      (3.0 - t2.asDouble());
13942                         const fp16type  t4      (t.asDouble() * t3.asDouble());
13943                         const fp16type  t5      (t.asDouble() * t4.asDouble());
13944
13945                         result = t5.asDouble();
13946                 }
13947                 else
13948                 {
13949                         TCU_THROW(InternalError, "Unknown flavor");
13950                 }
13951
13952                 out[0] = fp16type(result).bits();
13953                 min[0] = getMin(result, getULPs(in));
13954                 max[0] = getMax(result, getULPs(in));
13955
13956                 return true;
13957         }
13958 };
13959
13960 struct fp16Fma : public fp16PerComponent
13961 {
13962         fp16Fma()
13963         {
13964                 flavorNames.push_back("DoubleCalc");
13965                 flavorNames.push_back("EmulatingFP16");
13966         }
13967
13968         virtual double getULPs(vector<const deFloat16*>& in)
13969         {
13970                 DE_UNREF(in);
13971
13972                 return 16.0;
13973         }
13974
13975         template<class fp16type>
13976         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13977         {
13978                 DE_ASSERT(in.size() == 3);
13979                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13980                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
13981                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
13982                 DE_ASSERT(getOutCompCount() > 0);
13983
13984                 const fp16type  a               (*in[0]);
13985                 const fp16type  b               (*in[1]);
13986                 const fp16type  c               (*in[2]);
13987                 double                  result  (0.0);
13988
13989                 if (getFlavor() == 0)
13990                 {
13991                         const double    ad      (a.asDouble());
13992                         const double    bd      (b.asDouble());
13993                         const double    cd      (c.asDouble());
13994
13995                         result  = deMadd(ad, bd, cd);
13996                 }
13997                 else if (getFlavor() == 1)
13998                 {
13999                         const double    ad      (a.asDouble());
14000                         const double    bd      (b.asDouble());
14001                         const double    cd      (c.asDouble());
14002                         const fp16type  ab      (ad * bd);
14003                         const fp16type  r       (ab.asDouble() + cd);
14004
14005                         result  = r.asDouble();
14006                 }
14007                 else
14008                 {
14009                         TCU_THROW(InternalError, "Unknown flavor");
14010                 }
14011
14012                 out[0] = fp16type(result).bits();
14013                 min[0] = getMin(result, getULPs(in));
14014                 max[0] = getMax(result, getULPs(in));
14015
14016                 return true;
14017         }
14018 };
14019
14020
14021 struct fp16AllComponents : public fp16PerComponent
14022 {
14023         bool            callOncePerComponent    ()      { return false; }
14024 };
14025
14026 struct fp16Length : public fp16AllComponents
14027 {
14028         fp16Length() : fp16AllComponents()
14029         {
14030                 flavorNames.push_back("EmulatingFP16");
14031                 flavorNames.push_back("DoubleCalc");
14032         }
14033
14034         virtual double getULPs(vector<const deFloat16*>& in)
14035         {
14036                 DE_UNREF(in);
14037
14038                 return 4.0;
14039         }
14040
14041         template<class fp16type>
14042         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14043         {
14044                 DE_ASSERT(getOutCompCount() == 1);
14045                 DE_ASSERT(in.size() == 1);
14046
14047                 double  result  (0.0);
14048
14049                 if (getFlavor() == 0)
14050                 {
14051                         fp16type        r       (0.0);
14052
14053                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14054                         {
14055                                 const fp16type  x       (in[0][componentNdx]);
14056                                 const fp16type  q       (x.asDouble() * x.asDouble());
14057
14058                                 r = fp16type(r.asDouble() + q.asDouble());
14059                         }
14060
14061                         result = deSqrt(r.asDouble());
14062
14063                         out[0] = fp16type(result).bits();
14064                 }
14065                 else if (getFlavor() == 1)
14066                 {
14067                         double  r       (0.0);
14068
14069                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14070                         {
14071                                 const fp16type  x       (in[0][componentNdx]);
14072                                 const double    q       (x.asDouble() * x.asDouble());
14073
14074                                 r += q;
14075                         }
14076
14077                         result = deSqrt(r);
14078
14079                         out[0] = fp16type(result).bits();
14080                 }
14081                 else
14082                 {
14083                         TCU_THROW(InternalError, "Unknown flavor");
14084                 }
14085
14086                 min[0] = getMin(result, getULPs(in));
14087                 max[0] = getMax(result, getULPs(in));
14088
14089                 return true;
14090         }
14091 };
14092
14093 struct fp16Distance : public fp16AllComponents
14094 {
14095         fp16Distance() : fp16AllComponents()
14096         {
14097                 flavorNames.push_back("EmulatingFP16");
14098                 flavorNames.push_back("DoubleCalc");
14099         }
14100
14101         virtual double getULPs(vector<const deFloat16*>& in)
14102         {
14103                 DE_UNREF(in);
14104
14105                 return 4.0;
14106         }
14107
14108         template<class fp16type>
14109         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14110         {
14111                 DE_ASSERT(getOutCompCount() == 1);
14112                 DE_ASSERT(in.size() == 2);
14113                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
14114
14115                 double  result  (0.0);
14116
14117                 if (getFlavor() == 0)
14118                 {
14119                         fp16type        r       (0.0);
14120
14121                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14122                         {
14123                                 const fp16type  x       (in[0][componentNdx]);
14124                                 const fp16type  y       (in[1][componentNdx]);
14125                                 const fp16type  d       (x.asDouble() - y.asDouble());
14126                                 const fp16type  q       (d.asDouble() * d.asDouble());
14127
14128                                 r = fp16type(r.asDouble() + q.asDouble());
14129                         }
14130
14131                         result = deSqrt(r.asDouble());
14132                 }
14133                 else if (getFlavor() == 1)
14134                 {
14135                         double  r       (0.0);
14136
14137                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14138                         {
14139                                 const fp16type  x       (in[0][componentNdx]);
14140                                 const fp16type  y       (in[1][componentNdx]);
14141                                 const double    d       (x.asDouble() - y.asDouble());
14142                                 const double    q       (d * d);
14143
14144                                 r += q;
14145                         }
14146
14147                         result = deSqrt(r);
14148                 }
14149                 else
14150                 {
14151                         TCU_THROW(InternalError, "Unknown flavor");
14152                 }
14153
14154                 out[0] = fp16type(result).bits();
14155                 min[0] = getMin(result, getULPs(in));
14156                 max[0] = getMax(result, getULPs(in));
14157
14158                 return true;
14159         }
14160 };
14161
14162 struct fp16Cross : public fp16AllComponents
14163 {
14164         fp16Cross() : fp16AllComponents()
14165         {
14166                 flavorNames.push_back("EmulatingFP16");
14167                 flavorNames.push_back("DoubleCalc");
14168         }
14169
14170         virtual double getULPs(vector<const deFloat16*>& in)
14171         {
14172                 DE_UNREF(in);
14173
14174                 return 4.0;
14175         }
14176
14177         template<class fp16type>
14178         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14179         {
14180                 DE_ASSERT(getOutCompCount() == 3);
14181                 DE_ASSERT(in.size() == 2);
14182                 DE_ASSERT(getArgCompCount(0) == 3);
14183                 DE_ASSERT(getArgCompCount(1) == 3);
14184
14185                 if (getFlavor() == 0)
14186                 {
14187                         const fp16type  x0              (in[0][0]);
14188                         const fp16type  x1              (in[0][1]);
14189                         const fp16type  x2              (in[0][2]);
14190                         const fp16type  y0              (in[1][0]);
14191                         const fp16type  y1              (in[1][1]);
14192                         const fp16type  y2              (in[1][2]);
14193                         const fp16type  x1y2    (x1.asDouble() * y2.asDouble());
14194                         const fp16type  y1x2    (y1.asDouble() * x2.asDouble());
14195                         const fp16type  x2y0    (x2.asDouble() * y0.asDouble());
14196                         const fp16type  y2x0    (y2.asDouble() * x0.asDouble());
14197                         const fp16type  x0y1    (x0.asDouble() * y1.asDouble());
14198                         const fp16type  y0x1    (y0.asDouble() * x1.asDouble());
14199
14200                         out[0] = fp16type(x1y2.asDouble() - y1x2.asDouble()).bits();
14201                         out[1] = fp16type(x2y0.asDouble() - y2x0.asDouble()).bits();
14202                         out[2] = fp16type(x0y1.asDouble() - y0x1.asDouble()).bits();
14203                 }
14204                 else if (getFlavor() == 1)
14205                 {
14206                         const fp16type  x0              (in[0][0]);
14207                         const fp16type  x1              (in[0][1]);
14208                         const fp16type  x2              (in[0][2]);
14209                         const fp16type  y0              (in[1][0]);
14210                         const fp16type  y1              (in[1][1]);
14211                         const fp16type  y2              (in[1][2]);
14212                         const double    x1y2    (x1.asDouble() * y2.asDouble());
14213                         const double    y1x2    (y1.asDouble() * x2.asDouble());
14214                         const double    x2y0    (x2.asDouble() * y0.asDouble());
14215                         const double    y2x0    (y2.asDouble() * x0.asDouble());
14216                         const double    x0y1    (x0.asDouble() * y1.asDouble());
14217                         const double    y0x1    (y0.asDouble() * x1.asDouble());
14218
14219                         out[0] = fp16type(x1y2 - y1x2).bits();
14220                         out[1] = fp16type(x2y0 - y2x0).bits();
14221                         out[2] = fp16type(x0y1 - y0x1).bits();
14222                 }
14223                 else
14224                 {
14225                         TCU_THROW(InternalError, "Unknown flavor");
14226                 }
14227
14228                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14229                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14230                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14231                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14232
14233                 return true;
14234         }
14235 };
14236
14237 struct fp16Normalize : public fp16AllComponents
14238 {
14239         fp16Normalize() : fp16AllComponents()
14240         {
14241                 flavorNames.push_back("EmulatingFP16");
14242                 flavorNames.push_back("DoubleCalc");
14243
14244                 // flavorNames will be extended later
14245         }
14246
14247         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14248         {
14249                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14250
14251                 if (argNo == 0 && argCompCount[argNo] == 0)
14252                 {
14253                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14254                         std::vector<int>        indices;
14255
14256                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14257                                 indices.push_back(static_cast<int>(componentNdx));
14258
14259                         m_permutations.reserve(maxPermutationsCount);
14260
14261                         permutationsFlavorStart = flavorNames.size();
14262
14263                         do
14264                         {
14265                                 tcu::UVec4      permutation;
14266                                 std::string     name            = "Permutted_";
14267
14268                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14269                                 {
14270                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14271                                         name += de::toString(indices[componentNdx]);
14272                                 }
14273
14274                                 m_permutations.push_back(permutation);
14275                                 flavorNames.push_back(name);
14276
14277                         } while(std::next_permutation(indices.begin(), indices.end()));
14278
14279                         permutationsFlavorEnd = flavorNames.size();
14280                 }
14281
14282                 fp16AllComponents::setArgCompCount(argNo, compCount);
14283         }
14284         virtual double getULPs(vector<const deFloat16*>& in)
14285         {
14286                 DE_UNREF(in);
14287
14288                 return 8.0;
14289         }
14290
14291         template<class fp16type>
14292         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14293         {
14294                 DE_ASSERT(in.size() == 1);
14295                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14296
14297                 if (getFlavor() == 0)
14298                 {
14299                         fp16type        r(0.0);
14300
14301                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14302                         {
14303                                 const fp16type  x       (in[0][componentNdx]);
14304                                 const fp16type  q       (x.asDouble() * x.asDouble());
14305
14306                                 r = fp16type(r.asDouble() + q.asDouble());
14307                         }
14308
14309                         r = fp16type(deSqrt(r.asDouble()));
14310
14311                         if (r.isZero())
14312                                 return false;
14313
14314                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14315                         {
14316                                 const fp16type  x       (in[0][componentNdx]);
14317
14318                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14319                         }
14320                 }
14321                 else if (getFlavor() == 1)
14322                 {
14323                         double  r(0.0);
14324
14325                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14326                         {
14327                                 const fp16type  x       (in[0][componentNdx]);
14328                                 const double    q       (x.asDouble() * x.asDouble());
14329
14330                                 r += q;
14331                         }
14332
14333                         r = deSqrt(r);
14334
14335                         if (r == 0)
14336                                 return false;
14337
14338                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14339                         {
14340                                 const fp16type  x       (in[0][componentNdx]);
14341
14342                                 out[componentNdx] = fp16type(x.asDouble() / r).bits();
14343                         }
14344                 }
14345                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14346                 {
14347                         const int                       compCount               (static_cast<int>(getArgCompCount(0)));
14348                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14349                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14350                         fp16type                        r                               (0.0);
14351
14352                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14353                         {
14354                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14355                                 const fp16type  x                               (in[0][componentNdx]);
14356                                 const fp16type  q                               (x.asDouble() * x.asDouble());
14357
14358                                 r = fp16type(r.asDouble() + q.asDouble());
14359                         }
14360
14361                         r = fp16type(deSqrt(r.asDouble()));
14362
14363                         if (r.isZero())
14364                                 return false;
14365
14366                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14367                         {
14368                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14369                                 const fp16type  x                               (in[0][componentNdx]);
14370
14371                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14372                         }
14373                 }
14374                 else
14375                 {
14376                         TCU_THROW(InternalError, "Unknown flavor");
14377                 }
14378
14379                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14380                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14381                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14382                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14383
14384                 return true;
14385         }
14386
14387 private:
14388         std::vector<tcu::UVec4> m_permutations;
14389         size_t                                  permutationsFlavorStart;
14390         size_t                                  permutationsFlavorEnd;
14391 };
14392
14393 struct fp16FaceForward : public fp16AllComponents
14394 {
14395         virtual double getULPs(vector<const deFloat16*>& in)
14396         {
14397                 DE_UNREF(in);
14398
14399                 return 4.0;
14400         }
14401
14402         template<class fp16type>
14403         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14404         {
14405                 DE_ASSERT(in.size() == 3);
14406                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14407                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14408                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
14409
14410                 fp16type        dp(0.0);
14411
14412                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14413                 {
14414                         const fp16type  x       (in[1][componentNdx]);
14415                         const fp16type  y       (in[2][componentNdx]);
14416                         const double    xd      (x.asDouble());
14417                         const double    yd      (y.asDouble());
14418                         const fp16type  q       (xd * yd);
14419
14420                         dp = fp16type(dp.asDouble() + q.asDouble());
14421                 }
14422
14423                 if (dp.isNaN() || dp.isZero())
14424                         return false;
14425
14426                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14427                 {
14428                         const fp16type  n       (in[0][componentNdx]);
14429
14430                         out[componentNdx] = (dp.signBit() == 1) ? n.bits() : fp16type(-n.asDouble()).bits();
14431                 }
14432
14433                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14434                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14435                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14436                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14437
14438                 return true;
14439         }
14440 };
14441
14442 struct fp16Reflect : public fp16AllComponents
14443 {
14444         fp16Reflect() : fp16AllComponents()
14445         {
14446                 flavorNames.push_back("EmulatingFP16");
14447                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14448                 flavorNames.push_back("FloatCalc");
14449                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14450                 flavorNames.push_back("EmulatingFP16+2Nfirst");
14451                 flavorNames.push_back("EmulatingFP16+2Ifirst");
14452         }
14453
14454         virtual double getULPs(vector<const deFloat16*>& in)
14455         {
14456                 DE_UNREF(in);
14457
14458                 return 256.0; // This is not a precision test. Value is not from spec
14459         }
14460
14461         template<class fp16type>
14462         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14463         {
14464                 DE_ASSERT(in.size() == 2);
14465                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14466                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14467
14468                 if (getFlavor() < 4)
14469                 {
14470                         const bool      keepZeroSign    ((flavor & 1) != 0 ? true : false);
14471                         const bool      floatCalc               ((flavor & 2) != 0 ? true : false);
14472
14473                         if (floatCalc)
14474                         {
14475                                 float   dp(0.0f);
14476
14477                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14478                                 {
14479                                         const fp16type  i       (in[0][componentNdx]);
14480                                         const fp16type  n       (in[1][componentNdx]);
14481                                         const float             id      (i.asFloat());
14482                                         const float             nd      (n.asFloat());
14483                                         const float             qd      (id * nd);
14484
14485                                         if (keepZeroSign)
14486                                                 dp = (componentNdx == 0) ? qd : dp + qd;
14487                                         else
14488                                                 dp = dp + qd;
14489                                 }
14490
14491                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14492                                 {
14493                                         const fp16type  i               (in[0][componentNdx]);
14494                                         const fp16type  n               (in[1][componentNdx]);
14495                                         const float             dpnd    (dp * n.asFloat());
14496                                         const float             dpn2d   (2.0f * dpnd);
14497                                         const float             idpn2d  (i.asFloat() - dpn2d);
14498                                         const fp16type  result  (idpn2d);
14499
14500                                         out[componentNdx] = result.bits();
14501                                 }
14502                         }
14503                         else
14504                         {
14505                                 fp16type        dp(0.0);
14506
14507                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14508                                 {
14509                                         const fp16type  i       (in[0][componentNdx]);
14510                                         const fp16type  n       (in[1][componentNdx]);
14511                                         const double    id      (i.asDouble());
14512                                         const double    nd      (n.asDouble());
14513                                         const fp16type  q       (id * nd);
14514
14515                                         if (keepZeroSign)
14516                                                 dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14517                                         else
14518                                                 dp = fp16type(dp.asDouble() + q.asDouble());
14519                                 }
14520
14521                                 if (dp.isNaN())
14522                                         return false;
14523
14524                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14525                                 {
14526                                         const fp16type  i               (in[0][componentNdx]);
14527                                         const fp16type  n               (in[1][componentNdx]);
14528                                         const fp16type  dpn             (dp.asDouble() * n.asDouble());
14529                                         const fp16type  dpn2    (2 * dpn.asDouble());
14530                                         const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14531
14532                                         out[componentNdx] = idpn2.bits();
14533                                 }
14534                         }
14535                 }
14536                 else if (getFlavor() == 4)
14537                 {
14538                         fp16type        dp(0.0);
14539
14540                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14541                         {
14542                                 const fp16type  i       (in[0][componentNdx]);
14543                                 const fp16type  n       (in[1][componentNdx]);
14544                                 const double    id      (i.asDouble());
14545                                 const double    nd      (n.asDouble());
14546                                 const fp16type  q       (id * nd);
14547
14548                                 dp = fp16type(dp.asDouble() + q.asDouble());
14549                         }
14550
14551                         if (dp.isNaN())
14552                                 return false;
14553
14554                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14555                         {
14556                                 const fp16type  i               (in[0][componentNdx]);
14557                                 const fp16type  n               (in[1][componentNdx]);
14558                                 const fp16type  n2              (2 * n.asDouble());
14559                                 const fp16type  dpn2    (dp.asDouble() * n2.asDouble());
14560                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14561
14562                                 out[componentNdx] = idpn2.bits();
14563                         }
14564                 }
14565                 else if (getFlavor() == 5)
14566                 {
14567                         fp16type        dp2(0.0);
14568
14569                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14570                         {
14571                                 const fp16type  i       (in[0][componentNdx]);
14572                                 const fp16type  n       (in[1][componentNdx]);
14573                                 const fp16type  i2      (2.0 * i.asDouble());
14574                                 const double    i2d     (i2.asDouble());
14575                                 const double    nd      (n.asDouble());
14576                                 const fp16type  q       (i2d * nd);
14577
14578                                 dp2 = fp16type(dp2.asDouble() + q.asDouble());
14579                         }
14580
14581                         if (dp2.isNaN())
14582                                 return false;
14583
14584                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14585                         {
14586                                 const fp16type  i               (in[0][componentNdx]);
14587                                 const fp16type  n               (in[1][componentNdx]);
14588                                 const fp16type  dpn2    (dp2.asDouble() * n.asDouble());
14589                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14590
14591                                 out[componentNdx] = idpn2.bits();
14592                         }
14593                 }
14594                 else
14595                 {
14596                         TCU_THROW(InternalError, "Unknown flavor");
14597                 }
14598
14599                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14600                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14601                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14602                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14603
14604                 return true;
14605         }
14606 };
14607
14608 struct fp16Refract : public fp16AllComponents
14609 {
14610         fp16Refract() : fp16AllComponents()
14611         {
14612                 flavorNames.push_back("EmulatingFP16");
14613                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14614                 flavorNames.push_back("FloatCalc");
14615                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14616         }
14617
14618         virtual double getULPs(vector<const deFloat16*>& in)
14619         {
14620                 DE_UNREF(in);
14621
14622                 return 8192.0; // This is not a precision test. Value is not from spec
14623         }
14624
14625         template<class fp16type>
14626         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14627         {
14628                 DE_ASSERT(in.size() == 3);
14629                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14630                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14631                 DE_ASSERT(getArgCompCount(2) == 1);
14632
14633                 const bool              keepZeroSign    ((flavor & 1) != 0 ? true : false);
14634                 const bool              doubleCalc              ((flavor & 2) != 0 ? true : false);
14635                 const fp16type  eta                             (*in[2]);
14636
14637                 if (doubleCalc)
14638                 {
14639                         double  dp      (0.0);
14640
14641                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14642                         {
14643                                 const fp16type  i       (in[0][componentNdx]);
14644                                 const fp16type  n       (in[1][componentNdx]);
14645                                 const double    id      (i.asDouble());
14646                                 const double    nd      (n.asDouble());
14647                                 const double    qd      (id * nd);
14648
14649                                 if (keepZeroSign)
14650                                         dp = (componentNdx == 0) ? qd : dp + qd;
14651                                 else
14652                                         dp = dp + qd;
14653                         }
14654
14655                         const double    eta2    (eta.asDouble() * eta.asDouble());
14656                         const double    dp2             (dp * dp);
14657                         const double    dp1             (1.0 - dp2);
14658                         const double    dpe             (eta2 * dp1);
14659                         const double    k               (1.0 - dpe);
14660
14661                         if (k < 0.0)
14662                         {
14663                                 const fp16type  zero    (0.0);
14664
14665                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14666                                         out[componentNdx] = zero.bits();
14667                         }
14668                         else
14669                         {
14670                                 const double    sk      (deSqrt(k));
14671
14672                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14673                                 {
14674                                         const fp16type  i               (in[0][componentNdx]);
14675                                         const fp16type  n               (in[1][componentNdx]);
14676                                         const double    etai    (i.asDouble() * eta.asDouble());
14677                                         const double    etadp   (eta.asDouble() * dp);
14678                                         const double    etadpk  (etadp + sk);
14679                                         const double    etadpkn (etadpk * n.asDouble());
14680                                         const double    full    (etai - etadpkn);
14681                                         const fp16type  result  (full);
14682
14683                                         if (result.isInf())
14684                                                 return false;
14685
14686                                         out[componentNdx] = result.bits();
14687                                 }
14688                         }
14689                 }
14690                 else
14691                 {
14692                         fp16type        dp      (0.0);
14693
14694                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14695                         {
14696                                 const fp16type  i       (in[0][componentNdx]);
14697                                 const fp16type  n       (in[1][componentNdx]);
14698                                 const double    id      (i.asDouble());
14699                                 const double    nd      (n.asDouble());
14700                                 const fp16type  q       (id * nd);
14701
14702                                 if (keepZeroSign)
14703                                         dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14704                                 else
14705                                         dp = fp16type(dp.asDouble() + q.asDouble());
14706                         }
14707
14708                         if (dp.isNaN())
14709                                 return false;
14710
14711                         const fp16type  eta2(eta.asDouble() * eta.asDouble());
14712                         const fp16type  dp2     (dp.asDouble() * dp.asDouble());
14713                         const fp16type  dp1     (1.0 - dp2.asDouble());
14714                         const fp16type  dpe     (eta2.asDouble() * dp1.asDouble());
14715                         const fp16type  k       (1.0 - dpe.asDouble());
14716
14717                         if (k.asDouble() < 0.0)
14718                         {
14719                                 const fp16type  zero    (0.0);
14720
14721                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14722                                         out[componentNdx] = zero.bits();
14723                         }
14724                         else
14725                         {
14726                                 const fp16type  sk      (deSqrt(k.asDouble()));
14727
14728                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14729                                 {
14730                                         const fp16type  i               (in[0][componentNdx]);
14731                                         const fp16type  n               (in[1][componentNdx]);
14732                                         const fp16type  etai    (i.asDouble() * eta.asDouble());
14733                                         const fp16type  etadp   (eta.asDouble() * dp.asDouble());
14734                                         const fp16type  etadpk  (etadp.asDouble() + sk.asDouble());
14735                                         const fp16type  etadpkn (etadpk.asDouble() * n.asDouble());
14736                                         const fp16type  full    (etai.asDouble() - etadpkn.asDouble());
14737
14738                                         if (full.isNaN() || full.isInf())
14739                                                 return false;
14740
14741                                         out[componentNdx] = full.bits();
14742                                 }
14743                         }
14744                 }
14745
14746                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14747                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14748                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14749                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14750
14751                 return true;
14752         }
14753 };
14754
14755 struct fp16Dot : public fp16AllComponents
14756 {
14757         fp16Dot() : fp16AllComponents()
14758         {
14759                 flavorNames.push_back("EmulatingFP16");
14760                 flavorNames.push_back("FloatCalc");
14761                 flavorNames.push_back("DoubleCalc");
14762
14763                 // flavorNames will be extended later
14764         }
14765
14766         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14767         {
14768                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14769
14770                 if (argNo == 0 && argCompCount[argNo] == 0)
14771                 {
14772                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14773                         std::vector<int>        indices;
14774
14775                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14776                                 indices.push_back(static_cast<int>(componentNdx));
14777
14778                         m_permutations.reserve(maxPermutationsCount);
14779
14780                         permutationsFlavorStart = flavorNames.size();
14781
14782                         do
14783                         {
14784                                 tcu::UVec4      permutation;
14785                                 std::string     name            = "Permutted_";
14786
14787                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14788                                 {
14789                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14790                                         name += de::toString(indices[componentNdx]);
14791                                 }
14792
14793                                 m_permutations.push_back(permutation);
14794                                 flavorNames.push_back(name);
14795
14796                         } while(std::next_permutation(indices.begin(), indices.end()));
14797
14798                         permutationsFlavorEnd = flavorNames.size();
14799                 }
14800
14801                 fp16AllComponents::setArgCompCount(argNo, compCount);
14802         }
14803
14804         virtual double  getULPs(vector<const deFloat16*>& in)
14805         {
14806                 DE_UNREF(in);
14807
14808                 return 16.0; // This is not a precision test. Value is not from spec
14809         }
14810
14811         template<class fp16type>
14812         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14813         {
14814                 DE_ASSERT(in.size() == 2);
14815                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
14816                 DE_ASSERT(getOutCompCount() == 1);
14817
14818                 double  result  (0.0);
14819                 double  eps             (0.0);
14820
14821                 if (getFlavor() == 0)
14822                 {
14823                         fp16type        dp      (0.0);
14824
14825                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14826                         {
14827                                 const fp16type  x       (in[0][componentNdx]);
14828                                 const fp16type  y       (in[1][componentNdx]);
14829                                 const fp16type  q       (x.asDouble() * y.asDouble());
14830
14831                                 dp = fp16type(dp.asDouble() + q.asDouble());
14832                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14833                         }
14834
14835                         result = dp.asDouble();
14836                 }
14837                 else if (getFlavor() == 1)
14838                 {
14839                         float   dp      (0.0);
14840
14841                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14842                         {
14843                                 const fp16type  x       (in[0][componentNdx]);
14844                                 const fp16type  y       (in[1][componentNdx]);
14845                                 const float             q       (x.asFloat() * y.asFloat());
14846
14847                                 dp += q;
14848                                 eps += floatFormat16.ulp(static_cast<double>(q), 2.0);
14849                         }
14850
14851                         result = dp;
14852                 }
14853                 else if (getFlavor() == 2)
14854                 {
14855                         double  dp      (0.0);
14856
14857                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14858                         {
14859                                 const fp16type  x       (in[0][componentNdx]);
14860                                 const fp16type  y       (in[1][componentNdx]);
14861                                 const double    q       (x.asDouble() * y.asDouble());
14862
14863                                 dp += q;
14864                                 eps += floatFormat16.ulp(q, 2.0);
14865                         }
14866
14867                         result = dp;
14868                 }
14869                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14870                 {
14871                         const int                       compCount               (static_cast<int>(getArgCompCount(1)));
14872                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14873                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14874                         fp16type                        dp                              (0.0);
14875
14876                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14877                         {
14878                                 const size_t            componentNdx    (permutation[permComponentNdx]);
14879                                 const fp16type          x                               (in[0][componentNdx]);
14880                                 const fp16type          y                               (in[1][componentNdx]);
14881                                 const fp16type          q                               (x.asDouble() * y.asDouble());
14882
14883                                 dp = fp16type(dp.asDouble() + q.asDouble());
14884                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14885                         }
14886
14887                         result = dp.asDouble();
14888                 }
14889                 else
14890                 {
14891                         TCU_THROW(InternalError, "Unknown flavor");
14892                 }
14893
14894                 out[0] = fp16type(result).bits();
14895                 min[0] = result - eps;
14896                 max[0] = result + eps;
14897
14898                 return true;
14899         }
14900
14901 private:
14902         std::vector<tcu::UVec4> m_permutations;
14903         size_t                                  permutationsFlavorStart;
14904         size_t                                  permutationsFlavorEnd;
14905 };
14906
14907 struct fp16VectorTimesScalar : public fp16AllComponents
14908 {
14909         virtual double getULPs(vector<const deFloat16*>& in)
14910         {
14911                 DE_UNREF(in);
14912
14913                 return 2.0;
14914         }
14915
14916         template<class fp16type>
14917         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14918         {
14919                 DE_ASSERT(in.size() == 2);
14920                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14921                 DE_ASSERT(getArgCompCount(1) == 1);
14922
14923                 fp16type        s       (*in[1]);
14924
14925                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14926                 {
14927                         const fp16type  x          (in[0][componentNdx]);
14928                         const double    result (s.asDouble() * x.asDouble());
14929                         const fp16type  m          (result);
14930
14931                         out[componentNdx] = m.bits();
14932                         min[componentNdx] = getMin(result, getULPs(in));
14933                         max[componentNdx] = getMax(result, getULPs(in));
14934                 }
14935
14936                 return true;
14937         }
14938 };
14939
14940 struct fp16MatrixBase : public fp16AllComponents
14941 {
14942         deUint32                getComponentValidity                    ()
14943         {
14944                 return static_cast<deUint32>(-1);
14945         }
14946
14947         inline size_t   getNdx                                                  (const size_t rowCount, const size_t col, const size_t row)
14948         {
14949                 const size_t minComponentCount  = 0;
14950                 const size_t maxComponentCount  = 3;
14951                 const size_t alignedRowsCount   = (rowCount == 3) ? 4 : rowCount;
14952
14953                 DE_ASSERT(de::inRange(rowCount, minComponentCount + 1, maxComponentCount + 1));
14954                 DE_ASSERT(de::inRange(col, minComponentCount, maxComponentCount));
14955                 DE_ASSERT(de::inBounds(row, minComponentCount, rowCount));
14956                 DE_UNREF(minComponentCount);
14957                 DE_UNREF(maxComponentCount);
14958
14959                 return col * alignedRowsCount + row;
14960         }
14961
14962         deUint32                getComponentMatrixValidityMask  (size_t cols, size_t rows)
14963         {
14964                 deUint32        result  = 0u;
14965
14966                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14967                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14968                         {
14969                                 const size_t bitNdx = getNdx(rows, colNdx, rowNdx);
14970
14971                                 DE_ASSERT(bitNdx < sizeof(result) * 8);
14972
14973                                 result |= (1<<bitNdx);
14974                         }
14975
14976                 return result;
14977         }
14978 };
14979
14980 template<size_t cols, size_t rows>
14981 struct fp16Transpose : public fp16MatrixBase
14982 {
14983         virtual double getULPs(vector<const deFloat16*>& in)
14984         {
14985                 DE_UNREF(in);
14986
14987                 return 1.0;
14988         }
14989
14990         deUint32        getComponentValidity    ()
14991         {
14992                 return getComponentMatrixValidityMask(rows, cols);
14993         }
14994
14995         template<class fp16type>
14996         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14997         {
14998                 DE_ASSERT(in.size() == 1);
14999
15000                 const size_t            alignedCols     = (cols == 3) ? 4 : cols;
15001                 const size_t            alignedRows     = (rows == 3) ? 4 : rows;
15002                 vector<deFloat16>       output          (alignedCols * alignedRows, 0);
15003
15004                 DE_ASSERT(output.size() == alignedCols * alignedRows);
15005
15006                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15007                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15008                                 output[rowNdx * alignedCols + colNdx] = in[0][colNdx * alignedRows + rowNdx];
15009
15010                 deMemcpy(out, &output[0], sizeof(deFloat16) * output.size());
15011                 deMemcpy(min, &output[0], sizeof(deFloat16) * output.size());
15012                 deMemcpy(max, &output[0], sizeof(deFloat16) * output.size());
15013
15014                 return true;
15015         }
15016 };
15017
15018 template<size_t cols, size_t rows>
15019 struct fp16MatrixTimesScalar : public fp16MatrixBase
15020 {
15021         virtual double getULPs(vector<const deFloat16*>& in)
15022         {
15023                 DE_UNREF(in);
15024
15025                 return 4.0;
15026         }
15027
15028         deUint32        getComponentValidity    ()
15029         {
15030                 return getComponentMatrixValidityMask(cols, rows);
15031         }
15032
15033         template<class fp16type>
15034         bool calc(vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15035         {
15036                 DE_ASSERT(in.size() == 2);
15037                 DE_ASSERT(getArgCompCount(1) == 1);
15038
15039                 const fp16type  y                       (in[1][0]);
15040                 const float             scalar          (y.asFloat());
15041                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15042                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15043
15044                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
15045                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
15046                 DE_UNREF(alignedCols);
15047
15048                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15049                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15050                         {
15051                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15052                                 const fp16type  x       (in[0][ndx]);
15053                                 const double    result  (scalar * x.asFloat());
15054
15055                                 out[ndx] = fp16type(result).bits();
15056                                 min[ndx] = getMin(result, getULPs(in));
15057                                 max[ndx] = getMax(result, getULPs(in));
15058                         }
15059
15060                 return true;
15061         }
15062 };
15063
15064 template<size_t cols, size_t rows>
15065 struct fp16VectorTimesMatrix : public fp16MatrixBase
15066 {
15067         fp16VectorTimesMatrix() : fp16MatrixBase()
15068         {
15069                 flavorNames.push_back("EmulatingFP16");
15070                 flavorNames.push_back("FloatCalc");
15071         }
15072
15073         virtual double getULPs (vector<const deFloat16*>& in)
15074         {
15075                 DE_UNREF(in);
15076
15077                 return (8.0 * cols);
15078         }
15079
15080         deUint32 getComponentValidity ()
15081         {
15082                 return getComponentMatrixValidityMask(cols, 1);
15083         }
15084
15085         template<class fp16type>
15086         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15087         {
15088                 DE_ASSERT(in.size() == 2);
15089
15090                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15091                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15092
15093                 DE_ASSERT(getOutCompCount() == cols);
15094                 DE_ASSERT(getArgCompCount(0) == rows);
15095                 DE_ASSERT(getArgCompCount(1) == alignedCols * alignedRows);
15096                 DE_UNREF(alignedCols);
15097
15098                 if (getFlavor() == 0)
15099                 {
15100                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15101                         {
15102                                 fp16type        s       (fp16type::zero(1));
15103
15104                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15105                                 {
15106                                         const fp16type  v       (in[0][rowNdx]);
15107                                         const float             vf      (v.asFloat());
15108                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
15109                                         const fp16type  x       (in[1][ndx]);
15110                                         const float             xf      (x.asFloat());
15111                                         const fp16type  m       (vf * xf);
15112
15113                                         s = fp16type(s.asFloat() + m.asFloat());
15114                                 }
15115
15116                                 out[colNdx] = s.bits();
15117                                 min[colNdx] = getMin(s.asDouble(), getULPs(in));
15118                                 max[colNdx] = getMax(s.asDouble(), getULPs(in));
15119                         }
15120                 }
15121                 else if (getFlavor() == 1)
15122                 {
15123                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15124                         {
15125                                 float   s       (0.0f);
15126
15127                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15128                                 {
15129                                         const fp16type  v       (in[0][rowNdx]);
15130                                         const float             vf      (v.asFloat());
15131                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
15132                                         const fp16type  x       (in[1][ndx]);
15133                                         const float             xf      (x.asFloat());
15134                                         const float             m       (vf * xf);
15135
15136                                         s += m;
15137                                 }
15138
15139                                 out[colNdx] = fp16type(s).bits();
15140                                 min[colNdx] = getMin(static_cast<double>(s), getULPs(in));
15141                                 max[colNdx] = getMax(static_cast<double>(s), getULPs(in));
15142                         }
15143                 }
15144                 else
15145                 {
15146                         TCU_THROW(InternalError, "Unknown flavor");
15147                 }
15148
15149                 return true;
15150         }
15151 };
15152
15153 template<size_t cols, size_t rows>
15154 struct fp16MatrixTimesVector : public fp16MatrixBase
15155 {
15156         fp16MatrixTimesVector() : fp16MatrixBase()
15157         {
15158                 flavorNames.push_back("EmulatingFP16");
15159                 flavorNames.push_back("FloatCalc");
15160         }
15161
15162         virtual double getULPs (vector<const deFloat16*>& in)
15163         {
15164                 DE_UNREF(in);
15165
15166                 return (8.0 * rows);
15167         }
15168
15169         deUint32 getComponentValidity ()
15170         {
15171                 return getComponentMatrixValidityMask(rows, 1);
15172         }
15173
15174         template<class fp16type>
15175         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15176         {
15177                 DE_ASSERT(in.size() == 2);
15178
15179                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15180                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15181
15182                 DE_ASSERT(getOutCompCount() == rows);
15183                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
15184                 DE_ASSERT(getArgCompCount(1) == cols);
15185                 DE_UNREF(alignedCols);
15186
15187                 if (getFlavor() == 0)
15188                 {
15189                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15190                         {
15191                                 fp16type        s       (fp16type::zero(1));
15192
15193                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15194                                 {
15195                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
15196                                         const fp16type  x       (in[0][ndx]);
15197                                         const float             xf      (x.asFloat());
15198                                         const fp16type  v       (in[1][colNdx]);
15199                                         const float             vf      (v.asFloat());
15200                                         const fp16type  m       (vf * xf);
15201
15202                                         s = fp16type(s.asFloat() + m.asFloat());
15203                                 }
15204
15205                                 out[rowNdx] = s.bits();
15206                                 min[rowNdx] = getMin(s.asDouble(), getULPs(in));
15207                                 max[rowNdx] = getMax(s.asDouble(), getULPs(in));
15208                         }
15209                 }
15210                 else if (getFlavor() == 1)
15211                 {
15212                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15213                         {
15214                                 float   s       (0.0f);
15215
15216                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15217                                 {
15218                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
15219                                         const fp16type  x       (in[0][ndx]);
15220                                         const float             xf      (x.asFloat());
15221                                         const fp16type  v       (in[1][colNdx]);
15222                                         const float             vf      (v.asFloat());
15223                                         const float             m       (vf * xf);
15224
15225                                         s += m;
15226                                 }
15227
15228                                 out[rowNdx] = fp16type(s).bits();
15229                                 min[rowNdx] = getMin(static_cast<double>(s), getULPs(in));
15230                                 max[rowNdx] = getMax(static_cast<double>(s), getULPs(in));
15231                         }
15232                 }
15233                 else
15234                 {
15235                         TCU_THROW(InternalError, "Unknown flavor");
15236                 }
15237
15238                 return true;
15239         }
15240 };
15241
15242 template<size_t colsL, size_t rowsL, size_t colsR, size_t rowsR>
15243 struct fp16MatrixTimesMatrix : public fp16MatrixBase
15244 {
15245         fp16MatrixTimesMatrix() : fp16MatrixBase()
15246         {
15247                 flavorNames.push_back("EmulatingFP16");
15248                 flavorNames.push_back("FloatCalc");
15249         }
15250
15251         virtual double getULPs (vector<const deFloat16*>& in)
15252         {
15253                 DE_UNREF(in);
15254
15255                 return 32.0;
15256         }
15257
15258         deUint32 getComponentValidity ()
15259         {
15260                 return getComponentMatrixValidityMask(colsR, rowsL);
15261         }
15262
15263         template<class fp16type>
15264         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15265         {
15266                 DE_STATIC_ASSERT(colsL == rowsR);
15267
15268                 DE_ASSERT(in.size() == 2);
15269
15270                 const size_t    alignedColsL    = (colsL == 3) ? 4 : colsL;
15271                 const size_t    alignedRowsL    = (rowsL == 3) ? 4 : rowsL;
15272                 const size_t    alignedColsR    = (colsR == 3) ? 4 : colsR;
15273                 const size_t    alignedRowsR    = (rowsR == 3) ? 4 : rowsR;
15274
15275                 DE_ASSERT(getOutCompCount() == alignedColsR * alignedRowsL);
15276                 DE_ASSERT(getArgCompCount(0) == alignedColsL * alignedRowsL);
15277                 DE_ASSERT(getArgCompCount(1) == alignedColsR * alignedRowsR);
15278                 DE_UNREF(alignedColsL);
15279                 DE_UNREF(alignedColsR);
15280
15281                 if (getFlavor() == 0)
15282                 {
15283                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15284                         {
15285                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15286                                 {
15287                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15288                                         fp16type                s       (fp16type::zero(1));
15289
15290                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15291                                         {
15292                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15293                                                 const fp16type  l               (in[0][ndxl]);
15294                                                 const float             lf              (l.asFloat());
15295                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15296                                                 const fp16type  r               (in[1][ndxr]);
15297                                                 const float             rf              (r.asFloat());
15298                                                 const fp16type  m               (lf * rf);
15299
15300                                                 s = fp16type(s.asFloat() + m.asFloat());
15301                                         }
15302
15303                                         out[ndx] = s.bits();
15304                                         min[ndx] = getMin(s.asDouble(), getULPs(in));
15305                                         max[ndx] = getMax(s.asDouble(), getULPs(in));
15306                                 }
15307                         }
15308                 }
15309                 else if (getFlavor() == 1)
15310                 {
15311                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15312                         {
15313                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15314                                 {
15315                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15316                                         float                   s       (0.0f);
15317
15318                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15319                                         {
15320                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15321                                                 const fp16type  l               (in[0][ndxl]);
15322                                                 const float             lf              (l.asFloat());
15323                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15324                                                 const fp16type  r               (in[1][ndxr]);
15325                                                 const float             rf              (r.asFloat());
15326                                                 const float             m               (lf * rf);
15327
15328                                                 s += m;
15329                                         }
15330
15331                                         out[ndx] = fp16type(s).bits();
15332                                         min[ndx] = getMin(static_cast<double>(s), getULPs(in));
15333                                         max[ndx] = getMax(static_cast<double>(s), getULPs(in));
15334                                 }
15335                         }
15336                 }
15337                 else
15338                 {
15339                         TCU_THROW(InternalError, "Unknown flavor");
15340                 }
15341
15342                 return true;
15343         }
15344 };
15345
15346 template<size_t cols, size_t rows>
15347 struct fp16OuterProduct : public fp16MatrixBase
15348 {
15349         virtual double getULPs (vector<const deFloat16*>& in)
15350         {
15351                 DE_UNREF(in);
15352
15353                 return 2.0;
15354         }
15355
15356         deUint32 getComponentValidity ()
15357         {
15358                 return getComponentMatrixValidityMask(cols, rows);
15359         }
15360
15361         template<class fp16type>
15362         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15363         {
15364                 DE_ASSERT(in.size() == 2);
15365
15366                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15367                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15368
15369                 DE_ASSERT(getArgCompCount(0) == rows);
15370                 DE_ASSERT(getArgCompCount(1) == cols);
15371                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
15372                 DE_UNREF(alignedCols);
15373
15374                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15375                 {
15376                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15377                         {
15378                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15379                                 const fp16type  x       (in[0][rowNdx]);
15380                                 const float             xf      (x.asFloat());
15381                                 const fp16type  y       (in[1][colNdx]);
15382                                 const float             yf      (y.asFloat());
15383                                 const fp16type  m       (xf * yf);
15384
15385                                 out[ndx] = m.bits();
15386                                 min[ndx] = getMin(m.asDouble(), getULPs(in));
15387                                 max[ndx] = getMax(m.asDouble(), getULPs(in));
15388                         }
15389                 }
15390
15391                 return true;
15392         }
15393 };
15394
15395 template<size_t size>
15396 struct fp16Determinant;
15397
15398 template<>
15399 struct fp16Determinant<2> : public fp16MatrixBase
15400 {
15401         virtual double getULPs (vector<const deFloat16*>& in)
15402         {
15403                 DE_UNREF(in);
15404
15405                 return 128.0; // This is not a precision test. Value is not from spec
15406         }
15407
15408         deUint32 getComponentValidity ()
15409         {
15410                 return 1;
15411         }
15412
15413         template<class fp16type>
15414         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15415         {
15416                 const size_t    cols            = 2;
15417                 const size_t    rows            = 2;
15418                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15419                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15420
15421                 DE_ASSERT(in.size() == 1);
15422                 DE_ASSERT(getOutCompCount() == 1);
15423                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15424                 DE_UNREF(alignedCols);
15425                 DE_UNREF(alignedRows);
15426
15427                 // [ a b ]
15428                 // [ c d ]
15429                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15430                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15431                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15432                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15433                 const float             ad              (a * d);
15434                 const fp16type  adf16   (ad);
15435                 const float             bc              (b * c);
15436                 const fp16type  bcf16   (bc);
15437                 const float             r               (adf16.asFloat() - bcf16.asFloat());
15438                 const fp16type  rf16    (r);
15439
15440                 out[0] = rf16.bits();
15441                 min[0] = getMin(r, getULPs(in));
15442                 max[0] = getMax(r, getULPs(in));
15443
15444                 return true;
15445         }
15446 };
15447
15448 template<>
15449 struct fp16Determinant<3> : public fp16MatrixBase
15450 {
15451         virtual double getULPs (vector<const deFloat16*>& in)
15452         {
15453                 DE_UNREF(in);
15454
15455                 return 128.0; // This is not a precision test. Value is not from spec
15456         }
15457
15458         deUint32 getComponentValidity ()
15459         {
15460                 return 1;
15461         }
15462
15463         template<class fp16type>
15464         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15465         {
15466                 const size_t    cols            = 3;
15467                 const size_t    rows            = 3;
15468                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15469                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15470
15471                 DE_ASSERT(in.size() == 1);
15472                 DE_ASSERT(getOutCompCount() == 1);
15473                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15474                 DE_UNREF(alignedCols);
15475                 DE_UNREF(alignedRows);
15476
15477                 // [ a b c ]
15478                 // [ d e f ]
15479                 // [ g h i ]
15480                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15481                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15482                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15483                 const float             d               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15484                 const float             e               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15485                 const float             f               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15486                 const float             g               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15487                 const float             h               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15488                 const float             i               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15489                 const fp16type  aei             (a * e * i);
15490                 const fp16type  bfg             (b * f * g);
15491                 const fp16type  cdh             (c * d * h);
15492                 const fp16type  ceg             (c * e * g);
15493                 const fp16type  bdi             (b * d * i);
15494                 const fp16type  afh             (a * f * h);
15495                 const float             r               (aei.asFloat() + bfg.asFloat() + cdh.asFloat() - ceg.asFloat() - bdi.asFloat() - afh.asFloat());
15496                 const fp16type  rf16    (r);
15497
15498                 out[0] = rf16.bits();
15499                 min[0] = getMin(r, getULPs(in));
15500                 max[0] = getMax(r, getULPs(in));
15501
15502                 return true;
15503         }
15504 };
15505
15506 template<>
15507 struct fp16Determinant<4> : public fp16MatrixBase
15508 {
15509         virtual double getULPs (vector<const deFloat16*>& in)
15510         {
15511                 DE_UNREF(in);
15512
15513                 return 128.0; // This is not a precision test. Value is not from spec
15514         }
15515
15516         deUint32 getComponentValidity ()
15517         {
15518                 return 1;
15519         }
15520
15521         template<class fp16type>
15522         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15523         {
15524                 const size_t    rows            = 4;
15525                 const size_t    cols            = 4;
15526                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15527                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15528
15529                 DE_ASSERT(in.size() == 1);
15530                 DE_ASSERT(getOutCompCount() == 1);
15531                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15532                 DE_UNREF(alignedCols);
15533                 DE_UNREF(alignedRows);
15534
15535                 // [ a b c d ]
15536                 // [ e f g h ]
15537                 // [ i j k l ]
15538                 // [ m n o p ]
15539                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15540                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15541                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15542                 const float             d               (fp16type(in[0][getNdx(rows, 3, 0)]).asFloat());
15543                 const float             e               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15544                 const float             f               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15545                 const float             g               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15546                 const float             h               (fp16type(in[0][getNdx(rows, 3, 1)]).asFloat());
15547                 const float             i               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15548                 const float             j               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15549                 const float             k               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15550                 const float             l               (fp16type(in[0][getNdx(rows, 3, 2)]).asFloat());
15551                 const float             m               (fp16type(in[0][getNdx(rows, 0, 3)]).asFloat());
15552                 const float             n               (fp16type(in[0][getNdx(rows, 1, 3)]).asFloat());
15553                 const float             o               (fp16type(in[0][getNdx(rows, 2, 3)]).asFloat());
15554                 const float             p               (fp16type(in[0][getNdx(rows, 3, 3)]).asFloat());
15555
15556                 // [ f g h ]
15557                 // [ j k l ]
15558                 // [ n o p ]
15559                 const fp16type  fkp             (f * k * p);
15560                 const fp16type  gln             (g * l * n);
15561                 const fp16type  hjo             (h * j * o);
15562                 const fp16type  hkn             (h * k * n);
15563                 const fp16type  gjp             (g * j * p);
15564                 const fp16type  flo             (f * l * o);
15565                 const fp16type  detA    (a * (fkp.asFloat() + gln.asFloat() + hjo.asFloat() - hkn.asFloat() - gjp.asFloat() - flo.asFloat()));
15566
15567                 // [ e g h ]
15568                 // [ i k l ]
15569                 // [ m o p ]
15570                 const fp16type  ekp             (e * k * p);
15571                 const fp16type  glm             (g * l * m);
15572                 const fp16type  hio             (h * i * o);
15573                 const fp16type  hkm             (h * k * m);
15574                 const fp16type  gip             (g * i * p);
15575                 const fp16type  elo             (e * l * o);
15576                 const fp16type  detB    (b * (ekp.asFloat() + glm.asFloat() + hio.asFloat() - hkm.asFloat() - gip.asFloat() - elo.asFloat()));
15577
15578                 // [ e f h ]
15579                 // [ i j l ]
15580                 // [ m n p ]
15581                 const fp16type  ejp             (e * j * p);
15582                 const fp16type  flm             (f * l * m);
15583                 const fp16type  hin             (h * i * n);
15584                 const fp16type  hjm             (h * j * m);
15585                 const fp16type  fip             (f * i * p);
15586                 const fp16type  eln             (e * l * n);
15587                 const fp16type  detC    (c * (ejp.asFloat() + flm.asFloat() + hin.asFloat() - hjm.asFloat() - fip.asFloat() - eln.asFloat()));
15588
15589                 // [ e f g ]
15590                 // [ i j k ]
15591                 // [ m n o ]
15592                 const fp16type  ejo             (e * j * o);
15593                 const fp16type  fkm             (f * k * m);
15594                 const fp16type  gin             (g * i * n);
15595                 const fp16type  gjm             (g * j * m);
15596                 const fp16type  fio             (f * i * o);
15597                 const fp16type  ekn             (e * k * n);
15598                 const fp16type  detD    (d * (ejo.asFloat() + fkm.asFloat() + gin.asFloat() - gjm.asFloat() - fio.asFloat() - ekn.asFloat()));
15599
15600                 const float             r               (detA.asFloat() - detB.asFloat() + detC.asFloat() - detD.asFloat());
15601                 const fp16type  rf16    (r);
15602
15603                 out[0] = rf16.bits();
15604                 min[0] = getMin(r, getULPs(in));
15605                 max[0] = getMax(r, getULPs(in));
15606
15607                 return true;
15608         }
15609 };
15610
15611 template<size_t size>
15612 struct fp16Inverse;
15613
15614 template<>
15615 struct fp16Inverse<2> : public fp16MatrixBase
15616 {
15617         virtual double getULPs (vector<const deFloat16*>& in)
15618         {
15619                 DE_UNREF(in);
15620
15621                 return 128.0; // This is not a precision test. Value is not from spec
15622         }
15623
15624         deUint32 getComponentValidity ()
15625         {
15626                 return getComponentMatrixValidityMask(2, 2);
15627         }
15628
15629         template<class fp16type>
15630         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15631         {
15632                 const size_t    cols            = 2;
15633                 const size_t    rows            = 2;
15634                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15635                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15636
15637                 DE_ASSERT(in.size() == 1);
15638                 DE_ASSERT(getOutCompCount() == alignedRows * alignedCols);
15639                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15640                 DE_UNREF(alignedCols);
15641
15642                 // [ a b ]
15643                 // [ c d ]
15644                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15645                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15646                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15647                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15648                 const float             ad              (a * d);
15649                 const fp16type  adf16   (ad);
15650                 const float             bc              (b * c);
15651                 const fp16type  bcf16   (bc);
15652                 const float             det             (adf16.asFloat() - bcf16.asFloat());
15653                 const fp16type  det16   (det);
15654
15655                 out[0] = fp16type( d / det16.asFloat()).bits();
15656                 out[1] = fp16type(-c / det16.asFloat()).bits();
15657                 out[2] = fp16type(-b / det16.asFloat()).bits();
15658                 out[3] = fp16type( a / det16.asFloat()).bits();
15659
15660                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15661                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15662                         {
15663                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15664                                 const fp16type  s       (out[ndx]);
15665
15666                                 min[ndx] = getMin(s.asDouble(), getULPs(in));
15667                                 max[ndx] = getMax(s.asDouble(), getULPs(in));
15668                         }
15669
15670                 return true;
15671         }
15672 };
15673
15674 inline std::string fp16ToString(deFloat16 val)
15675 {
15676         return tcu::toHex<4>(val).toString() + " (" + de::floatToString(tcu::Float16(val).asFloat(), 10) + ")";
15677 }
15678
15679 template <size_t RES_COMPONENTS, size_t ARG0_COMPONENTS, size_t ARG1_COMPONENTS, size_t ARG2_COMPONENTS, class TestedArithmeticFunction>
15680 bool compareFP16ArithmeticFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
15681 {
15682         if (inputs.size() < 1 || inputs.size() > 3 || outputAllocs.size() != 1 || expectedOutputs.size() != 1)
15683                 return false;
15684
15685         const size_t    resultStep                      = (RES_COMPONENTS == 3) ? 4 : RES_COMPONENTS;
15686         const size_t    iterationsCount         = expectedOutputs[0].getByteSize() / (sizeof(deFloat16) * resultStep);
15687         const size_t    inputsSteps[3]          =
15688         {
15689                 (ARG0_COMPONENTS == 3) ? 4 : ARG0_COMPONENTS,
15690                 (ARG1_COMPONENTS == 3) ? 4 : ARG1_COMPONENTS,
15691                 (ARG2_COMPONENTS == 3) ? 4 : ARG2_COMPONENTS,
15692         };
15693
15694         DE_ASSERT(expectedOutputs[0].getByteSize() > 0);
15695         DE_ASSERT(expectedOutputs[0].getByteSize() == sizeof(deFloat16) * iterationsCount * resultStep);
15696
15697         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15698         {
15699                 DE_ASSERT(inputs[inputNdx].getByteSize() > 0);
15700                 DE_ASSERT(inputs[inputNdx].getByteSize() == sizeof(deFloat16) * iterationsCount * inputsSteps[inputNdx]);
15701         }
15702
15703         const deFloat16* const          outputAsFP16                                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
15704         TestedArithmeticFunction        func;
15705
15706         func.setOutCompCount(RES_COMPONENTS);
15707         func.setArgCompCount(0, ARG0_COMPONENTS);
15708         func.setArgCompCount(1, ARG1_COMPONENTS);
15709         func.setArgCompCount(2, ARG2_COMPONENTS);
15710
15711         const bool                                      callOncePerComponent                    = func.callOncePerComponent();
15712         const deUint32                          componentValidityMask                   = func.getComponentValidity();
15713         const size_t                            denormModesCount                                = 2;
15714         const char*                                     denormModes[denormModesCount]   = { "keep denormal numbers", "flush to zero" };
15715         const size_t                            successfulRunsPerComponent              = denormModesCount * func.getFlavorCount();
15716         bool                                            success                                                 = true;
15717         size_t                                          validatedCount                                  = 0;
15718
15719         vector<deUint8> inputBytes[3];
15720
15721         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15722                 inputs[inputNdx].getBytes(inputBytes[inputNdx]);
15723
15724         const deFloat16* const                  inputsAsFP16[3]                 =
15725         {
15726                 inputs.size() >= 1 ? (const deFloat16*)&inputBytes[0][0] : DE_NULL,
15727                 inputs.size() >= 2 ? (const deFloat16*)&inputBytes[1][0] : DE_NULL,
15728                 inputs.size() >= 3 ? (const deFloat16*)&inputBytes[2][0] : DE_NULL,
15729         };
15730
15731         for (size_t idx = 0; idx < iterationsCount; ++idx)
15732         {
15733                 std::vector<size_t>                     successfulRuns          (RES_COMPONENTS, successfulRunsPerComponent);
15734                 std::vector<std::string>        errors                          (RES_COMPONENTS);
15735                 bool                                            iterationValidated      (true);
15736
15737                 for (size_t denormNdx = 0; denormNdx < 2; ++denormNdx)
15738                 {
15739                         for (size_t flavorNdx = 0; flavorNdx < func.getFlavorCount(); ++flavorNdx)
15740                         {
15741                                 func.setFlavor(flavorNdx);
15742
15743                                 const deFloat16*                        iterationOutputFP16             = &outputAsFP16[idx * resultStep];
15744                                 vector<deFloat16>                       iterationCalculatedFP16 (resultStep, 0);
15745                                 vector<double>                          iterationEdgeMin                (resultStep, 0.0);
15746                                 vector<double>                          iterationEdgeMax                (resultStep, 0.0);
15747                                 vector<const deFloat16*>        arguments;
15748
15749                                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15750                                 {
15751                                         std::string     error;
15752                                         bool            reportError = false;
15753
15754                                         if (callOncePerComponent || componentNdx == 0)
15755                                         {
15756                                                 bool funcCallResult;
15757
15758                                                 arguments.clear();
15759
15760                                                 for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15761                                                         arguments.push_back(&inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + componentNdx]);
15762
15763                                                 if (denormNdx == 0)
15764                                                         funcCallResult = func.template calc<tcu::Float16>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15765                                                 else
15766                                                         funcCallResult = func.template calc<tcu::Float16Denormless>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15767
15768                                                 if (!funcCallResult)
15769                                                 {
15770                                                         iterationValidated = false;
15771
15772                                                         if (callOncePerComponent)
15773                                                                 continue;
15774                                                         else
15775                                                                 break;
15776                                                 }
15777                                         }
15778
15779                                         if ((componentValidityMask != 0) && (componentValidityMask & (1<<componentNdx)) == 0)
15780                                                 continue;
15781
15782                                         reportError = !compare16BitFloat(iterationCalculatedFP16[componentNdx], iterationOutputFP16[componentNdx], error);
15783
15784                                         if (reportError)
15785                                         {
15786                                                 tcu::Float16 expected   (iterationCalculatedFP16[componentNdx]);
15787                                                 tcu::Float16 outputted  (iterationOutputFP16[componentNdx]);
15788
15789                                                 if (reportError && expected.isNaN())
15790                                                         reportError = false;
15791
15792                                                 if (reportError && !expected.isNaN() && !outputted.isNaN())
15793                                                 {
15794                                                         if (reportError && !expected.isInf() && !outputted.isInf())
15795                                                         {
15796                                                                 // Ignore rounding
15797                                                                 if (expected.bits() == outputted.bits() + 1 || expected.bits() + 1 == outputted.bits())
15798                                                                         reportError = false;
15799                                                         }
15800
15801                                                         if (reportError && expected.isInf())
15802                                                         {
15803                                                                 // RTZ rounding mode returns +/-65504 instead of Inf on overflow
15804                                                                 if (expected.sign() == 1 && outputted.bits() == 0x7bff && iterationEdgeMin[componentNdx] <= std::numeric_limits<double>::max())
15805                                                                         reportError = false;
15806                                                                 else if (expected.sign() == -1 && outputted.bits() == 0xfbff && iterationEdgeMax[componentNdx] >= -std::numeric_limits<double>::max())
15807                                                                         reportError = false;
15808                                                         }
15809
15810                                                         if (reportError)
15811                                                         {
15812                                                                 const double    outputtedDouble = outputted.asDouble();
15813
15814                                                                 DE_ASSERT(iterationEdgeMin[componentNdx] <= iterationEdgeMax[componentNdx]);
15815
15816                                                                 if (de::inRange(outputtedDouble, iterationEdgeMin[componentNdx], iterationEdgeMax[componentNdx]))
15817                                                                         reportError = false;
15818                                                         }
15819                                                 }
15820
15821                                                 if (reportError)
15822                                                 {
15823                                                         const size_t            inputsComps[3]  =
15824                                                         {
15825                                                                 ARG0_COMPONENTS,
15826                                                                 ARG1_COMPONENTS,
15827                                                                 ARG2_COMPONENTS,
15828                                                         };
15829                                                         string                          inputsValues    ("Inputs:");
15830                                                         string                          flavorName              (func.getFlavorCount() == 1 ? "" : string(" flavor ") + de::toString(flavorNdx) + " (" + func.getCurrentFlavorName() + ")");
15831                                                         std::stringstream       errStream;
15832
15833                                                         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15834                                                         {
15835                                                                 const size_t    inputCompsCount = inputsComps[inputNdx];
15836
15837                                                                 inputsValues += " [" + de::toString(inputNdx) + "]=(";
15838
15839                                                                 for (size_t compNdx = 0; compNdx < inputCompsCount; ++compNdx)
15840                                                                 {
15841                                                                         const deFloat16 inputComponentValue = inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + compNdx];
15842
15843                                                                         inputsValues += fp16ToString(inputComponentValue) + ((compNdx + 1 == inputCompsCount) ? ")": ", ");
15844                                                                 }
15845                                                         }
15846
15847                                                         errStream       << "At"
15848                                                                                 << " iteration " << de::toString(idx)
15849                                                                                 << " component " << de::toString(componentNdx)
15850                                                                                 << " denormMode " << de::toString(denormNdx)
15851                                                                                 << " (" << denormModes[denormNdx] << ")"
15852                                                                                 << " " << flavorName
15853                                                                                 << " " << inputsValues
15854                                                                                 << " outputted:" + fp16ToString(iterationOutputFP16[componentNdx])
15855                                                                                 << " expected:" + fp16ToString(iterationCalculatedFP16[componentNdx])
15856                                                                                 << " or in range: [" << iterationEdgeMin[componentNdx] << ", " << iterationEdgeMax[componentNdx] << "]."
15857                                                                                 << " " << error << "."
15858                                                                                 << std::endl;
15859
15860                                                         errors[componentNdx] += errStream.str();
15861
15862                                                         successfulRuns[componentNdx]--;
15863                                                 }
15864                                         }
15865                                 }
15866                         }
15867                 }
15868
15869                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15870                 {
15871                         // Check if any component has total failure
15872                         if (successfulRuns[componentNdx] == 0)
15873                         {
15874                                 // Test failed in all denorm modes and all flavors for certain component: dump errors
15875                                 log << TestLog::Message << errors[componentNdx] << TestLog::EndMessage;
15876
15877                                 success = false;
15878                         }
15879                 }
15880
15881                 if (iterationValidated)
15882                         validatedCount++;
15883         }
15884
15885         if (validatedCount < 16)
15886                 TCU_THROW(InternalError, "Too few samples has been validated.");
15887
15888         return success;
15889 }
15890
15891 // IEEE-754 floating point numbers:
15892 // +--------+------+----------+-------------+
15893 // | binary | sign | exponent | significand |
15894 // +--------+------+----------+-------------+
15895 // | 16-bit |  1   |    5     |     10      |
15896 // +--------+------+----------+-------------+
15897 // | 32-bit |  1   |    8     |     23      |
15898 // +--------+------+----------+-------------+
15899 //
15900 // 16-bit floats:
15901 //
15902 // 0   000 00   00 0000 0001 (0x0001: 2e-24:         minimum positive denormalized)
15903 // 0   000 00   11 1111 1111 (0x03ff: 2e-14 - 2e-24: maximum positive denormalized)
15904 // 0   000 01   00 0000 0000 (0x0400: 2e-14:         minimum positive normalized)
15905 // 0   111 10   11 1111 1111 (0x7bff: 65504:         maximum positive normalized)
15906 //
15907 // 0   000 00   00 0000 0000 (0x0000: +0)
15908 // 0   111 11   00 0000 0000 (0x7c00: +Inf)
15909 // 0   000 00   11 1111 0000 (0x03f0: +Denorm)
15910 // 0   000 01   00 0000 0001 (0x0401: +Norm)
15911 // 0   111 11   00 0000 1111 (0x7c0f: +SNaN)
15912 // 0   111 11   11 1111 0000 (0x7ff0: +QNaN)
15913 // Generate and return 16-bit floats and their corresponding 32-bit values.
15914 //
15915 // The first 14 number pairs are manually picked, while the rest are randomly generated.
15916 // Expected count to be at least 14 (numPicks).
15917 vector<deFloat16> getFloat16a (de::Random& rnd, deUint32 count)
15918 {
15919         vector<deFloat16>       float16;
15920
15921         float16.reserve(count);
15922
15923         // Zero
15924         float16.push_back(deUint16(0x0000));
15925         float16.push_back(deUint16(0x8000));
15926         // Infinity
15927         float16.push_back(deUint16(0x7c00));
15928         float16.push_back(deUint16(0xfc00));
15929         // Normalized
15930         float16.push_back(deUint16(0x0401));
15931         float16.push_back(deUint16(0x8401));
15932         // Some normal number
15933         float16.push_back(deUint16(0x14cb));
15934         float16.push_back(deUint16(0x94cb));
15935         // Min/max positive normal
15936         float16.push_back(deUint16(0x0400));
15937         float16.push_back(deUint16(0x7bff));
15938         // Min/max negative normal
15939         float16.push_back(deUint16(0x8400));
15940         float16.push_back(deUint16(0xfbff));
15941         // PI
15942         float16.push_back(deUint16(0x4248)); // 3.140625
15943         float16.push_back(deUint16(0xb248)); // -3.140625
15944         // PI/2
15945         float16.push_back(deUint16(0x3e48)); // 1.5703125
15946         float16.push_back(deUint16(0xbe48)); // -1.5703125
15947         float16.push_back(deUint16(0x3c00)); // 1.0
15948         float16.push_back(deUint16(0x3800)); // 0.5
15949         // Some useful constants
15950         float16.push_back(tcu::Float16(-2.5f).bits());
15951         float16.push_back(tcu::Float16(-1.0f).bits());
15952         float16.push_back(tcu::Float16( 0.4f).bits());
15953         float16.push_back(tcu::Float16( 2.5f).bits());
15954
15955         const deUint32          numPicks        = static_cast<deUint32>(float16.size());
15956
15957         DE_ASSERT(count >= numPicks);
15958         count -= numPicks;
15959
15960         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15961         {
15962                 int                     sign            = (rnd.getUint16() % 2 == 0) ? +1 : -1;
15963                 int                     exponent        = (rnd.getUint16() % 29) - 14 + 1;
15964                 deUint16        mantissa        = static_cast<deUint16>(2 * (rnd.getUint16() % 512));
15965
15966                 // Exclude power of -14 to avoid denorms
15967                 DE_ASSERT(de::inRange(exponent, -13, 15));
15968
15969                 float16.push_back(tcu::Float16::constructBits(sign, exponent, mantissa).bits());
15970         }
15971
15972         return float16;
15973 }
15974
15975 static inline vector<deFloat16> getInputData1 (deUint32 seed, size_t count, size_t argNo)
15976 {
15977         DE_UNREF(argNo);
15978
15979         de::Random      rnd(seed);
15980
15981         return getFloat16a(rnd, static_cast<deUint32>(count));
15982 }
15983
15984 static inline vector<deFloat16> getInputData2 (deUint32 seed, size_t count, size_t argNo)
15985 {
15986         de::Random      rnd             (seed);
15987         size_t          newCount = static_cast<size_t>(deSqrt(double(count)));
15988
15989         DE_ASSERT(newCount * newCount == count);
15990
15991         vector<deFloat16>       float16 = getFloat16a(rnd, static_cast<deUint32>(newCount));
15992
15993         return squarize(float16, static_cast<deUint32>(argNo));
15994 }
15995
15996 static inline vector<deFloat16> getInputData3 (deUint32 seed, size_t count, size_t argNo)
15997 {
15998         if (argNo == 0 || argNo == 1)
15999                 return getInputData2(seed, count, argNo);
16000         else
16001                 return getInputData1(seed<<argNo, count, argNo);
16002 }
16003
16004 vector<deFloat16> getInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16005 {
16006         DE_UNREF(stride);
16007
16008         vector<deFloat16>       result;
16009
16010         switch (argCount)
16011         {
16012                 case 1:result = getInputData1(seed, count, argNo); break;
16013                 case 2:result = getInputData2(seed, count, argNo); break;
16014                 case 3:result = getInputData3(seed, count, argNo); break;
16015                 default: TCU_THROW(InternalError, "Invalid argument count specified");
16016         }
16017
16018         if (compCount == 3)
16019         {
16020                 const size_t            newCount = (3 * count) / 4;
16021                 vector<deFloat16>       newResult;
16022
16023                 newResult.reserve(result.size());
16024
16025                 for (size_t ndx = 0; ndx < newCount; ++ndx)
16026                 {
16027                         newResult.push_back(result[ndx]);
16028
16029                         if (ndx % 3 == 2)
16030                                 newResult.push_back(0);
16031                 }
16032
16033                 result = newResult;
16034         }
16035
16036         DE_ASSERT(result.size() == count);
16037
16038         return result;
16039 }
16040
16041 // Generator for functions requiring data in range [1, inf]
16042 vector<deFloat16> getInputDataAC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16043 {
16044         vector<deFloat16>       result;
16045
16046         result = getInputData(seed, count, compCount, stride, argCount, argNo);
16047
16048         // Filter out values below 1.0 from upper half of numbers
16049         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16050         {
16051                 const float f = tcu::Float16(result[idx]).asFloat();
16052
16053                 if (f < 1.0f)
16054                         result[idx] = tcu::Float16(1.0f - f).bits();
16055         }
16056
16057         return result;
16058 }
16059
16060 // Generator for functions requiring data in range [-1, 1]
16061 vector<deFloat16> getInputDataA (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16062 {
16063         vector<deFloat16>       result;
16064
16065         result = getInputData(seed, count, compCount, stride, argCount, argNo);
16066
16067         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16068         {
16069                 const float f = tcu::Float16(result[idx]).asFloat();
16070
16071                 if (!de::inRange(f, -1.0f, 1.0f))
16072                         result[idx] = tcu::Float16(deFloatFrac(f)).bits();
16073         }
16074
16075         return result;
16076 }
16077
16078 // Generator for functions requiring data in range [-pi, pi]
16079 vector<deFloat16> getInputDataPI (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16080 {
16081         vector<deFloat16>       result;
16082
16083         result = getInputData(seed, count, compCount, stride, argCount, argNo);
16084
16085         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16086         {
16087                 const float f = tcu::Float16(result[idx]).asFloat();
16088
16089                 if (!de::inRange(f, -DE_PI, DE_PI))
16090                         result[idx] = tcu::Float16(fmodf(f, DE_PI)).bits();
16091         }
16092
16093         return result;
16094 }
16095
16096 // Generator for functions requiring data in range [0, inf]
16097 vector<deFloat16> getInputDataP (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16098 {
16099         vector<deFloat16>       result;
16100
16101         result = getInputData(seed, count, compCount, stride, argCount, argNo);
16102
16103         if (argNo == 0)
16104         {
16105                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16106                         result[idx] &= static_cast<deFloat16>(~0x8000);
16107         }
16108
16109         return result;
16110 }
16111
16112 vector<deFloat16> getInputDataV (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16113 {
16114         DE_UNREF(stride);
16115         DE_UNREF(argCount);
16116
16117         vector<deFloat16>       result;
16118
16119         if (argNo == 0)
16120                 result = getInputData2(seed, count, argNo);
16121         else
16122         {
16123                 const size_t            alignedCount    = (compCount == 3) ? 4 : compCount;
16124                 const size_t            newCountX               = static_cast<size_t>(deSqrt(double(count * alignedCount)));
16125                 const size_t            newCountY               = count / newCountX;
16126                 de::Random                      rnd                             (seed);
16127                 vector<deFloat16>       float16                 = getFloat16a(rnd, static_cast<deUint32>(newCountX));
16128
16129                 DE_ASSERT(newCountX * newCountX == alignedCount * count);
16130
16131                 for (size_t numIdx = 0; numIdx < newCountX; ++numIdx)
16132                 {
16133                         const vector<deFloat16> tmp(newCountY, float16[numIdx]);
16134
16135                         result.insert(result.end(), tmp.begin(), tmp.end());
16136                 }
16137         }
16138
16139         DE_ASSERT(result.size() == count);
16140
16141         return result;
16142 }
16143
16144 vector<deFloat16> getInputDataM (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16145 {
16146         DE_UNREF(compCount);
16147         DE_UNREF(stride);
16148         DE_UNREF(argCount);
16149
16150         de::Random                      rnd             (seed << argNo);
16151         vector<deFloat16>       result;
16152
16153         result = getFloat16a(rnd, static_cast<deUint32>(count));
16154
16155         DE_ASSERT(result.size() == count);
16156
16157         return result;
16158 }
16159
16160 vector<deFloat16> getInputDataD (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16161 {
16162         DE_UNREF(compCount);
16163         DE_UNREF(argCount);
16164
16165         de::Random                      rnd             (seed << argNo);
16166         vector<deFloat16>       result;
16167
16168         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16169         {
16170                 int num = (rnd.getUint16() % 16) - 8;
16171
16172                 result.push_back(tcu::Float16(float(num)).bits());
16173         }
16174
16175         result[0 * stride] = deUint16(0x7c00); // +Inf
16176         result[1 * stride] = deUint16(0xfc00); // -Inf
16177
16178         DE_ASSERT(result.size() == count);
16179
16180         return result;
16181 }
16182
16183 // Generator for smoothstep function
16184 vector<deFloat16> getInputDataSS (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16185 {
16186         vector<deFloat16>       result;
16187
16188         result = getInputDataD(seed, count, compCount, stride, argCount, argNo);
16189
16190         if (argNo == 0)
16191         {
16192                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16193                 {
16194                         const float f = tcu::Float16(result[idx]).asFloat();
16195
16196                         if (f > 4.0f)
16197                                 result[idx] = tcu::Float16(-f).bits();
16198                 }
16199         }
16200
16201         if (argNo == 1)
16202         {
16203                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16204                 {
16205                         const float f = tcu::Float16(result[idx]).asFloat();
16206
16207                         if (f < 4.0f)
16208                                 result[idx] = tcu::Float16(-f).bits();
16209                 }
16210         }
16211
16212         return result;
16213 }
16214
16215 // Generates normalized vectors for arguments 0 and 1
16216 vector<deFloat16> getInputDataN (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16217 {
16218         DE_UNREF(compCount);
16219         DE_UNREF(argCount);
16220
16221         de::Random                      rnd             (seed << argNo);
16222         vector<deFloat16>       result;
16223
16224         if (argNo == 0 || argNo == 1)
16225         {
16226                 // The input parameters for the incident vector I and the surface normal N must already be normalized
16227                 for (size_t numIdx = 0; numIdx < count; numIdx += stride)
16228                 {
16229                         vector <float>  unnormolized;
16230                         float                   sum                             = 0;
16231
16232                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16233                                 unnormolized.push_back(float((rnd.getUint16() % 16) - 8));
16234
16235                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16236                                 sum += unnormolized[compIdx] * unnormolized[compIdx];
16237
16238                         sum = deFloatSqrt(sum);
16239                         if (sum == 0.0f)
16240                                 unnormolized[0] = sum = 1.0f;
16241
16242                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16243                                 result.push_back(tcu::Float16(unnormolized[compIdx] / sum).bits());
16244
16245                         for (size_t compIdx = compCount; compIdx < stride; ++compIdx)
16246                                 result.push_back(0);
16247                 }
16248         }
16249         else
16250         {
16251                 // Input parameter eta
16252                 for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16253                 {
16254                         int num = (rnd.getUint16() % 16) - 8;
16255
16256                         result.push_back(tcu::Float16(float(num)).bits());
16257                 }
16258         }
16259
16260         DE_ASSERT(result.size() == count);
16261
16262         return result;
16263 }
16264
16265 // Data generator for complex matrix functions like determinant and inverse
16266 vector<deFloat16> getInputDataC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16267 {
16268         DE_UNREF(compCount);
16269         DE_UNREF(stride);
16270         DE_UNREF(argCount);
16271
16272         de::Random                      rnd             (seed << argNo);
16273         vector<deFloat16>       result;
16274
16275         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16276         {
16277                 int num = (rnd.getUint16() % 16) - 8;
16278
16279                 result.push_back(tcu::Float16(float(num)).bits());
16280         }
16281
16282         DE_ASSERT(result.size() == count);
16283
16284         return result;
16285 }
16286
16287 struct Math16TestType
16288 {
16289         const char*             typePrefix;
16290         const size_t    typeComponents;
16291         const size_t    typeArrayStride;
16292         const size_t    typeStructStride;
16293 };
16294
16295 enum Math16DataTypes
16296 {
16297         NONE    = 0,
16298         SCALAR  = 1,
16299         VEC2    = 2,
16300         VEC3    = 3,
16301         VEC4    = 4,
16302         MAT2X2,
16303         MAT2X3,
16304         MAT2X4,
16305         MAT3X2,
16306         MAT3X3,
16307         MAT3X4,
16308         MAT4X2,
16309         MAT4X3,
16310         MAT4X4,
16311         MATH16_TYPE_LAST
16312 };
16313
16314 struct Math16ArgFragments
16315 {
16316         const char*     bodies;
16317         const char*     variables;
16318         const char*     decorations;
16319         const char*     funcVariables;
16320 };
16321
16322 typedef vector<deFloat16> Math16GetInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo);
16323
16324 struct Math16TestFunc
16325 {
16326         const char*                                     funcName;
16327         const char*                                     funcSuffix;
16328         size_t                                          funcArgsCount;
16329         size_t                                          typeResult;
16330         size_t                                          typeArg0;
16331         size_t                                          typeArg1;
16332         size_t                                          typeArg2;
16333         Math16GetInputData*                     getInputDataFunc;
16334         VerifyIOFunc                            verifyFunc;
16335 };
16336
16337 template<class SpecResource>
16338 void createFloat16ArithmeticFuncTest (tcu::TestContext& testCtx, tcu::TestCaseGroup& testGroup, const size_t testTypeIdx, const Math16TestFunc& testFunc)
16339 {
16340         const int                                       testSpecificSeed                        = deStringHash(testGroup.getName());
16341         const int                                       seed                                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
16342         const size_t                            numDataPointsByAxis                     = 32;
16343         const size_t                            numDataPoints                           = numDataPointsByAxis * numDataPointsByAxis;
16344         const char*                                     componentType                           = "f16";
16345         const Math16TestType            testTypes[MATH16_TYPE_LAST]     =
16346         {
16347                 { "",           0,       0,                                              0,                                             },
16348                 { "",           1,       1 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16349                 { "v2",         2,       2 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16350                 { "v3",         3,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16351                 { "v4",         4,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16352                 { "m2x2",       0,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16353                 { "m2x3",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16354                 { "m2x4",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16355                 { "m3x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16356                 { "m3x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16357                 { "m3x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16358                 { "m4x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16359                 { "m4x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16360                 { "m4x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16361         };
16362
16363         DE_ASSERT(testTypeIdx == testTypes[testTypeIdx].typeComponents);
16364
16365
16366         const StringTemplate preMain
16367         (
16368                 "     %c_i32_ndp  = OpConstant %i32 ${num_data_points}\n"
16369
16370                 "        %f16     = OpTypeFloat 16\n"
16371                 "        %v2f16   = OpTypeVector %f16 2\n"
16372                 "        %v3f16   = OpTypeVector %f16 3\n"
16373                 "        %v4f16   = OpTypeVector %f16 4\n"
16374                 "        %m2x2f16 = OpTypeMatrix %v2f16 2\n"
16375                 "        %m2x3f16 = OpTypeMatrix %v3f16 2\n"
16376                 "        %m2x4f16 = OpTypeMatrix %v4f16 2\n"
16377                 "        %m3x2f16 = OpTypeMatrix %v2f16 3\n"
16378                 "        %m3x3f16 = OpTypeMatrix %v3f16 3\n"
16379                 "        %m3x4f16 = OpTypeMatrix %v4f16 3\n"
16380                 "        %m4x2f16 = OpTypeMatrix %v2f16 4\n"
16381                 "        %m4x3f16 = OpTypeMatrix %v3f16 4\n"
16382                 "        %m4x4f16 = OpTypeMatrix %v4f16 4\n"
16383
16384                 "     %up_f16     = OpTypePointer Uniform %f16    \n"
16385                 "     %up_v2f16   = OpTypePointer Uniform %v2f16  \n"
16386                 "     %up_v3f16   = OpTypePointer Uniform %v3f16  \n"
16387                 "     %up_v4f16   = OpTypePointer Uniform %v4f16  \n"
16388                 "     %up_m2x2f16 = OpTypePointer Uniform %m2x2f16\n"
16389                 "     %up_m2x3f16 = OpTypePointer Uniform %m2x3f16\n"
16390                 "     %up_m2x4f16 = OpTypePointer Uniform %m2x4f16\n"
16391                 "     %up_m3x2f16 = OpTypePointer Uniform %m3x2f16\n"
16392                 "     %up_m3x3f16 = OpTypePointer Uniform %m3x3f16\n"
16393                 "     %up_m3x4f16 = OpTypePointer Uniform %m3x4f16\n"
16394                 "     %up_m4x2f16 = OpTypePointer Uniform %m4x2f16\n"
16395                 "     %up_m4x3f16 = OpTypePointer Uniform %m4x3f16\n"
16396                 "     %up_m4x4f16 = OpTypePointer Uniform %m4x4f16\n"
16397
16398                 "     %ra_f16     = OpTypeArray %f16     %c_i32_ndp\n"
16399                 "     %ra_v2f16   = OpTypeArray %v2f16   %c_i32_ndp\n"
16400                 "     %ra_v3f16   = OpTypeArray %v3f16   %c_i32_ndp\n"
16401                 "     %ra_v4f16   = OpTypeArray %v4f16   %c_i32_ndp\n"
16402                 "     %ra_m2x2f16 = OpTypeArray %m2x2f16 %c_i32_ndp\n"
16403                 "     %ra_m2x3f16 = OpTypeArray %m2x3f16 %c_i32_ndp\n"
16404                 "     %ra_m2x4f16 = OpTypeArray %m2x4f16 %c_i32_ndp\n"
16405                 "     %ra_m3x2f16 = OpTypeArray %m3x2f16 %c_i32_ndp\n"
16406                 "     %ra_m3x3f16 = OpTypeArray %m3x3f16 %c_i32_ndp\n"
16407                 "     %ra_m3x4f16 = OpTypeArray %m3x4f16 %c_i32_ndp\n"
16408                 "     %ra_m4x2f16 = OpTypeArray %m4x2f16 %c_i32_ndp\n"
16409                 "     %ra_m4x3f16 = OpTypeArray %m4x3f16 %c_i32_ndp\n"
16410                 "     %ra_m4x4f16 = OpTypeArray %m4x4f16 %c_i32_ndp\n"
16411
16412                 "   %SSBO_f16     = OpTypeStruct %ra_f16    \n"
16413                 "   %SSBO_v2f16   = OpTypeStruct %ra_v2f16  \n"
16414                 "   %SSBO_v3f16   = OpTypeStruct %ra_v3f16  \n"
16415                 "   %SSBO_v4f16   = OpTypeStruct %ra_v4f16  \n"
16416                 "   %SSBO_m2x2f16 = OpTypeStruct %ra_m2x2f16\n"
16417                 "   %SSBO_m2x3f16 = OpTypeStruct %ra_m2x3f16\n"
16418                 "   %SSBO_m2x4f16 = OpTypeStruct %ra_m2x4f16\n"
16419                 "   %SSBO_m3x2f16 = OpTypeStruct %ra_m3x2f16\n"
16420                 "   %SSBO_m3x3f16 = OpTypeStruct %ra_m3x3f16\n"
16421                 "   %SSBO_m3x4f16 = OpTypeStruct %ra_m3x4f16\n"
16422                 "   %SSBO_m4x2f16 = OpTypeStruct %ra_m4x2f16\n"
16423                 "   %SSBO_m4x3f16 = OpTypeStruct %ra_m4x3f16\n"
16424                 "   %SSBO_m4x4f16 = OpTypeStruct %ra_m4x4f16\n"
16425
16426                 "%up_SSBO_f16     = OpTypePointer Uniform %SSBO_f16    \n"
16427                 "%up_SSBO_v2f16   = OpTypePointer Uniform %SSBO_v2f16  \n"
16428                 "%up_SSBO_v3f16   = OpTypePointer Uniform %SSBO_v3f16  \n"
16429                 "%up_SSBO_v4f16   = OpTypePointer Uniform %SSBO_v4f16  \n"
16430                 "%up_SSBO_m2x2f16 = OpTypePointer Uniform %SSBO_m2x2f16\n"
16431                 "%up_SSBO_m2x3f16 = OpTypePointer Uniform %SSBO_m2x3f16\n"
16432                 "%up_SSBO_m2x4f16 = OpTypePointer Uniform %SSBO_m2x4f16\n"
16433                 "%up_SSBO_m3x2f16 = OpTypePointer Uniform %SSBO_m3x2f16\n"
16434                 "%up_SSBO_m3x3f16 = OpTypePointer Uniform %SSBO_m3x3f16\n"
16435                 "%up_SSBO_m3x4f16 = OpTypePointer Uniform %SSBO_m3x4f16\n"
16436                 "%up_SSBO_m4x2f16 = OpTypePointer Uniform %SSBO_m4x2f16\n"
16437                 "%up_SSBO_m4x3f16 = OpTypePointer Uniform %SSBO_m4x3f16\n"
16438                 "%up_SSBO_m4x4f16 = OpTypePointer Uniform %SSBO_m4x4f16\n"
16439
16440                 "       %fp_v2i32 = OpTypePointer Function %v2i32\n"
16441                 "       %fp_v3i32 = OpTypePointer Function %v3i32\n"
16442                 "       %fp_v4i32 = OpTypePointer Function %v4i32\n"
16443                 "${arg_vars}"
16444         );
16445
16446         const StringTemplate decoration
16447         (
16448                 "OpDecorate %ra_f16     ArrayStride 2 \n"
16449                 "OpDecorate %ra_v2f16   ArrayStride 4 \n"
16450                 "OpDecorate %ra_v3f16   ArrayStride 8 \n"
16451                 "OpDecorate %ra_v4f16   ArrayStride 8 \n"
16452                 "OpDecorate %ra_m2x2f16 ArrayStride 8 \n"
16453                 "OpDecorate %ra_m2x3f16 ArrayStride 16\n"
16454                 "OpDecorate %ra_m2x4f16 ArrayStride 16\n"
16455                 "OpDecorate %ra_m3x2f16 ArrayStride 16\n"
16456                 "OpDecorate %ra_m3x3f16 ArrayStride 32\n"
16457                 "OpDecorate %ra_m3x4f16 ArrayStride 32\n"
16458                 "OpDecorate %ra_m4x2f16 ArrayStride 16\n"
16459                 "OpDecorate %ra_m4x3f16 ArrayStride 32\n"
16460                 "OpDecorate %ra_m4x4f16 ArrayStride 32\n"
16461
16462                 "OpMemberDecorate %SSBO_f16     0 Offset 0\n"
16463                 "OpMemberDecorate %SSBO_v2f16   0 Offset 0\n"
16464                 "OpMemberDecorate %SSBO_v3f16   0 Offset 0\n"
16465                 "OpMemberDecorate %SSBO_v4f16   0 Offset 0\n"
16466                 "OpMemberDecorate %SSBO_m2x2f16 0 Offset 0\n"
16467                 "OpMemberDecorate %SSBO_m2x3f16 0 Offset 0\n"
16468                 "OpMemberDecorate %SSBO_m2x4f16 0 Offset 0\n"
16469                 "OpMemberDecorate %SSBO_m3x2f16 0 Offset 0\n"
16470                 "OpMemberDecorate %SSBO_m3x3f16 0 Offset 0\n"
16471                 "OpMemberDecorate %SSBO_m3x4f16 0 Offset 0\n"
16472                 "OpMemberDecorate %SSBO_m4x2f16 0 Offset 0\n"
16473                 "OpMemberDecorate %SSBO_m4x3f16 0 Offset 0\n"
16474                 "OpMemberDecorate %SSBO_m4x4f16 0 Offset 0\n"
16475
16476                 "OpDecorate %SSBO_f16     BufferBlock\n"
16477                 "OpDecorate %SSBO_v2f16   BufferBlock\n"
16478                 "OpDecorate %SSBO_v3f16   BufferBlock\n"
16479                 "OpDecorate %SSBO_v4f16   BufferBlock\n"
16480                 "OpDecorate %SSBO_m2x2f16 BufferBlock\n"
16481                 "OpDecorate %SSBO_m2x3f16 BufferBlock\n"
16482                 "OpDecorate %SSBO_m2x4f16 BufferBlock\n"
16483                 "OpDecorate %SSBO_m3x2f16 BufferBlock\n"
16484                 "OpDecorate %SSBO_m3x3f16 BufferBlock\n"
16485                 "OpDecorate %SSBO_m3x4f16 BufferBlock\n"
16486                 "OpDecorate %SSBO_m4x2f16 BufferBlock\n"
16487                 "OpDecorate %SSBO_m4x3f16 BufferBlock\n"
16488                 "OpDecorate %SSBO_m4x4f16 BufferBlock\n"
16489
16490                 "OpMemberDecorate %SSBO_m2x2f16 0 ColMajor\n"
16491                 "OpMemberDecorate %SSBO_m2x3f16 0 ColMajor\n"
16492                 "OpMemberDecorate %SSBO_m2x4f16 0 ColMajor\n"
16493                 "OpMemberDecorate %SSBO_m3x2f16 0 ColMajor\n"
16494                 "OpMemberDecorate %SSBO_m3x3f16 0 ColMajor\n"
16495                 "OpMemberDecorate %SSBO_m3x4f16 0 ColMajor\n"
16496                 "OpMemberDecorate %SSBO_m4x2f16 0 ColMajor\n"
16497                 "OpMemberDecorate %SSBO_m4x3f16 0 ColMajor\n"
16498                 "OpMemberDecorate %SSBO_m4x4f16 0 ColMajor\n"
16499
16500                 "OpMemberDecorate %SSBO_m2x2f16 0 MatrixStride 4\n"
16501                 "OpMemberDecorate %SSBO_m2x3f16 0 MatrixStride 8\n"
16502                 "OpMemberDecorate %SSBO_m2x4f16 0 MatrixStride 8\n"
16503                 "OpMemberDecorate %SSBO_m3x2f16 0 MatrixStride 4\n"
16504                 "OpMemberDecorate %SSBO_m3x3f16 0 MatrixStride 8\n"
16505                 "OpMemberDecorate %SSBO_m3x4f16 0 MatrixStride 8\n"
16506                 "OpMemberDecorate %SSBO_m4x2f16 0 MatrixStride 4\n"
16507                 "OpMemberDecorate %SSBO_m4x3f16 0 MatrixStride 8\n"
16508                 "OpMemberDecorate %SSBO_m4x4f16 0 MatrixStride 8\n"
16509
16510                 "${arg_decorations}"
16511         );
16512
16513         const StringTemplate testFun
16514         (
16515                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
16516                 "    %param = OpFunctionParameter %v4f32\n"
16517                 "    %entry = OpLabel\n"
16518
16519                 "        %i = OpVariable %fp_i32 Function\n"
16520                 "${arg_infunc_vars}"
16521                 "             OpStore %i %c_i32_0\n"
16522                 "             OpBranch %loop\n"
16523
16524                 "     %loop = OpLabel\n"
16525                 "    %i_cmp = OpLoad %i32 %i\n"
16526                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
16527                 "             OpLoopMerge %merge %next None\n"
16528                 "             OpBranchConditional %lt %write %merge\n"
16529
16530                 "    %write = OpLabel\n"
16531                 "      %ndx = OpLoad %i32 %i\n"
16532
16533                 "${arg_func_call}"
16534
16535                 "             OpBranch %next\n"
16536
16537                 "     %next = OpLabel\n"
16538                 "    %i_cur = OpLoad %i32 %i\n"
16539                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
16540                 "             OpStore %i %i_new\n"
16541                 "             OpBranch %loop\n"
16542
16543                 "    %merge = OpLabel\n"
16544                 "             OpReturnValue %param\n"
16545                 "             OpFunctionEnd\n"
16546         );
16547
16548         const Math16ArgFragments        argFragment1    =
16549         {
16550                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16551                 " %val_src0 = OpLoad %${t0} %src0\n"
16552                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0\n"
16553                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16554                 "             OpStore %dst %val_dst\n",
16555                 "",
16556                 "",
16557                 "",
16558         };
16559
16560         const Math16ArgFragments        argFragment2    =
16561         {
16562                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16563                 " %val_src0 = OpLoad %${t0} %src0\n"
16564                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16565                 " %val_src1 = OpLoad %${t1} %src1\n"
16566                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1\n"
16567                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16568                 "             OpStore %dst %val_dst\n",
16569                 "",
16570                 "",
16571                 "",
16572         };
16573
16574         const Math16ArgFragments        argFragment3    =
16575         {
16576                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16577                 " %val_src0 = OpLoad %${t0} %src0\n"
16578                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16579                 " %val_src1 = OpLoad %${t1} %src1\n"
16580                 "     %src2 = OpAccessChain %up_${t2} %ssbo_src2 %c_i32_0 %ndx\n"
16581                 " %val_src2 = OpLoad %${t2} %src2\n"
16582                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1 %val_src2\n"
16583                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16584                 "             OpStore %dst %val_dst\n",
16585                 "",
16586                 "",
16587                 "",
16588         };
16589
16590         const Math16ArgFragments        argFragmentLdExp        =
16591         {
16592                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16593                 " %val_src0 = OpLoad %${t0} %src0\n"
16594                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16595                 " %val_src1 = OpLoad %${t1} %src1\n"
16596                 "%val_src1i = OpConvertFToS %${dr}i32 %val_src1\n"
16597                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1i\n"
16598                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16599                 "             OpStore %dst %val_dst\n",
16600
16601                 "",
16602
16603                 "",
16604
16605                 "",
16606         };
16607
16608         const Math16ArgFragments        argFragmentModfFrac     =
16609         {
16610                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16611                 " %val_src0 = OpLoad %${t0} %src0\n"
16612                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16613                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16614                 "             OpStore %dst %val_dst\n",
16615
16616                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16617
16618                 "",
16619
16620                 "      %tmp = OpVariable %fp_tmp Function\n",
16621         };
16622
16623         const Math16ArgFragments        argFragmentModfInt      =
16624         {
16625                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16626                 " %val_src0 = OpLoad %${t0} %src0\n"
16627                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16628                 "     %tmp0 = OpAccessChain %fp_tmp %tmp\n"
16629                 "  %val_dst = OpLoad %${tr} %tmp0\n"
16630                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16631                 "             OpStore %dst %val_dst\n",
16632
16633                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16634
16635                 "",
16636
16637                 "      %tmp = OpVariable %fp_tmp Function\n",
16638         };
16639
16640         const Math16ArgFragments        argFragmentModfStruct   =
16641         {
16642                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16643                 " %val_src0 = OpLoad %${t0} %src0\n"
16644                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16645                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16646                 "             OpStore %tmp_ptr_s %val_tmp\n"
16647                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_${struct_member}\n"
16648                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16649                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16650                 "             OpStore %dst %val_dst\n",
16651
16652                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16653                 "   %st_tmp = OpTypeStruct %${tr} %${tr}\n"
16654                 "   %fp_tmp = OpTypePointer Function %st_tmp\n"
16655                 "   %c_frac = OpConstant %i32 0\n"
16656                 "    %c_int = OpConstant %i32 1\n",
16657
16658                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16659                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16660
16661                 "      %tmp = OpVariable %fp_tmp Function\n",
16662         };
16663
16664         const Math16ArgFragments        argFragmentFrexpStructS =
16665         {
16666                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16667                 " %val_src0 = OpLoad %${t0} %src0\n"
16668                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16669                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16670                 "             OpStore %tmp_ptr_s %val_tmp\n"
16671                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_i32_0\n"
16672                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16673                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16674                 "             OpStore %dst %val_dst\n",
16675
16676                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16677                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16678                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16679
16680                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16681                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16682
16683                 "      %tmp = OpVariable %fp_tmp Function\n",
16684         };
16685
16686         const Math16ArgFragments        argFragmentFrexpStructE =
16687         {
16688                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16689                 " %val_src0 = OpLoad %${t0} %src0\n"
16690                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16691                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16692                 "             OpStore %tmp_ptr_s %val_tmp\n"
16693                 "%tmp_ptr_l = OpAccessChain %fp_${dr}i32 %tmp %c_i32_1\n"
16694                 "%val_dst_i = OpLoad %${dr}i32 %tmp_ptr_l\n"
16695                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16696                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16697                 "             OpStore %dst %val_dst\n",
16698
16699                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16700                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16701
16702                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16703                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16704
16705                 "      %tmp = OpVariable %fp_tmp Function\n",
16706         };
16707
16708         const Math16ArgFragments        argFragmentFrexpS               =
16709         {
16710                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16711                 " %val_src0 = OpLoad %${t0} %src0\n"
16712                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16713                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16714                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16715                 "             OpStore %dst %val_dst\n",
16716
16717                 "",
16718
16719                 "",
16720
16721                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16722         };
16723
16724         const Math16ArgFragments        argFragmentFrexpE               =
16725         {
16726                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16727                 " %val_src0 = OpLoad %${t0} %src0\n"
16728                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16729                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16730                 "%val_dst_i = OpLoad %${dr}i32 %out_exp\n"
16731                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16732                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16733                 "             OpStore %dst %val_dst\n",
16734
16735                 "",
16736
16737                 "",
16738
16739                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16740         };
16741
16742         const Math16TestType&           testType                                = testTypes[testTypeIdx];
16743         const string                            funcNameString                  = string(testFunc.funcName) + string(testFunc.funcSuffix);
16744         const string                            testName                                = de::toLower(funcNameString);
16745         const Math16ArgFragments*       argFragments                    = DE_NULL;
16746         const size_t                            typeStructStride                = testType.typeStructStride;
16747         const bool                                      extInst                                 = !(testFunc.funcName[0] == 'O' && testFunc.funcName[1] == 'p');
16748         const size_t                            numFloatsPerArg0Type    = testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16);
16749         const size_t                            iterations                              = numDataPoints / numFloatsPerArg0Type;
16750         const size_t                            numFloatsPerResultType  = testTypes[testFunc.typeResult].typeArrayStride / sizeof(deFloat16);
16751         const vector<deFloat16>         float16DummyOutput              (iterations * numFloatsPerResultType, 0);
16752         VulkanFeatures                          features;
16753         SpecResource                            specResource;
16754         map<string, string>                     specs;
16755         map<string, string>                     fragments;
16756         vector<string>                          extensions;
16757         string                                          funcCall;
16758         string                                          funcVariables;
16759         string                                          variables;
16760         string                                          declarations;
16761         string                                          decorations;
16762
16763         switch (testFunc.funcArgsCount)
16764         {
16765                 case 1:
16766                 {
16767                         argFragments = &argFragment1;
16768
16769                         if (funcNameString == "ModfFrac")               argFragments = &argFragmentModfFrac;
16770                         if (funcNameString == "ModfInt")                argFragments = &argFragmentModfInt;
16771                         if (funcNameString == "ModfStructFrac") argFragments = &argFragmentModfStruct;
16772                         if (funcNameString == "ModfStructInt")  argFragments = &argFragmentModfStruct;
16773                         if (funcNameString == "FrexpS")                 argFragments = &argFragmentFrexpS;
16774                         if (funcNameString == "FrexpE")                 argFragments = &argFragmentFrexpE;
16775                         if (funcNameString == "FrexpStructS")   argFragments = &argFragmentFrexpStructS;
16776                         if (funcNameString == "FrexpStructE")   argFragments = &argFragmentFrexpStructE;
16777
16778                         break;
16779                 }
16780                 case 2:
16781                 {
16782                         argFragments = &argFragment2;
16783
16784                         if (funcNameString == "Ldexp")                  argFragments = &argFragmentLdExp;
16785
16786                         break;
16787                 }
16788                 case 3:
16789                 {
16790                         argFragments = &argFragment3;
16791
16792                         break;
16793                 }
16794                 default:
16795                 {
16796                         TCU_THROW(InternalError, "Invalid number of arguments");
16797                 }
16798         }
16799
16800         if (testFunc.funcArgsCount == 1)
16801         {
16802                 variables +=
16803                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16804                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16805
16806                 decorations +=
16807                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16808                         "OpDecorate %ssbo_src0 Binding 0\n"
16809                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16810                         "OpDecorate %ssbo_dst Binding 1\n";
16811         }
16812         else if (testFunc.funcArgsCount == 2)
16813         {
16814                 variables +=
16815                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16816                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16817                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16818
16819                 decorations +=
16820                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16821                         "OpDecorate %ssbo_src0 Binding 0\n"
16822                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16823                         "OpDecorate %ssbo_src1 Binding 1\n"
16824                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16825                         "OpDecorate %ssbo_dst Binding 2\n";
16826         }
16827         else if (testFunc.funcArgsCount == 3)
16828         {
16829                 variables +=
16830                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16831                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16832                         " %ssbo_src2 = OpVariable %up_SSBO_${t2} Uniform\n"
16833                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16834
16835                 decorations +=
16836                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16837                         "OpDecorate %ssbo_src0 Binding 0\n"
16838                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16839                         "OpDecorate %ssbo_src1 Binding 1\n"
16840                         "OpDecorate %ssbo_src2 DescriptorSet 0\n"
16841                         "OpDecorate %ssbo_src2 Binding 2\n"
16842                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16843                         "OpDecorate %ssbo_dst Binding 3\n";
16844         }
16845         else
16846         {
16847                 TCU_THROW(InternalError, "Invalid number of function arguments");
16848         }
16849
16850         variables       += argFragments->variables;
16851         decorations     += argFragments->decorations;
16852
16853         specs["dr"]                                     = testTypes[testFunc.typeResult].typePrefix;
16854         specs["d0"]                                     = testTypes[testFunc.typeArg0].typePrefix;
16855         specs["d1"]                                     = testTypes[testFunc.typeArg1].typePrefix;
16856         specs["d2"]                                     = testTypes[testFunc.typeArg2].typePrefix;
16857         specs["tr"]                                     = string(testTypes[testFunc.typeResult].typePrefix) + componentType;
16858         specs["t0"]                                     = string(testTypes[testFunc.typeArg0].typePrefix) + componentType;
16859         specs["t1"]                                     = string(testTypes[testFunc.typeArg1].typePrefix) + componentType;
16860         specs["t2"]                                     = string(testTypes[testFunc.typeArg2].typePrefix) + componentType;
16861         specs["struct_stride"]          = de::toString(typeStructStride);
16862         specs["op"]                                     = extInst ? "OpExtInst" : testFunc.funcName;
16863         specs["ext_inst"]                       = extInst ? string("%ext_import ") + testFunc.funcName : "";
16864         specs["struct_member"]          = de::toLower(testFunc.funcSuffix);
16865
16866         variables                                       = StringTemplate(variables).specialize(specs);
16867         decorations                                     = StringTemplate(decorations).specialize(specs);
16868         funcVariables                           = StringTemplate(argFragments->funcVariables).specialize(specs);
16869         funcCall                                        = StringTemplate(argFragments->bodies).specialize(specs);
16870
16871         specs["num_data_points"]        = de::toString(iterations);
16872         specs["arg_vars"]                       = variables;
16873         specs["arg_decorations"]        = decorations;
16874         specs["arg_infunc_vars"]        = funcVariables;
16875         specs["arg_func_call"]          = funcCall;
16876
16877         fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"\n%ext_import = OpExtInstImport \"GLSL.std.450\"";
16878         fragments["capability"]         = "OpCapability Matrix\nOpCapability StorageUniformBufferBlock16";
16879         fragments["decoration"]         = decoration.specialize(specs);
16880         fragments["pre_main"]           = preMain.specialize(specs);
16881         fragments["testfun"]            = testFun.specialize(specs);
16882
16883         for (size_t inputArgNdx = 0; inputArgNdx < testFunc.funcArgsCount; ++inputArgNdx)
16884         {
16885                 const size_t                    numFloatsPerItem        = (inputArgNdx == 0) ? testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16)
16886                                                                                                         : (inputArgNdx == 1) ? testTypes[testFunc.typeArg1].typeArrayStride / sizeof(deFloat16)
16887                                                                                                         : (inputArgNdx == 2) ? testTypes[testFunc.typeArg2].typeArrayStride / sizeof(deFloat16)
16888                                                                                                         : -1;
16889                 const vector<deFloat16> inputData                       = testFunc.getInputDataFunc(seed, numFloatsPerItem * iterations, testTypeIdx, numFloatsPerItem, testFunc.funcArgsCount, inputArgNdx);
16890
16891                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16892         }
16893
16894         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16DummyOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16895         specResource.verifyIO = testFunc.verifyFunc;
16896
16897         extensions.push_back("VK_KHR_16bit_storage");
16898         extensions.push_back("VK_KHR_shader_float16_int8");
16899
16900         features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
16901         features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
16902
16903         finalizeTestsCreation(specResource, fragments, testCtx, testGroup, testName, features, extensions, IVec3(1, 1, 1));
16904 }
16905
16906 template<size_t C, class SpecResource>
16907 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16908 {
16909         DE_STATIC_ASSERT(C >= 1 && C <= 4);
16910
16911         const std::string                               testGroupName   (string("arithmetic_") + de::toString(C));
16912         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16913         const Math16TestFunc                    testFuncs[]             =
16914         {
16915                 {       "OpFNegate",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16OpFNegate>                                       },
16916                 {       "Round",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Round>                                           },
16917                 {       "RoundEven",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16RoundEven>                                       },
16918                 {       "Trunc",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Trunc>                                           },
16919                 {       "FAbs",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FAbs>                                            },
16920                 {       "FSign",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FSign>                                           },
16921                 {       "Floor",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Floor>                                           },
16922                 {       "Ceil",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Ceil>                                            },
16923                 {       "Fract",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Fract>                                           },
16924                 {       "Radians",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Radians>                                         },
16925                 {       "Degrees",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Degrees>                                         },
16926                 {       "Sin",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sin>                                                     },
16927                 {       "Cos",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cos>                                                     },
16928                 {       "Tan",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tan>                                                     },
16929                 {       "Asin",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asin>                                            },
16930                 {       "Acos",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acos>                                            },
16931                 {       "Atan",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atan>                                            },
16932                 {       "Sinh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sinh>                                            },
16933                 {       "Cosh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cosh>                                            },
16934                 {       "Tanh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tanh>                                            },
16935                 {       "Asinh",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asinh>                                           },
16936                 {       "Acosh",                                "",                     1,      C,              C,              0,              0, &getInputDataAC,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acosh>                                           },
16937                 {       "Atanh",                                "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atanh>                                           },
16938                 {       "Exp",                                  "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp>                                                     },
16939                 {       "Log",                                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log>                                                     },
16940                 {       "Exp2",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp2>                                            },
16941                 {       "Log2",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log2>                                            },
16942                 {       "Sqrt",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sqrt>                                            },
16943                 {       "InverseSqrt",                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16InverseSqrt>                                     },
16944                 {       "Modf",                                 "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16945                 {       "Modf",                                 "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16946                 {       "ModfStruct",                   "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16947                 {       "ModfStruct",                   "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16948                 {       "Frexp",                                "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16949                 {       "Frexp",                                "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16950                 {       "FrexpStruct",                  "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16951                 {       "FrexpStruct",                  "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16952                 {       "OpFAdd",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFAdd>                                          },
16953                 {       "OpFSub",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFSub>                                          },
16954                 {       "OpFMul",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFMul>                                          },
16955                 {       "OpFDiv",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFDiv>                                          },
16956                 {       "Atan2",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Atan2>                                           },
16957                 {       "Pow",                                  "",                     2,      C,              C,              C,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Pow>                                                     },
16958                 {       "FMin",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMin>                                            },
16959                 {       "FMax",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMax>                                            },
16960                 {       "Step",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Step>                                            },
16961                 {       "Ldexp",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Ldexp>                                           },
16962                 {       "FClamp",                               "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FClamp>                                          },
16963                 {       "FMix",                                 "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FMix>                                            },
16964                 {       "SmoothStep",                   "",                     3,      C,              C,              C,              C, &getInputDataSS,     compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16SmoothStep>                                      },
16965                 {       "Fma",                                  "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16Fma>                                                     },
16966                 {       "Length",                               "",                     1,      1,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  0,  0, fp16Length>                                          },
16967                 {       "Distance",                             "",                     2,      1,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Distance>                                        },
16968                 {       "Cross",                                "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Cross>                                           },
16969                 {       "Normalize",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Normalize>                                       },
16970                 {       "FaceForward",                  "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FaceForward>                                     },
16971                 {       "Reflect",                              "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Reflect>                                         },
16972                 {       "Refract",                              "",                     3,      C,              C,              C,              1, &getInputDataN,      compareFP16ArithmeticFunc<  C,  C,  C,  1, fp16Refract>                                         },
16973                 {       "OpDot",                                "",                     2,      1,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Dot>                                                     },
16974                 {       "OpVectorTimesScalar",  "",                     2,      C,              C,              1,              0, &getInputDataV,      compareFP16ArithmeticFunc<  C,  C,  1,  0, fp16VectorTimesScalar>                       },
16975         };
16976
16977         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16978         {
16979                 const Math16TestFunc&   testFunc                = testFuncs[testFuncIdx];
16980                 const string                    funcNameString  = testFunc.funcName;
16981
16982                 if ((C != 3) && funcNameString == "Cross")
16983                         continue;
16984
16985                 if ((C < 2) && funcNameString == "OpDot")
16986                         continue;
16987
16988                 if ((C < 2) && funcNameString == "OpVectorTimesScalar")
16989                         continue;
16990
16991                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), C, testFunc);
16992         }
16993
16994         return testGroup.release();
16995 }
16996
16997 template<class SpecResource>
16998 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16999 {
17000         const std::string                               testGroupName   ("arithmetic");
17001         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
17002         const Math16TestFunc                    testFuncs[]             =
17003         {
17004                 {       "OpTranspose",                  "2x2",          1,      MAT2X2, MAT2X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Transpose<2,2> >                         },
17005                 {       "OpTranspose",                  "3x2",          1,      MAT2X3, MAT3X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<3,2> >                         },
17006                 {       "OpTranspose",                  "4x2",          1,      MAT2X4, MAT4X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<4,2> >                         },
17007                 {       "OpTranspose",                  "2x3",          1,      MAT3X2, MAT2X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,3> >                         },
17008                 {       "OpTranspose",                  "3x3",          1,      MAT3X3, MAT3X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,3> >                         },
17009                 {       "OpTranspose",                  "4x3",          1,      MAT3X4, MAT4X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,3> >                         },
17010                 {       "OpTranspose",                  "2x4",          1,      MAT4X2, MAT2X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,4> >                         },
17011                 {       "OpTranspose",                  "3x4",          1,      MAT4X3, MAT3X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,4> >                         },
17012                 {       "OpTranspose",                  "4x4",          1,      MAT4X4, MAT4X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,4> >                         },
17013                 {       "OpMatrixTimesScalar",  "2x2",          2,      MAT2X2, MAT2X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  1,  0, fp16MatrixTimesScalar<2,2> >         },
17014                 {       "OpMatrixTimesScalar",  "2x3",          2,      MAT2X3, MAT2X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,3> >         },
17015                 {       "OpMatrixTimesScalar",  "2x4",          2,      MAT2X4, MAT2X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,4> >         },
17016                 {       "OpMatrixTimesScalar",  "3x2",          2,      MAT3X2, MAT3X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<3,2> >         },
17017                 {       "OpMatrixTimesScalar",  "3x3",          2,      MAT3X3, MAT3X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,3> >         },
17018                 {       "OpMatrixTimesScalar",  "3x4",          2,      MAT3X4, MAT3X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,4> >         },
17019                 {       "OpMatrixTimesScalar",  "4x2",          2,      MAT4X2, MAT4X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<4,2> >         },
17020                 {       "OpMatrixTimesScalar",  "4x3",          2,      MAT4X3, MAT4X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,3> >         },
17021                 {       "OpMatrixTimesScalar",  "4x4",          2,      MAT4X4, MAT4X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,4> >         },
17022                 {       "OpVectorTimesMatrix",  "2x2",          2,      VEC2,   VEC2,   MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  2,  4,  0, fp16VectorTimesMatrix<2,2> >         },
17023                 {       "OpVectorTimesMatrix",  "2x3",          2,      VEC2,   VEC3,   MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  3,  8,  0, fp16VectorTimesMatrix<2,3> >         },
17024                 {       "OpVectorTimesMatrix",  "2x4",          2,      VEC2,   VEC4,   MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  8,  0, fp16VectorTimesMatrix<2,4> >         },
17025                 {       "OpVectorTimesMatrix",  "3x2",          2,      VEC3,   VEC2,   MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  2,  8,  0, fp16VectorTimesMatrix<3,2> >         },
17026                 {       "OpVectorTimesMatrix",  "3x3",          2,      VEC3,   VEC3,   MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  3, 16,  0, fp16VectorTimesMatrix<3,3> >         },
17027                 {       "OpVectorTimesMatrix",  "3x4",          2,      VEC3,   VEC4,   MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  4, 16,  0, fp16VectorTimesMatrix<3,4> >         },
17028                 {       "OpVectorTimesMatrix",  "4x2",          2,      VEC4,   VEC2,   MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  8,  0, fp16VectorTimesMatrix<4,2> >         },
17029                 {       "OpVectorTimesMatrix",  "4x3",          2,      VEC4,   VEC3,   MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  3, 16,  0, fp16VectorTimesMatrix<4,3> >         },
17030                 {       "OpVectorTimesMatrix",  "4x4",          2,      VEC4,   VEC4,   MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4, 16,  0, fp16VectorTimesMatrix<4,4> >         },
17031                 {       "OpMatrixTimesVector",  "2x2",          2,      VEC2,   MAT2X2, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  2,  0, fp16MatrixTimesVector<2,2> >         },
17032                 {       "OpMatrixTimesVector",  "2x3",          2,      VEC3,   MAT2X3, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  8,  2,  0, fp16MatrixTimesVector<2,3> >         },
17033                 {       "OpMatrixTimesVector",  "2x4",          2,      VEC4,   MAT2X4, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  2,  0, fp16MatrixTimesVector<2,4> >         },
17034                 {       "OpMatrixTimesVector",  "3x2",          2,      VEC2,   MAT3X2, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  3,  0, fp16MatrixTimesVector<3,2> >         },
17035                 {       "OpMatrixTimesVector",  "3x3",          2,      VEC3,   MAT3X3, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  3,  0, fp16MatrixTimesVector<3,3> >         },
17036                 {       "OpMatrixTimesVector",  "3x4",          2,      VEC4,   MAT3X4, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  3,  0, fp16MatrixTimesVector<3,4> >         },
17037                 {       "OpMatrixTimesVector",  "4x2",          2,      VEC2,   MAT4X2, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  4,  0, fp16MatrixTimesVector<4,2> >         },
17038                 {       "OpMatrixTimesVector",  "4x3",          2,      VEC3,   MAT4X3, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  4,  0, fp16MatrixTimesVector<4,3> >         },
17039                 {       "OpMatrixTimesVector",  "4x4",          2,      VEC4,   MAT4X4, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  4,  0, fp16MatrixTimesVector<4,4> >         },
17040                 {       "OpMatrixTimesMatrix",  "2x2_2x2",      2,      MAT2X2, MAT2X2, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  4,  0, fp16MatrixTimesMatrix<2,2,2,2> >     },
17041                 {       "OpMatrixTimesMatrix",  "2x2_3x2",      2,      MAT3X2, MAT2X2, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,3,2> >     },
17042                 {       "OpMatrixTimesMatrix",  "2x2_4x2",      2,      MAT4X2, MAT2X2, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,4,2> >     },
17043                 {       "OpMatrixTimesMatrix",  "2x3_2x2",      2,      MAT2X3, MAT2X3, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,3,2,2> >     },
17044                 {       "OpMatrixTimesMatrix",  "2x3_3x2",      2,      MAT3X3, MAT2X3, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,3,2> >     },
17045                 {       "OpMatrixTimesMatrix",  "2x3_4x2",      2,      MAT4X3, MAT2X3, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,4,2> >     },
17046                 {       "OpMatrixTimesMatrix",  "2x4_2x2",      2,      MAT2X4, MAT2X4, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,4,2,2> >     },
17047                 {       "OpMatrixTimesMatrix",  "2x4_3x2",      2,      MAT3X4, MAT2X4, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,3,2> >     },
17048                 {       "OpMatrixTimesMatrix",  "2x4_4x2",      2,      MAT4X4, MAT2X4, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,4,2> >     },
17049                 {       "OpMatrixTimesMatrix",  "3x2_2x3",      2,      MAT2X2, MAT3X2, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<3,2,2,3> >     },
17050                 {       "OpMatrixTimesMatrix",  "3x2_3x3",      2,      MAT3X2, MAT3X2, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,3,3> >     },
17051                 {       "OpMatrixTimesMatrix",  "3x2_4x3",      2,      MAT4X2, MAT3X2, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,4,3> >     },
17052                 {       "OpMatrixTimesMatrix",  "3x3_2x3",      2,      MAT2X3, MAT3X3, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,3,2,3> >     },
17053                 {       "OpMatrixTimesMatrix",  "3x3_3x3",      2,      MAT3X3, MAT3X3, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,3,3> >     },
17054                 {       "OpMatrixTimesMatrix",  "3x3_4x3",      2,      MAT4X3, MAT3X3, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,4,3> >     },
17055                 {       "OpMatrixTimesMatrix",  "3x4_2x3",      2,      MAT2X4, MAT3X4, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,4,2,3> >     },
17056                 {       "OpMatrixTimesMatrix",  "3x4_3x3",      2,      MAT3X4, MAT3X4, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,3,3> >     },
17057                 {       "OpMatrixTimesMatrix",  "3x4_4x3",      2,      MAT4X4, MAT3X4, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,4,3> >     },
17058                 {       "OpMatrixTimesMatrix",  "4x2_2x4",      2,      MAT2X2, MAT4X2, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<4,2,2,4> >     },
17059                 {       "OpMatrixTimesMatrix",  "4x2_3x4",      2,      MAT3X2, MAT4X2, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,3,4> >     },
17060                 {       "OpMatrixTimesMatrix",  "4x2_4x4",      2,      MAT4X2, MAT4X2, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,4,4> >     },
17061                 {       "OpMatrixTimesMatrix",  "4x3_2x4",      2,      MAT2X3, MAT4X3, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,3,2,4> >     },
17062                 {       "OpMatrixTimesMatrix",  "4x3_3x4",      2,      MAT3X3, MAT4X3, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,3,4> >     },
17063                 {       "OpMatrixTimesMatrix",  "4x3_4x4",      2,      MAT4X3, MAT4X3, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,4,4> >     },
17064                 {       "OpMatrixTimesMatrix",  "4x4_2x4",      2,      MAT2X4, MAT4X4, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,4,2,4> >     },
17065                 {       "OpMatrixTimesMatrix",  "4x4_3x4",      2,      MAT3X4, MAT4X4, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,3,4> >     },
17066                 {       "OpMatrixTimesMatrix",  "4x4_4x4",      2,      MAT4X4, MAT4X4, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,4,4> >     },
17067                 {       "OpOuterProduct",               "2x2",          2,      MAT2X2, VEC2,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  2,  0, fp16OuterProduct<2,2> >                      },
17068                 {       "OpOuterProduct",               "2x3",          2,      MAT2X3, VEC3,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  3,  2,  0, fp16OuterProduct<2,3> >                      },
17069                 {       "OpOuterProduct",               "2x4",          2,      MAT2X4, VEC4,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  2,  0, fp16OuterProduct<2,4> >                      },
17070                 {       "OpOuterProduct",               "3x2",          2,      MAT3X2, VEC2,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  3,  0, fp16OuterProduct<3,2> >                      },
17071                 {       "OpOuterProduct",               "3x3",          2,      MAT3X3, VEC3,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  3,  0, fp16OuterProduct<3,3> >                      },
17072                 {       "OpOuterProduct",               "3x4",          2,      MAT3X4, VEC4,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  3,  0, fp16OuterProduct<3,4> >                      },
17073                 {       "OpOuterProduct",               "4x2",          2,      MAT4X2, VEC2,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  4,  0, fp16OuterProduct<4,2> >                      },
17074                 {       "OpOuterProduct",               "4x3",          2,      MAT4X3, VEC3,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  4,  0, fp16OuterProduct<4,3> >                      },
17075                 {       "OpOuterProduct",               "4x4",          2,      MAT4X4, VEC4,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  4,  0, fp16OuterProduct<4,4> >                      },
17076                 {       "Determinant",                  "2x2",          1,      SCALAR, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1,  4,  0,  0, fp16Determinant<2> >                         },
17077                 {       "Determinant",                  "3x3",          1,      SCALAR, MAT3X3, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<3> >                         },
17078                 {       "Determinant",                  "4x4",          1,      SCALAR, MAT4X4, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<4> >                         },
17079                 {       "MatrixInverse",                "2x2",          1,      MAT2X2, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Inverse<2> >                                     },
17080         };
17081
17082         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
17083         {
17084                 const Math16TestFunc&   testFunc        = testFuncs[testFuncIdx];
17085
17086                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), 0, testFunc);
17087         }
17088
17089         return testGroup.release();
17090 }
17091
17092 const string getNumberTypeName (const NumberType type)
17093 {
17094         if (type == NUMBERTYPE_INT32)
17095         {
17096                 return "int";
17097         }
17098         else if (type == NUMBERTYPE_UINT32)
17099         {
17100                 return "uint";
17101         }
17102         else if (type == NUMBERTYPE_FLOAT32)
17103         {
17104                 return "float";
17105         }
17106         else
17107         {
17108                 DE_ASSERT(false);
17109                 return "";
17110         }
17111 }
17112
17113 deInt32 getInt(de::Random& rnd)
17114 {
17115         return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
17116 }
17117
17118 const string repeatString (const string& str, int times)
17119 {
17120         string filler;
17121         for (int i = 0; i < times; ++i)
17122         {
17123                 filler += str;
17124         }
17125         return filler;
17126 }
17127
17128 const string getRandomConstantString (const NumberType type, de::Random& rnd)
17129 {
17130         if (type == NUMBERTYPE_INT32)
17131         {
17132                 return numberToString<deInt32>(getInt(rnd));
17133         }
17134         else if (type == NUMBERTYPE_UINT32)
17135         {
17136                 return numberToString<deUint32>(rnd.getUint32());
17137         }
17138         else if (type == NUMBERTYPE_FLOAT32)
17139         {
17140                 return numberToString<float>(rnd.getFloat());
17141         }
17142         else
17143         {
17144                 DE_ASSERT(false);
17145                 return "";
17146         }
17147 }
17148
17149 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17150 {
17151         map<string, string> params;
17152
17153         // Vec2 to Vec4
17154         for (int width = 2; width <= 4; ++width)
17155         {
17156                 const string randomConst = numberToString(getInt(rnd));
17157                 const string widthStr = numberToString(width);
17158                 const string composite_type = "${customType}vec" + widthStr;
17159                 const int index = rnd.getInt(0, width-1);
17160
17161                 params["type"]                  = "vec";
17162                 params["name"]                  = params["type"] + "_" + widthStr;
17163                 params["compositeDecl"]         = composite_type + " = OpTypeVector ${customType} " + widthStr +"\n";
17164                 params["compositeType"]         = composite_type;
17165                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
17166                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct " + composite_type + repeatString(" %filler", width) + "\n";
17167                 params["indexes"]               = numberToString(index);
17168                 testCases.push_back(params);
17169         }
17170 }
17171
17172 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17173 {
17174         const int limit = 10;
17175         map<string, string> params;
17176
17177         for (int width = 2; width <= limit; ++width)
17178         {
17179                 string randomConst = numberToString(getInt(rnd));
17180                 string widthStr = numberToString(width);
17181                 int index = rnd.getInt(0, width-1);
17182
17183                 params["type"]                  = "array";
17184                 params["name"]                  = params["type"] + "_" + widthStr;
17185                 params["compositeDecl"]         = string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
17186                                                                                         +        "%composite = OpTypeArray ${customType} %arraywidth\n";
17187                 params["compositeType"]         = "%composite";
17188                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
17189                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
17190                 params["indexes"]               = numberToString(index);
17191                 testCases.push_back(params);
17192         }
17193 }
17194
17195 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17196 {
17197         const int limit = 10;
17198         map<string, string> params;
17199
17200         for (int width = 2; width <= limit; ++width)
17201         {
17202                 string randomConst = numberToString(getInt(rnd));
17203                 int index = rnd.getInt(0, width-1);
17204
17205                 params["type"]                  = "struct";
17206                 params["name"]                  = params["type"] + "_" + numberToString(width);
17207                 params["compositeDecl"]         = "%composite = OpTypeStruct" + repeatString(" ${customType}", width) + "\n";
17208                 params["compositeType"]         = "%composite";
17209                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
17210                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
17211                 params["indexes"]               = numberToString(index);
17212                 testCases.push_back(params);
17213         }
17214 }
17215
17216 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17217 {
17218         map<string, string> params;
17219
17220         // Vec2 to Vec4
17221         for (int width = 2; width <= 4; ++width)
17222         {
17223                 string widthStr = numberToString(width);
17224
17225                 for (int column = 2 ; column <= 4; ++column)
17226                 {
17227                         int index_0 = rnd.getInt(0, column-1);
17228                         int index_1 = rnd.getInt(0, width-1);
17229                         string columnStr = numberToString(column);
17230
17231                         params["type"]          = "matrix";
17232                         params["name"]          = params["type"] + "_" + widthStr + "x" + columnStr;
17233                         params["compositeDecl"] = string("%vectype   = OpTypeVector ${customType} " + widthStr + "\n")
17234                                                                                                 +        "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
17235                         params["compositeType"] = "%composite";
17236
17237                         params["filler"]        = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n"
17238                                                                                                 +        "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
17239
17240                         params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
17241                         params["indexes"]       = numberToString(index_0) + " " + numberToString(index_1);
17242                         testCases.push_back(params);
17243                 }
17244         }
17245 }
17246
17247 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17248 {
17249         createVectorCompositeCases(testCases, rnd, type);
17250         createArrayCompositeCases(testCases, rnd, type);
17251         createStructCompositeCases(testCases, rnd, type);
17252         // Matrix only supports float types
17253         if (type == NUMBERTYPE_FLOAT32)
17254         {
17255                 createMatrixCompositeCases(testCases, rnd, type);
17256         }
17257 }
17258
17259 const string getAssemblyTypeDeclaration (const NumberType type)
17260 {
17261         switch (type)
17262         {
17263                 case NUMBERTYPE_INT32:          return "OpTypeInt 32 1";
17264                 case NUMBERTYPE_UINT32:         return "OpTypeInt 32 0";
17265                 case NUMBERTYPE_FLOAT32:        return "OpTypeFloat 32";
17266                 default:                        DE_ASSERT(false); return "";
17267         }
17268 }
17269
17270 const string getAssemblyTypeName (const NumberType type)
17271 {
17272         switch (type)
17273         {
17274                 case NUMBERTYPE_INT32:          return "%i32";
17275                 case NUMBERTYPE_UINT32:         return "%u32";
17276                 case NUMBERTYPE_FLOAT32:        return "%f32";
17277                 default:                        DE_ASSERT(false); return "";
17278         }
17279 }
17280
17281 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
17282 {
17283         map<string, string>     parameters(params);
17284
17285         const string customType = getAssemblyTypeName(type);
17286         map<string, string> substCustomType;
17287         substCustomType["customType"] = customType;
17288         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17289         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17290         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17291         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17292         parameters["customType"] = customType;
17293         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17294
17295         if (parameters.at("compositeType") != "%u32vec3")
17296         {
17297                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17298         }
17299
17300         return StringTemplate(
17301                 "OpCapability Shader\n"
17302                 "OpCapability Matrix\n"
17303                 "OpMemoryModel Logical GLSL450\n"
17304                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17305                 "OpExecutionMode %main LocalSize 1 1 1\n"
17306
17307                 "OpSource GLSL 430\n"
17308                 "OpName %main           \"main\"\n"
17309                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17310
17311                 // Decorators
17312                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17313                 "OpDecorate %buf BufferBlock\n"
17314                 "OpDecorate %indata DescriptorSet 0\n"
17315                 "OpDecorate %indata Binding 0\n"
17316                 "OpDecorate %outdata DescriptorSet 0\n"
17317                 "OpDecorate %outdata Binding 1\n"
17318                 "OpDecorate %customarr ArrayStride 4\n"
17319                 "${compositeDecorator}"
17320                 "OpMemberDecorate %buf 0 Offset 0\n"
17321
17322                 // General types
17323                 "%void      = OpTypeVoid\n"
17324                 "%voidf     = OpTypeFunction %void\n"
17325                 "%u32       = OpTypeInt 32 0\n"
17326                 "%i32       = OpTypeInt 32 1\n"
17327                 "%f32       = OpTypeFloat 32\n"
17328
17329                 // Composite declaration
17330                 "${compositeDecl}"
17331
17332                 // Constants
17333                 "${filler}"
17334
17335                 "${u32vec3Decl:opt}"
17336                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17337
17338                 // Inherited from custom
17339                 "%customptr = OpTypePointer Uniform ${customType}\n"
17340                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17341                 "%buf       = OpTypeStruct %customarr\n"
17342                 "%bufptr    = OpTypePointer Uniform %buf\n"
17343
17344                 "%indata    = OpVariable %bufptr Uniform\n"
17345                 "%outdata   = OpVariable %bufptr Uniform\n"
17346
17347                 "%id        = OpVariable %uvec3ptr Input\n"
17348                 "%zero      = OpConstant %i32 0\n"
17349
17350                 "%main      = OpFunction %void None %voidf\n"
17351                 "%label     = OpLabel\n"
17352                 "%idval     = OpLoad %u32vec3 %id\n"
17353                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17354
17355                 "%inloc     = OpAccessChain %customptr %indata %zero %x\n"
17356                 "%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
17357                 // Read the input value
17358                 "%inval     = OpLoad ${customType} %inloc\n"
17359                 // Create the composite and fill it
17360                 "${compositeConstruct}"
17361                 // Insert the input value to a place
17362                 "%instance2 = OpCompositeInsert ${compositeType} %inval %instance ${indexes}\n"
17363                 // Read back the value from the position
17364                 "%out_val   = OpCompositeExtract ${customType} %instance2 ${indexes}\n"
17365                 // Store it in the output position
17366                 "             OpStore %outloc %out_val\n"
17367                 "             OpReturn\n"
17368                 "             OpFunctionEnd\n"
17369         ).specialize(parameters);
17370 }
17371
17372 template<typename T>
17373 BufferSp createCompositeBuffer(T number)
17374 {
17375         return BufferSp(new Buffer<T>(vector<T>(1, number)));
17376 }
17377
17378 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
17379 {
17380         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
17381         de::Random                                              rnd             (deStringHash(group->getName()));
17382
17383         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17384         {
17385                 NumberType                                              numberType              = NumberType(type);
17386                 const string                                    typeName                = getNumberTypeName(numberType);
17387                 const string                                    description             = "Test the OpCompositeInsert instruction with " + typeName + "s";
17388                 de::MovePtr<tcu::TestCaseGroup> subGroup                (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17389                 vector<map<string, string> >    testCases;
17390
17391                 createCompositeCases(testCases, rnd, numberType);
17392
17393                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17394                 {
17395                         ComputeShaderSpec       spec;
17396
17397                         spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
17398
17399                         switch (numberType)
17400                         {
17401                                 case NUMBERTYPE_INT32:
17402                                 {
17403                                         deInt32 number = getInt(rnd);
17404                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17405                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17406                                         break;
17407                                 }
17408                                 case NUMBERTYPE_UINT32:
17409                                 {
17410                                         deUint32 number = rnd.getUint32();
17411                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17412                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17413                                         break;
17414                                 }
17415                                 case NUMBERTYPE_FLOAT32:
17416                                 {
17417                                         float number = rnd.getFloat();
17418                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17419                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17420                                         break;
17421                                 }
17422                                 default:
17423                                         DE_ASSERT(false);
17424                         }
17425
17426                         spec.numWorkGroups = IVec3(1, 1, 1);
17427                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
17428                 }
17429                 group->addChild(subGroup.release());
17430         }
17431         return group.release();
17432 }
17433
17434 struct AssemblyStructInfo
17435 {
17436         AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
17437         : components    (comp)
17438         , index                 (idx)
17439         {}
17440
17441         deUint32 components;
17442         deUint32 index;
17443 };
17444
17445 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
17446 {
17447         // Create the full index string
17448         string                          fullIndex       = numberToString(structInfo.index) + " " + params.at("indexes");
17449         // Convert it to list of indexes
17450         vector<string>          indexes         = de::splitString(fullIndex, ' ');
17451
17452         map<string, string>     parameters      (params);
17453         parameters["structType"]        = repeatString(" ${compositeType}", structInfo.components);
17454         parameters["structConstruct"]   = repeatString(" %instance", structInfo.components);
17455         parameters["insertIndexes"]     = fullIndex;
17456
17457         // In matrix cases the last two index is the CompositeExtract indexes
17458         const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
17459
17460         // Construct the extractIndex
17461         for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
17462         {
17463                 parameters["extractIndexes"] += " " + *index;
17464         }
17465
17466         // Remove the last 1 or 2 element depends on matrix case or not
17467         indexes.erase(indexes.end() - extractIndexes, indexes.end());
17468
17469         deUint32 id = 0;
17470         // Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
17471         for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
17472         {
17473                 string indexId = "%index_" + numberToString(id++);
17474                 parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
17475                 parameters["accessChainIndexes"] += " " + indexId;
17476         }
17477
17478         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17479
17480         const string customType = getAssemblyTypeName(type);
17481         map<string, string> substCustomType;
17482         substCustomType["customType"] = customType;
17483         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17484         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17485         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17486         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17487         parameters["customType"] = customType;
17488
17489         const string compositeType = parameters.at("compositeType");
17490         map<string, string> substCompositeType;
17491         substCompositeType["compositeType"] = compositeType;
17492         parameters["structType"] = StringTemplate(parameters.at("structType")).specialize(substCompositeType);
17493         if (compositeType != "%u32vec3")
17494         {
17495                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17496         }
17497
17498         return StringTemplate(
17499                 "OpCapability Shader\n"
17500                 "OpCapability Matrix\n"
17501                 "OpMemoryModel Logical GLSL450\n"
17502                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17503                 "OpExecutionMode %main LocalSize 1 1 1\n"
17504
17505                 "OpSource GLSL 430\n"
17506                 "OpName %main           \"main\"\n"
17507                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17508                 // Decorators
17509                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17510                 "OpDecorate %buf BufferBlock\n"
17511                 "OpDecorate %indata DescriptorSet 0\n"
17512                 "OpDecorate %indata Binding 0\n"
17513                 "OpDecorate %outdata DescriptorSet 0\n"
17514                 "OpDecorate %outdata Binding 1\n"
17515                 "OpDecorate %customarr ArrayStride 4\n"
17516                 "${compositeDecorator}"
17517                 "OpMemberDecorate %buf 0 Offset 0\n"
17518                 // General types
17519                 "%void      = OpTypeVoid\n"
17520                 "%voidf     = OpTypeFunction %void\n"
17521                 "%i32       = OpTypeInt 32 1\n"
17522                 "%u32       = OpTypeInt 32 0\n"
17523                 "%f32       = OpTypeFloat 32\n"
17524                 // Custom types
17525                 "${compositeDecl}"
17526                 // %u32vec3 if not already declared in ${compositeDecl}
17527                 "${u32vec3Decl:opt}"
17528                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17529                 // Inherited from composite
17530                 "%composite_p = OpTypePointer Function ${compositeType}\n"
17531                 "%struct_t  = OpTypeStruct${structType}\n"
17532                 "%struct_p  = OpTypePointer Function %struct_t\n"
17533                 // Constants
17534                 "${filler}"
17535                 "${accessChainConstDeclaration}"
17536                 // Inherited from custom
17537                 "%customptr = OpTypePointer Uniform ${customType}\n"
17538                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17539                 "%buf       = OpTypeStruct %customarr\n"
17540                 "%bufptr    = OpTypePointer Uniform %buf\n"
17541                 "%indata    = OpVariable %bufptr Uniform\n"
17542                 "%outdata   = OpVariable %bufptr Uniform\n"
17543
17544                 "%id        = OpVariable %uvec3ptr Input\n"
17545                 "%zero      = OpConstant %u32 0\n"
17546                 "%main      = OpFunction %void None %voidf\n"
17547                 "%label     = OpLabel\n"
17548                 "%struct_v  = OpVariable %struct_p Function\n"
17549                 "%idval     = OpLoad %u32vec3 %id\n"
17550                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17551                 // Create the input/output type
17552                 "%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
17553                 "%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
17554                 // Read the input value
17555                 "%inval     = OpLoad ${customType} %inloc\n"
17556                 // Create the composite and fill it
17557                 "${compositeConstruct}"
17558                 // Create the struct and fill it with the composite
17559                 "%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
17560                 // Insert the value
17561                 "%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
17562                 // Store the object
17563                 "             OpStore %struct_v %comp_obj\n"
17564                 // Get deepest possible composite pointer
17565                 "%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
17566                 "%read_obj  = OpLoad ${compositeType} %inner_ptr\n"
17567                 // Read back the stored value
17568                 "%read_val  = OpCompositeExtract ${customType} %read_obj${extractIndexes}\n"
17569                 "             OpStore %outloc %read_val\n"
17570                 "             OpReturn\n"
17571                 "             OpFunctionEnd\n"
17572         ).specialize(parameters);
17573 }
17574
17575 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
17576 {
17577         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
17578         de::Random                                              rnd                             (deStringHash(group->getName()));
17579
17580         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17581         {
17582                 NumberType                                              numberType      = NumberType(type);
17583                 const string                                    typeName        = getNumberTypeName(numberType);
17584                 const string                                    description     = "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
17585                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17586
17587                 vector<map<string, string> >    testCases;
17588                 createCompositeCases(testCases, rnd, numberType);
17589
17590                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17591                 {
17592                         ComputeShaderSpec       spec;
17593
17594                         // Number of components inside of a struct
17595                         deUint32 structComponents = rnd.getInt(2, 8);
17596                         // Component index value
17597                         deUint32 structIndex = rnd.getInt(0, structComponents - 1);
17598                         AssemblyStructInfo structInfo(structComponents, structIndex);
17599
17600                         spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
17601
17602                         switch (numberType)
17603                         {
17604                                 case NUMBERTYPE_INT32:
17605                                 {
17606                                         deInt32 number = getInt(rnd);
17607                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17608                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17609                                         break;
17610                                 }
17611                                 case NUMBERTYPE_UINT32:
17612                                 {
17613                                         deUint32 number = rnd.getUint32();
17614                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17615                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17616                                         break;
17617                                 }
17618                                 case NUMBERTYPE_FLOAT32:
17619                                 {
17620                                         float number = rnd.getFloat();
17621                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17622                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17623                                         break;
17624                                 }
17625                                 default:
17626                                         DE_ASSERT(false);
17627                         }
17628                         spec.numWorkGroups = IVec3(1, 1, 1);
17629                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
17630                 }
17631                 group->addChild(subGroup.release());
17632         }
17633         return group.release();
17634 }
17635
17636 // If the params missing, uninitialized case
17637 const string specializeDefaultOutputShaderTemplate (const NumberType type, const map<string, string>& params = map<string, string>())
17638 {
17639         map<string, string> parameters(params);
17640
17641         parameters["customType"]        = getAssemblyTypeName(type);
17642
17643         // Declare the const value, and use it in the initializer
17644         if (params.find("constValue") != params.end())
17645         {
17646                 parameters["variableInitializer"]       = " %const";
17647         }
17648         // Uninitialized case
17649         else
17650         {
17651                 parameters["commentDecl"]       = ";";
17652         }
17653
17654         return StringTemplate(
17655                 "OpCapability Shader\n"
17656                 "OpMemoryModel Logical GLSL450\n"
17657                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17658                 "OpExecutionMode %main LocalSize 1 1 1\n"
17659                 "OpSource GLSL 430\n"
17660                 "OpName %main           \"main\"\n"
17661                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17662                 // Decorators
17663                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17664                 "OpDecorate %indata DescriptorSet 0\n"
17665                 "OpDecorate %indata Binding 0\n"
17666                 "OpDecorate %outdata DescriptorSet 0\n"
17667                 "OpDecorate %outdata Binding 1\n"
17668                 "OpDecorate %in_arr ArrayStride 4\n"
17669                 "OpDecorate %in_buf BufferBlock\n"
17670                 "OpMemberDecorate %in_buf 0 Offset 0\n"
17671                 // Base types
17672                 "%void       = OpTypeVoid\n"
17673                 "%voidf      = OpTypeFunction %void\n"
17674                 "%u32        = OpTypeInt 32 0\n"
17675                 "%i32        = OpTypeInt 32 1\n"
17676                 "%f32        = OpTypeFloat 32\n"
17677                 "%uvec3      = OpTypeVector %u32 3\n"
17678                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
17679                 "${commentDecl:opt}%const      = OpConstant ${customType} ${constValue:opt}\n"
17680                 // Derived types
17681                 "%in_ptr     = OpTypePointer Uniform ${customType}\n"
17682                 "%in_arr     = OpTypeRuntimeArray ${customType}\n"
17683                 "%in_buf     = OpTypeStruct %in_arr\n"
17684                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
17685                 "%indata     = OpVariable %in_bufptr Uniform\n"
17686                 "%outdata    = OpVariable %in_bufptr Uniform\n"
17687                 "%id         = OpVariable %uvec3ptr Input\n"
17688                 "%var_ptr    = OpTypePointer Function ${customType}\n"
17689                 // Constants
17690                 "%zero       = OpConstant %i32 0\n"
17691                 // Main function
17692                 "%main       = OpFunction %void None %voidf\n"
17693                 "%label      = OpLabel\n"
17694                 "%out_var    = OpVariable %var_ptr Function${variableInitializer:opt}\n"
17695                 "%idval      = OpLoad %uvec3 %id\n"
17696                 "%x          = OpCompositeExtract %u32 %idval 0\n"
17697                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
17698                 "%outloc     = OpAccessChain %in_ptr %outdata %zero %x\n"
17699
17700                 "%outval     = OpLoad ${customType} %out_var\n"
17701                 "              OpStore %outloc %outval\n"
17702                 "              OpReturn\n"
17703                 "              OpFunctionEnd\n"
17704         ).specialize(parameters);
17705 }
17706
17707 bool compareFloats (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
17708 {
17709         DE_ASSERT(outputAllocs.size() != 0);
17710         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17711
17712         // Use custom epsilon because of the float->string conversion
17713         const float     epsilon = 0.00001f;
17714
17715         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17716         {
17717                 vector<deUint8> expectedBytes;
17718                 float                   expected;
17719                 float                   actual;
17720
17721                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17722                 memcpy(&expected, &expectedBytes.front(), expectedBytes.size());
17723                 memcpy(&actual, outputAllocs[outputNdx]->getHostPtr(), expectedBytes.size());
17724
17725                 // Test with epsilon
17726                 if (fabs(expected - actual) > epsilon)
17727                 {
17728                         log << TestLog::Message << "Error: The actual and expected values not matching."
17729                                 << " Expected: " << expected << " Actual: " << actual << " Epsilon: " << epsilon << TestLog::EndMessage;
17730                         return false;
17731                 }
17732         }
17733         return true;
17734 }
17735
17736 // Checks if the driver crash with uninitialized cases
17737 bool passthruVerify (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
17738 {
17739         DE_ASSERT(outputAllocs.size() != 0);
17740         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17741
17742         // Copy and discard the result.
17743         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17744         {
17745                 vector<deUint8> expectedBytes;
17746                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17747
17748                 const size_t    width                   = expectedBytes.size();
17749                 vector<char>    data                    (width);
17750
17751                 memcpy(&data[0], outputAllocs[outputNdx]->getHostPtr(), width);
17752         }
17753         return true;
17754 }
17755
17756 tcu::TestCaseGroup* createShaderDefaultOutputGroup (tcu::TestContext& testCtx)
17757 {
17758         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "shader_default_output", "Test shader default output."));
17759         de::Random                                              rnd             (deStringHash(group->getName()));
17760
17761         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17762         {
17763                 NumberType                                              numberType      = NumberType(type);
17764                 const string                                    typeName        = getNumberTypeName(numberType);
17765                 const string                                    description     = "Test the OpVariable initializer with " + typeName + ".";
17766                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17767
17768                 // 2 similar subcases (initialized and uninitialized)
17769                 for (int subCase = 0; subCase < 2; ++subCase)
17770                 {
17771                         ComputeShaderSpec spec;
17772                         spec.numWorkGroups = IVec3(1, 1, 1);
17773
17774                         map<string, string>                             params;
17775
17776                         switch (numberType)
17777                         {
17778                                 case NUMBERTYPE_INT32:
17779                                 {
17780                                         deInt32 number = getInt(rnd);
17781                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17782                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17783                                         params["constValue"] = numberToString(number);
17784                                         break;
17785                                 }
17786                                 case NUMBERTYPE_UINT32:
17787                                 {
17788                                         deUint32 number = rnd.getUint32();
17789                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17790                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17791                                         params["constValue"] = numberToString(number);
17792                                         break;
17793                                 }
17794                                 case NUMBERTYPE_FLOAT32:
17795                                 {
17796                                         float number = rnd.getFloat();
17797                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17798                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17799                                         spec.verifyIO = &compareFloats;
17800                                         params["constValue"] = numberToString(number);
17801                                         break;
17802                                 }
17803                                 default:
17804                                         DE_ASSERT(false);
17805                         }
17806
17807                         // Initialized subcase
17808                         if (!subCase)
17809                         {
17810                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType, params);
17811                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "initialized", "OpVariable initializer tests.", spec));
17812                         }
17813                         // Uninitialized subcase
17814                         else
17815                         {
17816                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType);
17817                                 spec.verifyIO = &passthruVerify;
17818                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "uninitialized", "OpVariable initializer tests.", spec));
17819                         }
17820                 }
17821                 group->addChild(subGroup.release());
17822         }
17823         return group.release();
17824 }
17825
17826 tcu::TestCaseGroup* createOpNopTests (tcu::TestContext& testCtx)
17827 {
17828         de::MovePtr<tcu::TestCaseGroup> testGroup (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
17829         RGBA                                                    defaultColors[4];
17830         map<string, string>                             opNopFragments;
17831
17832         getDefaultColors(defaultColors);
17833
17834         opNopFragments["testfun"]               =
17835                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17836                 "%param1 = OpFunctionParameter %v4f32\n"
17837                 "%label_testfun = OpLabel\n"
17838                 "OpNop\n"
17839                 "OpNop\n"
17840                 "OpNop\n"
17841                 "OpNop\n"
17842                 "OpNop\n"
17843                 "OpNop\n"
17844                 "OpNop\n"
17845                 "OpNop\n"
17846                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17847                 "%b = OpFAdd %f32 %a %a\n"
17848                 "OpNop\n"
17849                 "%c = OpFSub %f32 %b %a\n"
17850                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17851                 "OpNop\n"
17852                 "OpNop\n"
17853                 "OpReturnValue %ret\n"
17854                 "OpFunctionEnd\n";
17855
17856         createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, testGroup.get());
17857
17858         return testGroup.release();
17859 }
17860
17861 tcu::TestCaseGroup* createOpNameTests (tcu::TestContext& testCtx)
17862 {
17863         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "opname","Test OpName"));
17864         RGBA                                                    defaultColors[4];
17865         map<string, string>                             opNameFragments;
17866
17867         getDefaultColors(defaultColors);
17868
17869         opNameFragments["testfun"] =
17870                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17871                 "%param1     = OpFunctionParameter %v4f32\n"
17872                 "%label_func = OpLabel\n"
17873                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17874                 "%b          = OpFAdd %f32 %a %a\n"
17875                 "%c          = OpFSub %f32 %b %a\n"
17876                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17877                 "OpReturnValue %ret\n"
17878                 "OpFunctionEnd\n";
17879
17880         opNameFragments["debug"] =
17881                 "OpName %BP_main \"not_main\"";
17882
17883         createTestsForAllStages("opname", defaultColors, defaultColors, opNameFragments, testGroup.get());
17884
17885         return testGroup.release();
17886 }
17887
17888 tcu::TestCaseGroup* createFloat16Tests (tcu::TestContext& testCtx)
17889 {
17890         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17891
17892         testGroup->addChild(createOpConstantFloat16Tests(testCtx));
17893         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITH_NAN));
17894         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITHOUT_NAN));
17895         testGroup->addChild(createFloat16FuncSet<GraphicsResources>(testCtx));
17896         testGroup->addChild(createDerivativeTests<256, 1>(testCtx));
17897         testGroup->addChild(createDerivativeTests<256, 2>(testCtx));
17898         testGroup->addChild(createDerivativeTests<256, 4>(testCtx));
17899         testGroup->addChild(createFloat16VectorExtractSet<GraphicsResources>(testCtx));
17900         testGroup->addChild(createFloat16VectorInsertSet<GraphicsResources>(testCtx));
17901         testGroup->addChild(createFloat16VectorShuffleSet<GraphicsResources>(testCtx));
17902         testGroup->addChild(createFloat16CompositeConstructSet<GraphicsResources>(testCtx));
17903         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeExtract"));
17904         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeInsert"));
17905         testGroup->addChild(createFloat16ArithmeticSet<GraphicsResources>(testCtx));
17906         testGroup->addChild(createFloat16ArithmeticSet<1, GraphicsResources>(testCtx));
17907         testGroup->addChild(createFloat16ArithmeticSet<2, GraphicsResources>(testCtx));
17908         testGroup->addChild(createFloat16ArithmeticSet<3, GraphicsResources>(testCtx));
17909         testGroup->addChild(createFloat16ArithmeticSet<4, GraphicsResources>(testCtx));
17910
17911         return testGroup.release();
17912 }
17913
17914 tcu::TestCaseGroup* createFloat16Group (tcu::TestContext& testCtx)
17915 {
17916         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17917
17918         testGroup->addChild(createFloat16OpConstantCompositeGroup(testCtx));
17919         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITH_NAN));
17920         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITHOUT_NAN));
17921         testGroup->addChild(createFloat16FuncSet<ComputeShaderSpec>(testCtx));
17922         testGroup->addChild(createFloat16VectorExtractSet<ComputeShaderSpec>(testCtx));
17923         testGroup->addChild(createFloat16VectorInsertSet<ComputeShaderSpec>(testCtx));
17924         testGroup->addChild(createFloat16VectorShuffleSet<ComputeShaderSpec>(testCtx));
17925         testGroup->addChild(createFloat16CompositeConstructSet<ComputeShaderSpec>(testCtx));
17926         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeExtract"));
17927         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeInsert"));
17928         testGroup->addChild(createFloat16ArithmeticSet<ComputeShaderSpec>(testCtx));
17929         testGroup->addChild(createFloat16ArithmeticSet<1, ComputeShaderSpec>(testCtx));
17930         testGroup->addChild(createFloat16ArithmeticSet<2, ComputeShaderSpec>(testCtx));
17931         testGroup->addChild(createFloat16ArithmeticSet<3, ComputeShaderSpec>(testCtx));
17932         testGroup->addChild(createFloat16ArithmeticSet<4, ComputeShaderSpec>(testCtx));
17933
17934         return testGroup.release();
17935 }
17936
17937 tcu::TestCaseGroup* createBoolMixedBitSizeGroup (tcu::TestContext& testCtx)
17938 {
17939         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "mixed_bitsize", "Tests boolean operands produced from instructions of different bit-sizes"));
17940
17941         de::Random                                              rnd                             (deStringHash(group->getName()));
17942         const int               numElements             = 100;
17943         vector<float>   inputData               (numElements, 0);
17944         vector<float>   outputData              (numElements, 0);
17945         fillRandomScalars(rnd, 0.0f, 100.0f, &inputData[0], 100);
17946
17947         const StringTemplate                    shaderTemplate  (
17948                 "${CAPS}\n"
17949                 "OpMemoryModel Logical GLSL450\n"
17950                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17951                 "OpExecutionMode %main LocalSize 1 1 1\n"
17952                 "OpSource GLSL 430\n"
17953                 "OpName %main           \"main\"\n"
17954                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17955
17956                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17957
17958                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
17959
17960                 "%id        = OpVariable %uvec3ptr Input\n"
17961                 "${CONST}\n"
17962                 "%main      = OpFunction %void None %voidf\n"
17963                 "%label     = OpLabel\n"
17964                 "%idval     = OpLoad %uvec3 %id\n"
17965                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17966                 "%inloc     = OpAccessChain %f32ptr %indata %c0i32 %x\n"
17967
17968                 "${TEST}\n"
17969
17970                 "%outloc    = OpAccessChain %f32ptr %outdata %c0i32 %x\n"
17971                 "             OpStore %outloc %res\n"
17972                 "             OpReturn\n"
17973                 "             OpFunctionEnd\n"
17974         );
17975
17976         // Each test case produces 4 boolean values, and we want each of these values
17977         // to come froma different combination of the available bit-sizes, so compute
17978         // all possible combinations here.
17979         vector<deUint32>        widths;
17980         widths.push_back(32);
17981         widths.push_back(16);
17982         widths.push_back(8);
17983
17984         vector<IVec4>   cases;
17985         for (size_t width0 = 0; width0 < widths.size(); width0++)
17986         {
17987                 for (size_t width1 = 0; width1 < widths.size(); width1++)
17988                 {
17989                         for (size_t width2 = 0; width2 < widths.size(); width2++)
17990                         {
17991                                 for (size_t width3 = 0; width3 < widths.size(); width3++)
17992                                 {
17993                                         cases.push_back(IVec4(widths[width0], widths[width1], widths[width2], widths[width3]));
17994                                 }
17995                         }
17996                 }
17997         }
17998
17999         for (size_t caseNdx = 0; caseNdx < cases.size(); caseNdx++)
18000         {
18001                 /// Skip cases where all bitsizes are the same, we are only interested in testing booleans produced from instructions with different native bit-sizes
18002                 if (cases[caseNdx][0] == cases[caseNdx][1] && cases[caseNdx][0] == cases[caseNdx][2] && cases[caseNdx][0] == cases[caseNdx][3])
18003                         continue;
18004
18005                 map<string, string>     specializations;
18006                 ComputeShaderSpec       spec;
18007
18008                 // Inject appropriate capabilities and reference constants depending
18009                 // on the bit-sizes required by this test case
18010                 bool hasFloat32 = cases[caseNdx][0] == 32 || cases[caseNdx][1] == 32 || cases[caseNdx][2] == 32 || cases[caseNdx][3] == 32;
18011                 bool hasFloat16 = cases[caseNdx][0] == 16 || cases[caseNdx][1] == 16 || cases[caseNdx][2] == 16 || cases[caseNdx][3] == 16;
18012                 bool hasInt8    = cases[caseNdx][0] == 8 || cases[caseNdx][1] == 8 || cases[caseNdx][2] == 8 || cases[caseNdx][3] == 8;
18013
18014                 string capsStr  = "OpCapability Shader\n";
18015                 string constStr =
18016                         "%c0i32     = OpConstant %i32 0\n"
18017                         "%c1f32     = OpConstant %f32 1.0\n"
18018                         "%c0f32     = OpConstant %f32 0.0\n";
18019
18020                 if (hasFloat32)
18021                 {
18022                         constStr        +=
18023                                 "%c10f32    = OpConstant %f32 10.0\n"
18024                                 "%c25f32    = OpConstant %f32 25.0\n"
18025                                 "%c50f32    = OpConstant %f32 50.0\n"
18026                                 "%c90f32    = OpConstant %f32 90.0\n";
18027                 }
18028
18029                 if (hasFloat16)
18030                 {
18031                         capsStr         += "OpCapability Float16\n";
18032                         constStr        +=
18033                                 "%f16       = OpTypeFloat 16\n"
18034                                 "%c10f16    = OpConstant %f16 10.0\n"
18035                                 "%c25f16    = OpConstant %f16 25.0\n"
18036                                 "%c50f16    = OpConstant %f16 50.0\n"
18037                                 "%c90f16    = OpConstant %f16 90.0\n";
18038                 }
18039
18040                 if (hasInt8)
18041                 {
18042                         capsStr         += "OpCapability Int8\n";
18043                         constStr        +=
18044                                 "%i8        = OpTypeInt 8 1\n"
18045                                 "%c10i8     = OpConstant %i8 10\n"
18046                                 "%c25i8     = OpConstant %i8 25\n"
18047                                 "%c50i8     = OpConstant %i8 50\n"
18048                                 "%c90i8     = OpConstant %i8 90\n";
18049                 }
18050
18051                 // Each invocation reads a different float32 value as input. Depending on
18052                 // the bit-sizes required by the particular test case, we also produce
18053                 // float16 and/or and int8 values by converting from the 32-bit float.
18054                 string testStr  = "";
18055                 testStr                 += "%inval32   = OpLoad %f32 %inloc\n";
18056                 if (hasFloat16)
18057                         testStr         += "%inval16   = OpFConvert %f16 %inval32\n";
18058                 if (hasInt8)
18059                         testStr         += "%inval8    = OpConvertFToS %i8 %inval32\n";
18060
18061                 // Because conversions from Float to Int round towards 0 we want our "greater" comparisons to be >=,
18062                 // that way a float32/float16 comparison such as 50.6f >= 50.0f will preserve its result
18063                 // when converted to int8, since FtoS(50.6f) results in 50. For "less" comparisons, it is the
18064                 // other way around, so in this case we want < instead of <=.
18065                 if (cases[caseNdx][0] == 32)
18066                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval32 %c25f32\n";
18067                 else if (cases[caseNdx][0] == 16)
18068                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval16 %c25f16\n";
18069                 else
18070                         testStr         += "%cmp1      = OpSGreaterThanEqual %bool %inval8 %c25i8\n";
18071
18072                 if (cases[caseNdx][1] == 32)
18073                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval32 %c50f32\n";
18074                 else if (cases[caseNdx][1] == 16)
18075                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval16 %c50f16\n";
18076                 else
18077                         testStr         += "%cmp2      = OpSLessThan %bool %inval8 %c50i8\n";
18078
18079                 if (cases[caseNdx][2] == 32)
18080                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval32 %c10f32\n";
18081                 else if (cases[caseNdx][2] == 16)
18082                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval16 %c10f16\n";
18083                 else
18084                         testStr         += "%cmp3      = OpSLessThan %bool %inval8 %c10i8\n";
18085
18086                 if (cases[caseNdx][3] == 32)
18087                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval32 %c90f32\n";
18088                 else if (cases[caseNdx][3] == 16)
18089                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval16 %c90f16\n";
18090                 else
18091                         testStr         += "%cmp4      = OpSGreaterThanEqual %bool %inval8 %c90i8\n";
18092
18093                 testStr                 += "%and1      = OpLogicalAnd %bool %cmp1 %cmp2\n";
18094                 testStr                 += "%or1       = OpLogicalOr %bool %cmp3 %cmp4\n";
18095                 testStr                 += "%or2       = OpLogicalOr %bool %and1 %or1\n";
18096                 testStr                 += "%not1      = OpLogicalNot %bool %or2\n";
18097                 testStr                 += "%res       = OpSelect %f32 %not1 %c1f32 %c0f32\n";
18098
18099                 specializations["CAPS"]         = capsStr;
18100                 specializations["CONST"]        = constStr;
18101                 specializations["TEST"]         = testStr;
18102
18103                 // Compute expected result by evaluating the boolean expression computed in the shader for each input value
18104                 for (size_t ndx = 0; ndx < numElements; ++ndx)
18105                         outputData[ndx] = !((inputData[ndx] >= 25.0f && inputData[ndx] < 50.0f) || (inputData[ndx] < 10.0f || inputData[ndx] >= 90.0f));
18106
18107                 spec.assembly = shaderTemplate.specialize(specializations);
18108                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputData)));
18109                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputData)));
18110                 spec.numWorkGroups = IVec3(numElements, 1, 1);
18111                 if (hasFloat16)
18112                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
18113                 if (hasInt8)
18114                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
18115                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
18116
18117                 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]);
18118                 group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", spec));
18119         }
18120
18121         return group.release();
18122 }
18123
18124 tcu::TestCaseGroup* createBoolGroup (tcu::TestContext& testCtx)
18125 {
18126         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "bool", "Boolean tests"));
18127
18128         testGroup->addChild(createBoolMixedBitSizeGroup(testCtx));
18129
18130         return testGroup.release();
18131 }
18132
18133 tcu::TestCaseGroup* createOpNameAbuseTests (tcu::TestContext& testCtx)
18134 {
18135         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opname_abuse", "OpName abuse tests"));
18136         vector<CaseParameter>                   abuseCases;
18137         RGBA                                                    defaultColors[4];
18138         map<string, string>                             opNameFragments;
18139
18140         getOpNameAbuseCases(abuseCases);
18141         getDefaultColors(defaultColors);
18142
18143         opNameFragments["testfun"] =
18144                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18145                 "%param1     = OpFunctionParameter %v4f32\n"
18146                 "%label_func = OpLabel\n"
18147                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
18148                 "%b          = OpFAdd %f32 %a %a\n"
18149                 "%c          = OpFSub %f32 %b %a\n"
18150                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
18151                 "OpReturnValue %ret\n"
18152                 "OpFunctionEnd\n";
18153
18154         for (unsigned int i = 0; i < abuseCases.size(); i++)
18155         {
18156                 string casename;
18157                 casename = string("main") + abuseCases[i].name;
18158
18159                 opNameFragments["debug"] =
18160                         "OpName %BP_main \"" + abuseCases[i].param + "\"";
18161
18162                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18163         }
18164
18165         for (unsigned int i = 0; i < abuseCases.size(); i++)
18166         {
18167                 string casename;
18168                 casename = string("b") + abuseCases[i].name;
18169
18170                 opNameFragments["debug"] =
18171                         "OpName %b \"" + abuseCases[i].param + "\"";
18172
18173                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18174         }
18175
18176         {
18177                 opNameFragments["debug"] =
18178                         "OpName %test_code \"name1\"\n"
18179                         "OpName %param1    \"name2\"\n"
18180                         "OpName %a         \"name3\"\n"
18181                         "OpName %b         \"name4\"\n"
18182                         "OpName %c         \"name5\"\n"
18183                         "OpName %ret       \"name6\"\n";
18184
18185                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18186         }
18187
18188         {
18189                 opNameFragments["debug"] =
18190                         "OpName %test_code \"the_same\"\n"
18191                         "OpName %param1    \"the_same\"\n"
18192                         "OpName %a         \"the_same\"\n"
18193                         "OpName %b         \"the_same\"\n"
18194                         "OpName %c         \"the_same\"\n"
18195                         "OpName %ret       \"the_same\"\n";
18196
18197                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18198         }
18199
18200         {
18201                 opNameFragments["debug"] =
18202                         "OpName %BP_main \"to_be\"\n"
18203                         "OpName %BP_main \"or_not\"\n"
18204                         "OpName %BP_main \"to_be\"\n";
18205
18206                 createTestsForAllStages("main_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18207         }
18208
18209         {
18210                 opNameFragments["debug"] =
18211                         "OpName %b \"to_be\"\n"
18212                         "OpName %b \"or_not\"\n"
18213                         "OpName %b \"to_be\"\n";
18214
18215                 createTestsForAllStages("b_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18216         }
18217
18218         return abuseGroup.release();
18219 }
18220
18221
18222 tcu::TestCaseGroup* createOpMemberNameAbuseTests (tcu::TestContext& testCtx)
18223 {
18224         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opmembername_abuse", "OpName abuse tests"));
18225         vector<CaseParameter>                   abuseCases;
18226         RGBA                                                    defaultColors[4];
18227         map<string, string>                             opMemberNameFragments;
18228
18229         getOpNameAbuseCases(abuseCases);
18230         getDefaultColors(defaultColors);
18231
18232         opMemberNameFragments["pre_main"] =
18233                 "%f3str = OpTypeStruct %f32 %f32 %f32\n";
18234
18235         opMemberNameFragments["testfun"] =
18236                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18237                 "%param1     = OpFunctionParameter %v4f32\n"
18238                 "%label_func = OpLabel\n"
18239                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
18240                 "%b          = OpFAdd %f32 %a %a\n"
18241                 "%c          = OpFSub %f32 %b %a\n"
18242                 "%cstr       = OpCompositeConstruct %f3str %c %c %c\n"
18243                 "%d          = OpCompositeExtract %f32 %cstr 0\n"
18244                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %d %c_i32_0\n"
18245                 "OpReturnValue %ret\n"
18246                 "OpFunctionEnd\n";
18247
18248         for (unsigned int i = 0; i < abuseCases.size(); i++)
18249         {
18250                 string casename;
18251                 casename = string("f3str_x") + abuseCases[i].name;
18252
18253                 opMemberNameFragments["debug"] =
18254                         "OpMemberName %f3str 0 \"" + abuseCases[i].param + "\"";
18255
18256                 createTestsForAllStages(casename, defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18257         }
18258
18259         {
18260                 opMemberNameFragments["debug"] =
18261                         "OpMemberName %f3str 0 \"name1\"\n"
18262                         "OpMemberName %f3str 1 \"name2\"\n"
18263                         "OpMemberName %f3str 2 \"name3\"\n";
18264
18265                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18266         }
18267
18268         {
18269                 opMemberNameFragments["debug"] =
18270                         "OpMemberName %f3str 0 \"the_same\"\n"
18271                         "OpMemberName %f3str 1 \"the_same\"\n"
18272                         "OpMemberName %f3str 2 \"the_same\"\n";
18273
18274                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18275         }
18276
18277         {
18278                 opMemberNameFragments["debug"] =
18279                         "OpMemberName %f3str 0 \"to_be\"\n"
18280                         "OpMemberName %f3str 1 \"or_not\"\n"
18281                         "OpMemberName %f3str 0 \"to_be\"\n"
18282                         "OpMemberName %f3str 2 \"makes_no\"\n"
18283                         "OpMemberName %f3str 0 \"difference\"\n"
18284                         "OpMemberName %f3str 0 \"to_me\"\n";
18285
18286
18287                 createTestsForAllStages("f3str_x_has_multiple_names", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18288         }
18289
18290         return abuseGroup.release();
18291 }
18292
18293 vector<deUint32> getSparseIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18294 {
18295         vector<deUint32>        result;
18296         de::Random                      rnd             (seed);
18297
18298         result.reserve(numDataPoints);
18299
18300         for (deUint32 dataPointNdx = 0; dataPointNdx < numDataPoints; ++dataPointNdx)
18301                 result.push_back(rnd.getUint32());
18302
18303         return result;
18304 }
18305
18306 vector<deUint32> getSparseIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2)
18307 {
18308         vector<deUint32>        result;
18309
18310         result.reserve(inData1.size());
18311
18312         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18313                 result.push_back(inData1[dataPointNdx] + inData2[dataPointNdx]);
18314
18315         return result;
18316 }
18317
18318 template<class SpecResource>
18319 void createSparseIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18320 {
18321         const deUint32                  numDataPoints   = 16;
18322         const std::string               testName                ("sparse_ids");
18323         const deUint32                  seed                    (deStringHash(testName.c_str()));
18324         const vector<deUint32>  inData1                 (getSparseIdsAbuseData(numDataPoints, seed + 1));
18325         const vector<deUint32>  inData2                 (getSparseIdsAbuseData(numDataPoints, seed + 2));
18326         const vector<deUint32>  outData                 (getSparseIdsAbuseResults(inData1, inData2));
18327         const StringTemplate    preMain
18328         (
18329                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18330                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18331                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18332                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18333                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18334                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18335                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18336                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18337         );
18338         const StringTemplate    decoration
18339         (
18340                 "OpDecorate %ra_u32 ArrayStride 4\n"
18341                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18342                 "OpDecorate %SSBO32 BufferBlock\n"
18343                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18344                 "OpDecorate %ssbo_src0 Binding 0\n"
18345                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18346                 "OpDecorate %ssbo_src1 Binding 1\n"
18347                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18348                 "OpDecorate %ssbo_dst Binding 2\n"
18349         );
18350         const StringTemplate    testFun
18351         (
18352                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18353                 "    %param = OpFunctionParameter %v4f32\n"
18354
18355                 "    %entry = OpLabel\n"
18356                 "        %i = OpVariable %fp_i32 Function\n"
18357                 "             OpStore %i %c_i32_0\n"
18358                 "             OpBranch %loop\n"
18359
18360                 "     %loop = OpLabel\n"
18361                 "    %i_cmp = OpLoad %i32 %i\n"
18362                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18363                 "             OpLoopMerge %merge %next None\n"
18364                 "             OpBranchConditional %lt %write %merge\n"
18365
18366                 "    %write = OpLabel\n"
18367                 "      %ndx = OpLoad %i32 %i\n"
18368
18369                 "      %127 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18370                 "      %128 = OpLoad %u32 %127\n"
18371
18372                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18373                 "  %4194000 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18374                 "  %4194001 = OpLoad %u32 %4194000\n"
18375
18376                 "  %2097151 = OpIAdd %u32 %128 %4194001\n"
18377                 "  %2097152 = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18378                 "             OpStore %2097152 %2097151\n"
18379                 "             OpBranch %next\n"
18380
18381                 "     %next = OpLabel\n"
18382                 "    %i_cur = OpLoad %i32 %i\n"
18383                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18384                 "             OpStore %i %i_new\n"
18385                 "             OpBranch %loop\n"
18386
18387                 "    %merge = OpLabel\n"
18388                 "             OpReturnValue %param\n"
18389
18390                 "             OpFunctionEnd\n"
18391         );
18392         SpecResource                    specResource;
18393         map<string, string>             specs;
18394         VulkanFeatures                  features;
18395         map<string, string>             fragments;
18396         vector<string>                  extensions;
18397
18398         specs["num_data_points"]        = de::toString(numDataPoints);
18399
18400         fragments["decoration"]         = decoration.specialize(specs);
18401         fragments["pre_main"]           = preMain.specialize(specs);
18402         fragments["testfun"]            = testFun.specialize(specs);
18403
18404         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18405         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18406         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18407
18408         features.coreFeatures.vertexPipelineStoresAndAtomics    = true;
18409         features.coreFeatures.fragmentStoresAndAtomics                  = true;
18410
18411         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18412 }
18413
18414 vector<deUint32> getLotsIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18415 {
18416         vector<deUint32>        result;
18417         de::Random                      rnd             (seed);
18418
18419         result.reserve(numDataPoints);
18420
18421         // Fixed value
18422         result.push_back(1u);
18423
18424         // Random values
18425         for (deUint32 dataPointNdx = 1; dataPointNdx < numDataPoints; ++dataPointNdx)
18426                 result.push_back(rnd.getUint8());
18427
18428         return result;
18429 }
18430
18431 vector<deUint32> getLotsIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2, const deUint32 count)
18432 {
18433         vector<deUint32>        result;
18434
18435         result.reserve(inData1.size());
18436
18437         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18438                 result.push_back(inData1[dataPointNdx] + count * inData2[dataPointNdx]);
18439
18440         return result;
18441 }
18442
18443 template<class SpecResource>
18444 void createLotsIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18445 {
18446         const deUint32                  numDataPoints   = 16;
18447         const deUint32                  firstNdx                = 100u;
18448         const deUint32                  sequenceCount   = 10000u;
18449         const std::string               testName                ("lots_ids");
18450         const deUint32                  seed                    (deStringHash(testName.c_str()));
18451         const vector<deUint32>  inData1                 (getLotsIdsAbuseData(numDataPoints, seed + 1));
18452         const vector<deUint32>  inData2                 (getLotsIdsAbuseData(numDataPoints, seed + 2));
18453         const vector<deUint32>  outData                 (getLotsIdsAbuseResults(inData1, inData2, sequenceCount));
18454         const StringTemplate preMain
18455         (
18456                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18457                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18458                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18459                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18460                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18461                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18462                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18463                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18464         );
18465         const StringTemplate decoration
18466         (
18467                 "OpDecorate %ra_u32 ArrayStride 4\n"
18468                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18469                 "OpDecorate %SSBO32 BufferBlock\n"
18470                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18471                 "OpDecorate %ssbo_src0 Binding 0\n"
18472                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18473                 "OpDecorate %ssbo_src1 Binding 1\n"
18474                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18475                 "OpDecorate %ssbo_dst Binding 2\n"
18476         );
18477         const StringTemplate testFun
18478         (
18479                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18480                 "    %param = OpFunctionParameter %v4f32\n"
18481
18482                 "    %entry = OpLabel\n"
18483                 "        %i = OpVariable %fp_i32 Function\n"
18484                 "             OpStore %i %c_i32_0\n"
18485                 "             OpBranch %loop\n"
18486
18487                 "     %loop = OpLabel\n"
18488                 "    %i_cmp = OpLoad %i32 %i\n"
18489                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18490                 "             OpLoopMerge %merge %next None\n"
18491                 "             OpBranchConditional %lt %write %merge\n"
18492
18493                 "    %write = OpLabel\n"
18494                 "      %ndx = OpLoad %i32 %i\n"
18495
18496                 "       %90 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18497                 "       %91 = OpLoad %u32 %90\n"
18498
18499                 "       %98 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18500                 "       %${zeroth_id} = OpLoad %u32 %98\n"
18501
18502                 "${seq}\n"
18503
18504                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18505                 "      %dst = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18506                 "             OpStore %dst %${last_id}\n"
18507                 "             OpBranch %next\n"
18508
18509                 "     %next = OpLabel\n"
18510                 "    %i_cur = OpLoad %i32 %i\n"
18511                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18512                 "             OpStore %i %i_new\n"
18513                 "             OpBranch %loop\n"
18514
18515                 "    %merge = OpLabel\n"
18516                 "             OpReturnValue %param\n"
18517
18518                 "             OpFunctionEnd\n"
18519         );
18520         deUint32                                lastId                  = firstNdx;
18521         SpecResource                    specResource;
18522         map<string, string>             specs;
18523         VulkanFeatures                  features;
18524         map<string, string>             fragments;
18525         vector<string>                  extensions;
18526         std::string                             sequence;
18527
18528         for (deUint32 sequenceNdx = 0; sequenceNdx < sequenceCount; ++sequenceNdx)
18529         {
18530                 const deUint32          sequenceId              = sequenceNdx + firstNdx;
18531                 const std::string       sequenceIdStr   = de::toString(sequenceId);
18532
18533                 sequence += "%" + sequenceIdStr + " = OpIAdd %u32 %91 %" + de::toString(sequenceId - 1) + "\n";
18534                 lastId = sequenceId;
18535
18536                 if (sequenceNdx == 0)
18537                         sequence.reserve((10 + sequence.length()) * sequenceCount);
18538         }
18539
18540         specs["num_data_points"]        = de::toString(numDataPoints);
18541         specs["zeroth_id"]                      = de::toString(firstNdx - 1);
18542         specs["last_id"]                        = de::toString(lastId);
18543         specs["seq"]                            = sequence;
18544
18545         fragments["decoration"]         = decoration.specialize(specs);
18546         fragments["pre_main"]           = preMain.specialize(specs);
18547         fragments["testfun"]            = testFun.specialize(specs);
18548
18549         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18550         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18551         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18552
18553         features.coreFeatures.vertexPipelineStoresAndAtomics    = true;
18554         features.coreFeatures.fragmentStoresAndAtomics                  = true;
18555
18556         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18557 }
18558
18559 tcu::TestCaseGroup* createSpirvIdsAbuseTests (tcu::TestContext& testCtx)
18560 {
18561         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18562
18563         createSparseIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18564         createLotsIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18565
18566         return testGroup.release();
18567 }
18568
18569 tcu::TestCaseGroup* createSpirvIdsAbuseGroup (tcu::TestContext& testCtx)
18570 {
18571         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18572
18573         createSparseIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18574         createLotsIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18575
18576         return testGroup.release();
18577 }
18578
18579 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
18580 {
18581         const bool testComputePipeline = true;
18582
18583         de::MovePtr<tcu::TestCaseGroup> instructionTests        (new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
18584         de::MovePtr<tcu::TestCaseGroup> computeTests            (new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
18585         de::MovePtr<tcu::TestCaseGroup> graphicsTests           (new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
18586
18587         computeTests->addChild(createSpivVersionCheckTests(testCtx, testComputePipeline));
18588         computeTests->addChild(createLocalSizeGroup(testCtx));
18589         computeTests->addChild(createOpNopGroup(testCtx));
18590         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITHOUT_NAN));
18591         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITH_NAN));
18592         computeTests->addChild(createOpAtomicGroup(testCtx, false));
18593         computeTests->addChild(createOpAtomicGroup(testCtx, true));                                     // Using new StorageBuffer decoration
18594         computeTests->addChild(createOpAtomicGroup(testCtx, false, 1024, true));        // Return value validation
18595         computeTests->addChild(createOpLineGroup(testCtx));
18596         computeTests->addChild(createOpModuleProcessedGroup(testCtx));
18597         computeTests->addChild(createOpNoLineGroup(testCtx));
18598         computeTests->addChild(createOpConstantNullGroup(testCtx));
18599         computeTests->addChild(createOpConstantCompositeGroup(testCtx));
18600         computeTests->addChild(createOpConstantUsageGroup(testCtx));
18601         computeTests->addChild(createSpecConstantGroup(testCtx));
18602         computeTests->addChild(createOpSourceGroup(testCtx));
18603         computeTests->addChild(createOpSourceExtensionGroup(testCtx));
18604         computeTests->addChild(createDecorationGroupGroup(testCtx));
18605         computeTests->addChild(createOpPhiGroup(testCtx));
18606         computeTests->addChild(createLoopControlGroup(testCtx));
18607         computeTests->addChild(createFunctionControlGroup(testCtx));
18608         computeTests->addChild(createSelectionControlGroup(testCtx));
18609         computeTests->addChild(createBlockOrderGroup(testCtx));
18610         computeTests->addChild(createMultipleShaderGroup(testCtx));
18611         computeTests->addChild(createMemoryAccessGroup(testCtx));
18612         computeTests->addChild(createOpCopyMemoryGroup(testCtx));
18613         computeTests->addChild(createOpCopyObjectGroup(testCtx));
18614         computeTests->addChild(createNoContractionGroup(testCtx));
18615         computeTests->addChild(createOpUndefGroup(testCtx));
18616         computeTests->addChild(createOpUnreachableGroup(testCtx));
18617         computeTests->addChild(createOpQuantizeToF16Group(testCtx));
18618         computeTests->addChild(createOpFRemGroup(testCtx));
18619         computeTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18620         computeTests->addChild(createOpSRemComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18621         computeTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18622         computeTests->addChild(createOpSModComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18623         computeTests->addChild(createConvertComputeTests(testCtx, "OpSConvert", "sconvert"));
18624         computeTests->addChild(createConvertComputeTests(testCtx, "OpUConvert", "uconvert"));
18625         computeTests->addChild(createConvertComputeTests(testCtx, "OpFConvert", "fconvert"));
18626         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertSToF", "convertstof"));
18627         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToS", "convertftos"));
18628         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertUToF", "convertutof"));
18629         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToU", "convertftou"));
18630         computeTests->addChild(createOpCompositeInsertGroup(testCtx));
18631         computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
18632         computeTests->addChild(createShaderDefaultOutputGroup(testCtx));
18633         computeTests->addChild(createOpNMinGroup(testCtx));
18634         computeTests->addChild(createOpNMaxGroup(testCtx));
18635         computeTests->addChild(createOpNClampGroup(testCtx));
18636         {
18637                 de::MovePtr<tcu::TestCaseGroup> computeAndroidTests     (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18638
18639                 computeAndroidTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18640                 computeAndroidTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18641
18642                 computeTests->addChild(computeAndroidTests.release());
18643         }
18644
18645         computeTests->addChild(create8BitStorageComputeGroup(testCtx));
18646         computeTests->addChild(create16BitStorageComputeGroup(testCtx));
18647         computeTests->addChild(createFloatControlsComputeGroup(testCtx));
18648         computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
18649         computeTests->addChild(createCompositeInsertComputeGroup(testCtx));
18650         computeTests->addChild(createVariableInitComputeGroup(testCtx));
18651         computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
18652         computeTests->addChild(createIndexingComputeGroup(testCtx));
18653         computeTests->addChild(createVariablePointersComputeGroup(testCtx));
18654         computeTests->addChild(createPhysicalPointersComputeGroup(testCtx));
18655         computeTests->addChild(createImageSamplerComputeGroup(testCtx));
18656         computeTests->addChild(createOpNameGroup(testCtx));
18657         computeTests->addChild(createOpMemberNameGroup(testCtx));
18658         computeTests->addChild(createPointerParameterComputeGroup(testCtx));
18659         computeTests->addChild(createFloat16Group(testCtx));
18660         computeTests->addChild(createBoolGroup(testCtx));
18661         computeTests->addChild(createWorkgroupMemoryComputeGroup(testCtx));
18662         computeTests->addChild(createSpirvIdsAbuseGroup(testCtx));
18663         computeTests->addChild(createSignedIntCompareGroup(testCtx));
18664         computeTests->addChild(createUnusedVariableComputeTests(testCtx));
18665         computeTests->addChild(createPtrAccessChainGroup(testCtx));
18666
18667         graphicsTests->addChild(createCrossStageInterfaceTests(testCtx));
18668         graphicsTests->addChild(createSpivVersionCheckTests(testCtx, !testComputePipeline));
18669         graphicsTests->addChild(createOpNopTests(testCtx));
18670         graphicsTests->addChild(createOpSourceTests(testCtx));
18671         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
18672         graphicsTests->addChild(createOpModuleProcessedTests(testCtx));
18673         graphicsTests->addChild(createOpLineTests(testCtx));
18674         graphicsTests->addChild(createOpNoLineTests(testCtx));
18675         graphicsTests->addChild(createOpConstantNullTests(testCtx));
18676         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
18677         graphicsTests->addChild(createMemoryAccessTests(testCtx));
18678         graphicsTests->addChild(createOpUndefTests(testCtx));
18679         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
18680         graphicsTests->addChild(createModuleTests(testCtx));
18681         graphicsTests->addChild(createUnusedVariableTests(testCtx));
18682         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
18683         graphicsTests->addChild(createOpPhiTests(testCtx));
18684         graphicsTests->addChild(createNoContractionTests(testCtx));
18685         graphicsTests->addChild(createOpQuantizeTests(testCtx));
18686         graphicsTests->addChild(createLoopTests(testCtx));
18687         graphicsTests->addChild(createSpecConstantTests(testCtx));
18688         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
18689         graphicsTests->addChild(createBarrierTests(testCtx));
18690         graphicsTests->addChild(createDecorationGroupTests(testCtx));
18691         graphicsTests->addChild(createFRemTests(testCtx));
18692         graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18693         graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18694
18695         {
18696                 de::MovePtr<tcu::TestCaseGroup> graphicsAndroidTests    (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18697
18698                 graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18699                 graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18700
18701                 graphicsTests->addChild(graphicsAndroidTests.release());
18702         }
18703         graphicsTests->addChild(createOpNameTests(testCtx));
18704         graphicsTests->addChild(createOpNameAbuseTests(testCtx));
18705         graphicsTests->addChild(createOpMemberNameAbuseTests(testCtx));
18706
18707         graphicsTests->addChild(create8BitStorageGraphicsGroup(testCtx));
18708         graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
18709         graphicsTests->addChild(createFloatControlsGraphicsGroup(testCtx));
18710         graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
18711         graphicsTests->addChild(createCompositeInsertGraphicsGroup(testCtx));
18712         graphicsTests->addChild(createVariableInitGraphicsGroup(testCtx));
18713         graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
18714         graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
18715         graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
18716         graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
18717         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpSConvert", "sconvert"));
18718         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpUConvert", "uconvert"));
18719         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpFConvert", "fconvert"));
18720         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertSToF", "convertstof"));
18721         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToS", "convertftos"));
18722         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertUToF", "convertutof"));
18723         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToU", "convertftou"));
18724         graphicsTests->addChild(createPointerParameterGraphicsGroup(testCtx));
18725         graphicsTests->addChild(createVaryingNameGraphicsGroup(testCtx));
18726         graphicsTests->addChild(createFloat16Tests(testCtx));
18727         graphicsTests->addChild(createSpirvIdsAbuseTests(testCtx));
18728
18729         instructionTests->addChild(computeTests.release());
18730         instructionTests->addChild(graphicsTests.release());
18731
18732         return instructionTests.release();
18733 }
18734
18735 } // SpirVAssembly
18736 } // vkt