Add SPIR-V unused variable tests
[platform/upstream/VK-GL-CTS.git] / external / vulkancts / modules / vulkan / spirv_assembly / vktSpvAsmInstructionTests.cpp
1 /*-------------------------------------------------------------------------
2  * Vulkan Conformance Tests
3  * ------------------------
4  *
5  * Copyright (c) 2015 Google Inc.
6  * Copyright (c) 2016 The Khronos Group Inc.
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  *//*!
21  * \file
22  * \brief SPIR-V Assembly Tests for Instructions (special opcode/operand)
23  *//*--------------------------------------------------------------------*/
24
25 #include "vktSpvAsmInstructionTests.hpp"
26
27 #include "tcuCommandLine.hpp"
28 #include "tcuFormatUtil.hpp"
29 #include "tcuFloat.hpp"
30 #include "tcuFloatFormat.hpp"
31 #include "tcuRGBA.hpp"
32 #include "tcuStringTemplate.hpp"
33 #include "tcuTestLog.hpp"
34 #include "tcuVectorUtil.hpp"
35 #include "tcuInterval.hpp"
36
37 #include "vkDefs.hpp"
38 #include "vkDeviceUtil.hpp"
39 #include "vkMemUtil.hpp"
40 #include "vkPlatform.hpp"
41 #include "vkPrograms.hpp"
42 #include "vkQueryUtil.hpp"
43 #include "vkRef.hpp"
44 #include "vkRefUtil.hpp"
45 #include "vkStrUtil.hpp"
46 #include "vkTypeUtil.hpp"
47
48 #include "deStringUtil.hpp"
49 #include "deUniquePtr.hpp"
50 #include "deMath.h"
51 #include "deRandom.hpp"
52 #include "tcuStringTemplate.hpp"
53
54 #include "vktSpvAsmCrossStageInterfaceTests.hpp"
55 #include "vktSpvAsm8bitStorageTests.hpp"
56 #include "vktSpvAsm16bitStorageTests.hpp"
57 #include "vktSpvAsmUboMatrixPaddingTests.hpp"
58 #include "vktSpvAsmConditionalBranchTests.hpp"
59 #include "vktSpvAsmIndexingTests.hpp"
60 #include "vktSpvAsmImageSamplerTests.hpp"
61 #include "vktSpvAsmComputeShaderCase.hpp"
62 #include "vktSpvAsmComputeShaderTestUtil.hpp"
63 #include "vktSpvAsmFloatControlsTests.hpp"
64 #include "vktSpvAsmGraphicsShaderTestUtil.hpp"
65 #include "vktSpvAsmVariablePointersTests.hpp"
66 #include "vktSpvAsmVariableInitTests.hpp"
67 #include "vktSpvAsmPointerParameterTests.hpp"
68 #include "vktSpvAsmSpirvVersionTests.hpp"
69 #include "vktTestCaseUtil.hpp"
70 #include "vktSpvAsmLoopDepLenTests.hpp"
71 #include "vktSpvAsmLoopDepInfTests.hpp"
72 #include "vktSpvAsmCompositeInsertTests.hpp"
73 #include "vktSpvAsmVaryingNameTests.hpp"
74 #include "vktSpvAsmWorkgroupMemoryTests.hpp"
75 #include "vktSpvAsmSignedIntCompareTests.hpp"
76
77 #include <cmath>
78 #include <limits>
79 #include <map>
80 #include <string>
81 #include <sstream>
82 #include <utility>
83 #include <stack>
84
85 namespace vkt
86 {
87 namespace SpirVAssembly
88 {
89
90 namespace
91 {
92
93 using namespace vk;
94 using std::map;
95 using std::string;
96 using std::vector;
97 using tcu::IVec3;
98 using tcu::IVec4;
99 using tcu::RGBA;
100 using tcu::TestLog;
101 using tcu::TestStatus;
102 using tcu::Vec4;
103 using de::UniquePtr;
104 using tcu::StringTemplate;
105 using tcu::Vec4;
106
107 const bool TEST_WITH_NAN        = true;
108 const bool TEST_WITHOUT_NAN     = false;
109
110 template<typename T>
111 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, int offset = 0)
112 {
113         T* const typedPtr = (T*)dst;
114         for (int ndx = 0; ndx < numValues; ndx++)
115                 typedPtr[offset + ndx] = de::randomScalar<T>(rnd, minValue, maxValue);
116 }
117
118 // Filter is a function that returns true if a value should pass, false otherwise.
119 template<typename T, typename FilterT>
120 static void fillRandomScalars (de::Random& rnd, T minValue, T maxValue, void* dst, int numValues, FilterT filter, int offset = 0)
121 {
122         T* const typedPtr = (T*)dst;
123         T value;
124         for (int ndx = 0; ndx < numValues; ndx++)
125         {
126                 do
127                         value = de::randomScalar<T>(rnd, minValue, maxValue);
128                 while (!filter(value));
129
130                 typedPtr[offset + ndx] = value;
131         }
132 }
133
134 // Gets a 64-bit integer with a more logarithmic distribution
135 deInt64 randomInt64LogDistributed (de::Random& rnd)
136 {
137         deInt64 val = rnd.getUint64();
138         val &= (1ull << rnd.getInt(1, 63)) - 1;
139         if (rnd.getBool())
140                 val = -val;
141         return val;
142 }
143
144 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues)
145 {
146         for (int ndx = 0; ndx < numValues; ndx++)
147                 dst[ndx] = randomInt64LogDistributed(rnd);
148 }
149
150 template<typename FilterT>
151 static void fillRandomInt64sLogDistributed (de::Random& rnd, vector<deInt64>& dst, int numValues, FilterT filter)
152 {
153         for (int ndx = 0; ndx < numValues; ndx++)
154         {
155                 deInt64 value;
156                 do {
157                         value = randomInt64LogDistributed(rnd);
158                 } while (!filter(value));
159                 dst[ndx] = value;
160         }
161 }
162
163 inline bool filterNonNegative (const deInt64 value)
164 {
165         return value >= 0;
166 }
167
168 inline bool filterPositive (const deInt64 value)
169 {
170         return value > 0;
171 }
172
173 inline bool filterNotZero (const deInt64 value)
174 {
175         return value != 0;
176 }
177
178 static void floorAll (vector<float>& values)
179 {
180         for (size_t i = 0; i < values.size(); i++)
181                 values[i] = deFloatFloor(values[i]);
182 }
183
184 static void floorAll (vector<Vec4>& values)
185 {
186         for (size_t i = 0; i < values.size(); i++)
187                 values[i] = floor(values[i]);
188 }
189
190 struct CaseParameter
191 {
192         const char*             name;
193         string                  param;
194
195         CaseParameter   (const char* case_, const string& param_) : name(case_), param(param_) {}
196 };
197
198 // Assembly code used for testing LocalSize, OpNop, OpConstant{Null|Composite}, Op[No]Line, OpSource[Continued], OpSourceExtension, OpUndef is based on GLSL source code:
199 //
200 // #version 430
201 //
202 // layout(std140, set = 0, binding = 0) readonly buffer Input {
203 //   float elements[];
204 // } input_data;
205 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
206 //   float elements[];
207 // } output_data;
208 //
209 // layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
210 //
211 // void main() {
212 //   uint x = gl_GlobalInvocationID.x;
213 //   output_data.elements[x] = -input_data.elements[x];
214 // }
215
216 static string getAsmForLocalSizeTest(bool useLiteralLocalSize, bool useSpecConstantWorkgroupSize, IVec3 workGroupSize, deUint32 ndx)
217 {
218         std::ostringstream out;
219         out << getComputeAsmShaderPreambleWithoutLocalSize();
220
221         if (useLiteralLocalSize)
222         {
223                 out << "OpExecutionMode %main LocalSize "
224                         << workGroupSize.x() << " " << workGroupSize.y() << " " << workGroupSize.z() << "\n";
225         }
226
227         out << "OpSource GLSL 430\n"
228                 "OpName %main           \"main\"\n"
229                 "OpName %id             \"gl_GlobalInvocationID\"\n"
230                 "OpDecorate %id BuiltIn GlobalInvocationId\n";
231
232         if (useSpecConstantWorkgroupSize)
233         {
234                 out << "OpDecorate %spec_0 SpecId 100\n"
235                         << "OpDecorate %spec_1 SpecId 101\n"
236                         << "OpDecorate %spec_2 SpecId 102\n"
237                         << "OpDecorate %gl_WorkGroupSize BuiltIn WorkgroupSize\n";
238         }
239
240         out << getComputeAsmInputOutputBufferTraits()
241                 << getComputeAsmCommonTypes()
242                 << getComputeAsmInputOutputBuffer()
243                 << "%id        = OpVariable %uvec3ptr Input\n"
244                 << "%zero      = OpConstant %i32 0 \n";
245
246         if (useSpecConstantWorkgroupSize)
247         {
248                 out     << "%spec_0   = OpSpecConstant %u32 "<< workGroupSize.x() << "\n"
249                         << "%spec_1   = OpSpecConstant %u32 "<< workGroupSize.y() << "\n"
250                         << "%spec_2   = OpSpecConstant %u32 "<< workGroupSize.z() << "\n"
251                         << "%gl_WorkGroupSize = OpSpecConstantComposite %uvec3 %spec_0 %spec_1 %spec_2\n";
252         }
253
254         out << "%main      = OpFunction %void None %voidf\n"
255                 << "%label     = OpLabel\n"
256                 << "%idval     = OpLoad %uvec3 %id\n"
257                 << "%ndx         = OpCompositeExtract %u32 %idval " << ndx << "\n"
258
259                         "%inloc     = OpAccessChain %f32ptr %indata %zero %ndx\n"
260                         "%inval     = OpLoad %f32 %inloc\n"
261                         "%neg       = OpFNegate %f32 %inval\n"
262                         "%outloc    = OpAccessChain %f32ptr %outdata %zero %ndx\n"
263                         "             OpStore %outloc %neg\n"
264                         "             OpReturn\n"
265                         "             OpFunctionEnd\n";
266         return out.str();
267 }
268
269 tcu::TestCaseGroup* createLocalSizeGroup (tcu::TestContext& testCtx)
270 {
271         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "localsize", ""));
272         ComputeShaderSpec                               spec;
273         de::Random                                              rnd                             (deStringHash(group->getName()));
274         const deUint32                                  numElements             = 64u;
275         vector<float>                                   positiveFloats  (numElements, 0);
276         vector<float>                                   negativeFloats  (numElements, 0);
277
278         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
279
280         for (size_t ndx = 0; ndx < numElements; ++ndx)
281                 negativeFloats[ndx] = -positiveFloats[ndx];
282
283         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
284         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
285
286         spec.numWorkGroups = IVec3(numElements, 1, 1);
287
288         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, 1), 0u);
289         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize", "", spec));
290
291         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, 1), 0u);
292         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize", "", spec));
293
294         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, 1), 0u);
295         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize", "", spec));
296
297         spec.numWorkGroups = IVec3(1, 1, 1);
298
299         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(numElements, 1, 1), 0u);
300         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_x", "", spec));
301
302         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(numElements, 1, 1), 0u);
303         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_x", "", spec));
304
305         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(numElements, 1, 1), 0u);
306         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_x", "", spec));
307
308         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, numElements, 1), 1u);
309         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_y", "", spec));
310
311         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, numElements, 1), 1u);
312         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_y", "", spec));
313
314         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, numElements, 1), 1u);
315         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_y", "", spec));
316
317         spec.assembly = getAsmForLocalSizeTest(true, false, IVec3(1, 1, numElements), 2u);
318         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_localsize_z", "", spec));
319
320         spec.assembly = getAsmForLocalSizeTest(true, true, IVec3(1, 1, numElements), 2u);
321         group->addChild(new SpvAsmComputeShaderCase(testCtx, "literal_and_specid_localsize_z", "", spec));
322
323         spec.assembly = getAsmForLocalSizeTest(false, true, IVec3(1, 1, numElements), 2u);
324         group->addChild(new SpvAsmComputeShaderCase(testCtx, "specid_localsize_z", "", spec));
325
326         return group.release();
327 }
328
329 tcu::TestCaseGroup* createOpNopGroup (tcu::TestContext& testCtx)
330 {
331         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnop", "Test the OpNop instruction"));
332         ComputeShaderSpec                               spec;
333         de::Random                                              rnd                             (deStringHash(group->getName()));
334         const int                                               numElements             = 100;
335         vector<float>                                   positiveFloats  (numElements, 0);
336         vector<float>                                   negativeFloats  (numElements, 0);
337
338         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
339
340         for (size_t ndx = 0; ndx < numElements; ++ndx)
341                 negativeFloats[ndx] = -positiveFloats[ndx];
342
343         spec.assembly =
344                 string(getComputeAsmShaderPreamble()) +
345
346                 "OpSource GLSL 430\n"
347                 "OpName %main           \"main\"\n"
348                 "OpName %id             \"gl_GlobalInvocationID\"\n"
349
350                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
351
352                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
353
354                 + string(getComputeAsmInputOutputBuffer()) +
355
356                 "%id        = OpVariable %uvec3ptr Input\n"
357                 "%zero      = OpConstant %i32 0\n"
358
359                 "%main      = OpFunction %void None %voidf\n"
360                 "%label     = OpLabel\n"
361                 "%idval     = OpLoad %uvec3 %id\n"
362                 "%x         = OpCompositeExtract %u32 %idval 0\n"
363
364                 "             OpNop\n" // Inside a function body
365
366                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
367                 "%inval     = OpLoad %f32 %inloc\n"
368                 "%neg       = OpFNegate %f32 %inval\n"
369                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
370                 "             OpStore %outloc %neg\n"
371                 "             OpReturn\n"
372                 "             OpFunctionEnd\n";
373         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
374         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
375         spec.numWorkGroups = IVec3(numElements, 1, 1);
376
377         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNop appearing at different places", spec));
378
379         return group.release();
380 }
381
382 tcu::TestCaseGroup* createUnusedVariableComputeTests (tcu::TestContext& testCtx)
383 {
384         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "unused_variables", "Compute shaders with unused variables"));
385         de::Random                                              rnd                             (deStringHash(group->getName()));
386         const int                                               numElements             = 100;
387         vector<float>                                   positiveFloats  (numElements, 0);
388         vector<float>                                   negativeFloats  (numElements, 0);
389
390         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
391
392         for (size_t ndx = 0; ndx < numElements; ++ndx)
393                 negativeFloats[ndx] = -positiveFloats[ndx];
394
395         const VariableLocation                  testLocations[] =
396         {
397                 // Set          Binding
398                 { 0,            5                       },
399                 { 5,            5                       },
400         };
401
402         for (size_t locationNdx = 0; locationNdx < DE_LENGTH_OF_ARRAY(testLocations); ++locationNdx)
403         {
404                 const VariableLocation& location = testLocations[locationNdx];
405
406                 // Unused variable.
407                 {
408                         ComputeShaderSpec                               spec;
409
410                         spec.assembly =
411                                 string(getComputeAsmShaderPreamble()) +
412
413                                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
414
415                                 + getUnusedDecorations(location)
416
417                                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
418
419                                 + getUnusedTypesAndConstants()
420
421                                 + string(getComputeAsmInputOutputBuffer())
422
423                                 + getUnusedBuffer() +
424
425                                 "%id        = OpVariable %uvec3ptr Input\n"
426                                 "%zero      = OpConstant %i32 0\n"
427
428                                 "%main      = OpFunction %void None %voidf\n"
429                                 "%label     = OpLabel\n"
430                                 "%idval     = OpLoad %uvec3 %id\n"
431                                 "%x         = OpCompositeExtract %u32 %idval 0\n"
432
433                                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
434                                 "%inval     = OpLoad %f32 %inloc\n"
435                                 "%neg       = OpFNegate %f32 %inval\n"
436                                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
437                                 "             OpStore %outloc %neg\n"
438                                 "             OpReturn\n"
439                                 "             OpFunctionEnd\n";
440                         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
441                         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
442                         spec.numWorkGroups = IVec3(numElements, 1, 1);
443
444                         std::string testName            = "variable_" + location.toString();
445                         std::string testDescription     = "Unused variable test with " + location.toDescription();
446
447                         group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), testDescription.c_str(), spec));
448                 }
449
450                 // Unused function.
451                 {
452                         ComputeShaderSpec                               spec;
453
454                         spec.assembly =
455                                 string(getComputeAsmShaderPreamble("", "", "", getUnusedEntryPoint())) +
456
457                                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
458
459                                 + getUnusedDecorations(location)
460
461                                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes())
462
463                                 + getUnusedTypesAndConstants() +
464
465                                 "%c_i32_0 = OpConstant %i32 0\n"
466                                 "%c_i32_1 = OpConstant %i32 1\n"
467
468                                 + string(getComputeAsmInputOutputBuffer())
469
470                                 + getUnusedBuffer() +
471
472                                 "%id        = OpVariable %uvec3ptr Input\n"
473                                 "%zero      = OpConstant %i32 0\n"
474
475                                 "%main      = OpFunction %void None %voidf\n"
476                                 "%label     = OpLabel\n"
477                                 "%idval     = OpLoad %uvec3 %id\n"
478                                 "%x         = OpCompositeExtract %u32 %idval 0\n"
479
480                                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
481                                 "%inval     = OpLoad %f32 %inloc\n"
482                                 "%neg       = OpFNegate %f32 %inval\n"
483                                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
484                                 "             OpStore %outloc %neg\n"
485                                 "             OpReturn\n"
486                                 "             OpFunctionEnd\n"
487
488                                 + getUnusedFunctionBody();
489
490                         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
491                         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
492                         spec.numWorkGroups = IVec3(numElements, 1, 1);
493
494                         std::string testName            = "function_" + location.toString();
495                         std::string testDescription     = "Unused function test with " + location.toDescription();
496
497                         group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), testDescription.c_str(), spec));
498                 }
499         }
500
501         return group.release();
502 }
503
504 template<bool nanSupported>
505 bool compareFUnord (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
506 {
507         if (outputAllocs.size() != 1)
508                 return false;
509
510         vector<deUint8> input1Bytes;
511         vector<deUint8> input2Bytes;
512         vector<deUint8> expectedBytes;
513
514         inputs[0].getBytes(input1Bytes);
515         inputs[1].getBytes(input2Bytes);
516         expectedOutputs[0].getBytes(expectedBytes);
517
518         const deInt32* const    expectedOutputAsInt             = reinterpret_cast<const deInt32*>(&expectedBytes.front());
519         const deInt32* const    outputAsInt                             = static_cast<const deInt32*>(outputAllocs[0]->getHostPtr());
520         const float* const              input1AsFloat                   = reinterpret_cast<const float*>(&input1Bytes.front());
521         const float* const              input2AsFloat                   = reinterpret_cast<const float*>(&input2Bytes.front());
522         bool returnValue                                                                = true;
523
524         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(deInt32); ++idx)
525         {
526                 if (!nanSupported && (tcu::Float32(input1AsFloat[idx]).isNaN() || tcu::Float32(input2AsFloat[idx]).isNaN()))
527                         continue;
528
529                 if (outputAsInt[idx] != expectedOutputAsInt[idx])
530                 {
531                         log << TestLog::Message << "ERROR: Sub-case failed. inputs: " << input1AsFloat[idx] << "," << input2AsFloat[idx] << " output: " << outputAsInt[idx]<< " expected output: " << expectedOutputAsInt[idx] << TestLog::EndMessage;
532                         returnValue = false;
533                 }
534         }
535         return returnValue;
536 }
537
538 typedef VkBool32 (*compareFuncType) (float, float);
539
540 struct OpFUnordCase
541 {
542         const char*             name;
543         const char*             opCode;
544         compareFuncType compareFunc;
545
546                                         OpFUnordCase                    (const char* _name, const char* _opCode, compareFuncType _compareFunc)
547                                                 : name                          (_name)
548                                                 , opCode                        (_opCode)
549                                                 , compareFunc           (_compareFunc) {}
550 };
551
552 #define ADD_OPFUNORD_CASE(NAME, OPCODE, OPERATOR) \
553 do { \
554         struct compare_##NAME { static VkBool32 compare(float x, float y) { return (x OPERATOR y) ? VK_TRUE : VK_FALSE; } }; \
555         cases.push_back(OpFUnordCase(#NAME, OPCODE, compare_##NAME::compare)); \
556 } while (deGetFalse())
557
558 tcu::TestCaseGroup* createOpFUnordGroup (tcu::TestContext& testCtx, const bool testWithNan)
559 {
560         const string                                    nan                             = testWithNan ? "_nan" : "";
561         const string                                    groupName               = "opfunord" + nan;
562         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpFUnord* opcodes"));
563         de::Random                                              rnd                             (deStringHash(group->getName()));
564         const int                                               numElements             = 100;
565         vector<OpFUnordCase>                    cases;
566         string                                                  extensions              = testWithNan ? "OpExtension \"SPV_KHR_float_controls\"\n" : "";
567         string                                                  capabilities    = testWithNan ? "OpCapability SignedZeroInfNanPreserve\n" : "";
568         string                                                  exeModes                = testWithNan ? "OpExecutionMode %main SignedZeroInfNanPreserve 32\n" : "";
569         const StringTemplate                    shaderTemplate  (
570                 string(getComputeAsmShaderPreamble(capabilities, extensions, exeModes)) +
571                 "OpSource GLSL 430\n"
572                 "OpName %main           \"main\"\n"
573                 "OpName %id             \"gl_GlobalInvocationID\"\n"
574
575                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
576
577                 "OpDecorate %buf BufferBlock\n"
578                 "OpDecorate %buf2 BufferBlock\n"
579                 "OpDecorate %indata1 DescriptorSet 0\n"
580                 "OpDecorate %indata1 Binding 0\n"
581                 "OpDecorate %indata2 DescriptorSet 0\n"
582                 "OpDecorate %indata2 Binding 1\n"
583                 "OpDecorate %outdata DescriptorSet 0\n"
584                 "OpDecorate %outdata Binding 2\n"
585                 "OpDecorate %f32arr ArrayStride 4\n"
586                 "OpDecorate %i32arr ArrayStride 4\n"
587                 "OpMemberDecorate %buf 0 Offset 0\n"
588                 "OpMemberDecorate %buf2 0 Offset 0\n"
589
590                 + string(getComputeAsmCommonTypes()) +
591
592                 "%buf        = OpTypeStruct %f32arr\n"
593                 "%bufptr     = OpTypePointer Uniform %buf\n"
594                 "%indata1    = OpVariable %bufptr Uniform\n"
595                 "%indata2    = OpVariable %bufptr Uniform\n"
596
597                 "%buf2       = OpTypeStruct %i32arr\n"
598                 "%buf2ptr    = OpTypePointer Uniform %buf2\n"
599                 "%outdata    = OpVariable %buf2ptr Uniform\n"
600
601                 "%id        = OpVariable %uvec3ptr Input\n"
602                 "%zero      = OpConstant %i32 0\n"
603                 "%consti1   = OpConstant %i32 1\n"
604                 "%constf1   = OpConstant %f32 1.0\n"
605
606                 "%main      = OpFunction %void None %voidf\n"
607                 "%label     = OpLabel\n"
608                 "%idval     = OpLoad %uvec3 %id\n"
609                 "%x         = OpCompositeExtract %u32 %idval 0\n"
610
611                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
612                 "%inval1    = OpLoad %f32 %inloc1\n"
613                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
614                 "%inval2    = OpLoad %f32 %inloc2\n"
615                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
616
617                 "%result    = ${OPCODE} %bool %inval1 %inval2\n"
618                 "%int_res   = OpSelect %i32 %result %consti1 %zero\n"
619                 "             OpStore %outloc %int_res\n"
620
621                 "             OpReturn\n"
622                 "             OpFunctionEnd\n");
623
624         ADD_OPFUNORD_CASE(equal, "OpFUnordEqual", ==);
625         ADD_OPFUNORD_CASE(less, "OpFUnordLessThan", <);
626         ADD_OPFUNORD_CASE(lessequal, "OpFUnordLessThanEqual", <=);
627         ADD_OPFUNORD_CASE(greater, "OpFUnordGreaterThan", >);
628         ADD_OPFUNORD_CASE(greaterequal, "OpFUnordGreaterThanEqual", >=);
629         ADD_OPFUNORD_CASE(notequal, "OpFUnordNotEqual", !=);
630
631         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
632         {
633                 map<string, string>                     specializations;
634                 ComputeShaderSpec                       spec;
635                 const float                                     NaN                             = std::numeric_limits<float>::quiet_NaN();
636                 vector<float>                           inputFloats1    (numElements, 0);
637                 vector<float>                           inputFloats2    (numElements, 0);
638                 vector<deInt32>                         expectedInts    (numElements, 0);
639
640                 specializations["OPCODE"]       = cases[caseNdx].opCode;
641                 spec.assembly                           = shaderTemplate.specialize(specializations);
642
643                 fillRandomScalars(rnd, 1.f, 100.f, &inputFloats1[0], numElements);
644                 for (size_t ndx = 0; ndx < numElements; ++ndx)
645                 {
646                         switch (ndx % 6)
647                         {
648                                 case 0:         inputFloats2[ndx] = inputFloats1[ndx] + 1.0f; break;
649                                 case 1:         inputFloats2[ndx] = inputFloats1[ndx] - 1.0f; break;
650                                 case 2:         inputFloats2[ndx] = inputFloats1[ndx]; break;
651                                 case 3:         inputFloats2[ndx] = NaN; break;
652                                 case 4:         inputFloats2[ndx] = inputFloats1[ndx];  inputFloats1[ndx] = NaN; break;
653                                 case 5:         inputFloats2[ndx] = NaN;                                inputFloats1[ndx] = NaN; break;
654                         }
655                         expectedInts[ndx] = tcu::Float32(inputFloats1[ndx]).isNaN() || tcu::Float32(inputFloats2[ndx]).isNaN() || cases[caseNdx].compareFunc(inputFloats1[ndx], inputFloats2[ndx]);
656                 }
657
658                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
659                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
660                 spec.outputs.push_back(BufferSp(new Int32Buffer(expectedInts)));
661                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
662                 spec.verifyIO           = testWithNan ? &compareFUnord<true> : &compareFUnord<false>;
663
664                 if (testWithNan)
665                 {
666                         spec.extensions.push_back("VK_KHR_shader_float_controls");
667                         spec.requestedVulkanFeatures.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat32 = DE_TRUE;
668                 }
669
670                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
671         }
672
673         return group.release();
674 }
675
676 struct OpAtomicCase
677 {
678         const char*             name;
679         const char*             assembly;
680         const char*             retValAssembly;
681         OpAtomicType    opAtomic;
682         deInt32                 numOutputElements;
683
684                                         OpAtomicCase(const char* _name, const char* _assembly, const char* _retValAssembly, OpAtomicType _opAtomic, deInt32 _numOutputElements)
685                                                 : name                          (_name)
686                                                 , assembly                      (_assembly)
687                                                 , retValAssembly        (_retValAssembly)
688                                                 , opAtomic                      (_opAtomic)
689                                                 , numOutputElements     (_numOutputElements) {}
690 };
691
692 tcu::TestCaseGroup* createOpAtomicGroup (tcu::TestContext& testCtx, bool useStorageBuffer, int numElements = 65535, bool verifyReturnValues = false)
693 {
694         std::string                                             groupName                       ("opatomic");
695         if (useStorageBuffer)
696                 groupName += "_storage_buffer";
697         if (verifyReturnValues)
698                 groupName += "_return_values";
699         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Test the OpAtomic* opcodes"));
700         vector<OpAtomicCase>                    cases;
701
702         const StringTemplate                    shaderTemplate  (
703
704                 string("OpCapability Shader\n") +
705                 (useStorageBuffer ? "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n" : "") +
706                 "OpMemoryModel Logical GLSL450\n"
707                 "OpEntryPoint GLCompute %main \"main\" %id\n"
708                 "OpExecutionMode %main LocalSize 1 1 1\n" +
709
710                 "OpSource GLSL 430\n"
711                 "OpName %main           \"main\"\n"
712                 "OpName %id             \"gl_GlobalInvocationID\"\n"
713
714                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
715
716                 "OpDecorate %buf ${BLOCK_DECORATION}\n"
717                 "OpDecorate %indata DescriptorSet 0\n"
718                 "OpDecorate %indata Binding 0\n"
719                 "OpDecorate %i32arr ArrayStride 4\n"
720                 "OpMemberDecorate %buf 0 Offset 0\n"
721
722                 "OpDecorate %sumbuf ${BLOCK_DECORATION}\n"
723                 "OpDecorate %sum DescriptorSet 0\n"
724                 "OpDecorate %sum Binding 1\n"
725                 "OpMemberDecorate %sumbuf 0 Coherent\n"
726                 "OpMemberDecorate %sumbuf 0 Offset 0\n"
727
728                 "${RETVAL_BUF_DECORATE}"
729
730                 + getComputeAsmCommonTypes("${BLOCK_POINTER_TYPE}") +
731
732                 "%buf       = OpTypeStruct %i32arr\n"
733                 "%bufptr    = OpTypePointer ${BLOCK_POINTER_TYPE} %buf\n"
734                 "%indata    = OpVariable %bufptr ${BLOCK_POINTER_TYPE}\n"
735
736                 "%sumbuf    = OpTypeStruct %i32arr\n"
737                 "%sumbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %sumbuf\n"
738                 "%sum       = OpVariable %sumbufptr ${BLOCK_POINTER_TYPE}\n"
739
740                 "${RETVAL_BUF_DECL}"
741
742                 "%id        = OpVariable %uvec3ptr Input\n"
743                 "%minusone  = OpConstant %i32 -1\n"
744                 "%zero      = OpConstant %i32 0\n"
745                 "%one       = OpConstant %u32 1\n"
746                 "%two       = OpConstant %i32 2\n"
747
748                 "%main      = OpFunction %void None %voidf\n"
749                 "%label     = OpLabel\n"
750                 "%idval     = OpLoad %uvec3 %id\n"
751                 "%x         = OpCompositeExtract %u32 %idval 0\n"
752
753                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
754                 "%inval     = OpLoad %i32 %inloc\n"
755
756                 "%outloc    = OpAccessChain %i32ptr %sum %zero ${INDEX}\n"
757                 "${INSTRUCTION}"
758                 "${RETVAL_ASSEMBLY}"
759
760                 "             OpReturn\n"
761                 "             OpFunctionEnd\n");
762
763         #define ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS) \
764         do { \
765                 DE_ASSERT((NUM_OUTPUT_ELEMENTS) == 1 || (NUM_OUTPUT_ELEMENTS) == numElements); \
766                 cases.push_back(OpAtomicCase(#NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, NUM_OUTPUT_ELEMENTS)); \
767         } while (deGetFalse())
768         #define ADD_OPATOMIC_CASE_1(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, 1)
769         #define ADD_OPATOMIC_CASE_N(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC) ADD_OPATOMIC_CASE(NAME, ASSEMBLY, RETVAL_ASSEMBLY, OPATOMIC, numElements)
770
771         ADD_OPATOMIC_CASE_1(iadd,       "%retv      = OpAtomicIAdd %i32 %outloc %one %zero %inval\n",
772                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IADD );
773         ADD_OPATOMIC_CASE_1(isub,       "%retv      = OpAtomicISub %i32 %outloc %one %zero %inval\n",
774                                                                 "             OpStore %retloc %retv\n", OPATOMIC_ISUB );
775         ADD_OPATOMIC_CASE_1(iinc,       "%retv      = OpAtomicIIncrement %i32 %outloc %one %zero\n",
776                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IINC );
777         ADD_OPATOMIC_CASE_1(idec,       "%retv      = OpAtomicIDecrement %i32 %outloc %one %zero\n",
778                                                                 "             OpStore %retloc %retv\n", OPATOMIC_IDEC );
779         if (!verifyReturnValues)
780         {
781                 ADD_OPATOMIC_CASE_N(load,       "%inval2    = OpAtomicLoad %i32 %inloc %one %zero\n"
782                                                                         "             OpStore %outloc %inval2\n", "", OPATOMIC_LOAD );
783                 ADD_OPATOMIC_CASE_N(store,      "             OpAtomicStore %outloc %one %zero %inval\n", "", OPATOMIC_STORE );
784         }
785
786         ADD_OPATOMIC_CASE_N(compex, "%even      = OpSMod %i32 %inval %two\n"
787                                                                 "             OpStore %outloc %even\n"
788                                                                 "%retv      = OpAtomicCompareExchange %i32 %outloc %one %zero %zero %minusone %zero\n",
789                                                                 "                         OpStore %retloc %retv\n", OPATOMIC_COMPEX );
790
791
792         #undef ADD_OPATOMIC_CASE
793         #undef ADD_OPATOMIC_CASE_1
794         #undef ADD_OPATOMIC_CASE_N
795
796         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
797         {
798                 map<string, string>                     specializations;
799                 ComputeShaderSpec                       spec;
800                 vector<deInt32>                         inputInts               (numElements, 0);
801                 vector<deInt32>                         expected                (cases[caseNdx].numOutputElements, -1);
802
803                 specializations["INDEX"]                                = (cases[caseNdx].numOutputElements == 1) ? "%zero" : "%x";
804                 specializations["INSTRUCTION"]                  = cases[caseNdx].assembly;
805                 specializations["BLOCK_DECORATION"]             = useStorageBuffer ? "Block" : "BufferBlock";
806                 specializations["BLOCK_POINTER_TYPE"]   = useStorageBuffer ? "StorageBuffer" : "Uniform";
807
808                 if (verifyReturnValues)
809                 {
810                         const StringTemplate blockDecoration    (
811                                 "\n"
812                                 "OpDecorate %retbuf ${BLOCK_DECORATION}\n"
813                                 "OpDecorate %ret DescriptorSet 0\n"
814                                 "OpDecorate %ret Binding 2\n"
815                                 "OpMemberDecorate %retbuf 0 Offset 0\n\n");
816
817                         const StringTemplate blockDeclaration   (
818                                 "\n"
819                                 "%retbuf    = OpTypeStruct %i32arr\n"
820                                 "%retbufptr = OpTypePointer ${BLOCK_POINTER_TYPE} %retbuf\n"
821                                 "%ret       = OpVariable %retbufptr ${BLOCK_POINTER_TYPE}\n\n");
822
823                         specializations["RETVAL_ASSEMBLY"] =
824                                 "%retloc    = OpAccessChain %i32ptr %ret %zero %x\n"
825                                 + std::string(cases[caseNdx].retValAssembly);
826
827                         specializations["RETVAL_BUF_DECORATE"]  = blockDecoration.specialize(specializations);
828                         specializations["RETVAL_BUF_DECL"]              = blockDeclaration.specialize(specializations);
829                 }
830                 else
831                 {
832                         specializations["RETVAL_ASSEMBLY"]              = "";
833                         specializations["RETVAL_BUF_DECORATE"]  = "";
834                         specializations["RETVAL_BUF_DECL"]              = "";
835                 }
836
837                 spec.assembly                                                   = shaderTemplate.specialize(specializations);
838
839                 if (useStorageBuffer)
840                         spec.extensions.push_back("VK_KHR_storage_buffer_storage_class");
841
842                 spec.inputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_INPUT)));
843                 spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_EXPECTED)));
844                 if (verifyReturnValues)
845                         spec.outputs.push_back(BufferSp(new OpAtomicBuffer(numElements, cases[caseNdx].numOutputElements, cases[caseNdx].opAtomic, BUFFERTYPE_ATOMIC_RET)));
846                 spec.numWorkGroups = IVec3(numElements, 1, 1);
847
848                 if (verifyReturnValues)
849                 {
850                         switch (cases[caseNdx].opAtomic)
851                         {
852                                 case OPATOMIC_IADD:
853                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IADD>;
854                                         break;
855                                 case OPATOMIC_ISUB:
856                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_ISUB>;
857                                         break;
858                                 case OPATOMIC_IINC:
859                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IINC>;
860                                         break;
861                                 case OPATOMIC_IDEC:
862                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_IDEC>;
863                                         break;
864                                 case OPATOMIC_COMPEX:
865                                         spec.verifyIO = OpAtomicBuffer::compareWithRetvals<OPATOMIC_COMPEX>;
866                                         break;
867                                 default:
868                                         DE_FATAL("Unsupported OpAtomic type for return value verification");
869                         }
870                 }
871                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
872         }
873
874         return group.release();
875 }
876
877 tcu::TestCaseGroup* createOpLineGroup (tcu::TestContext& testCtx)
878 {
879         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opline", "Test the OpLine instruction"));
880         ComputeShaderSpec                               spec;
881         de::Random                                              rnd                             (deStringHash(group->getName()));
882         const int                                               numElements             = 100;
883         vector<float>                                   positiveFloats  (numElements, 0);
884         vector<float>                                   negativeFloats  (numElements, 0);
885
886         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
887
888         for (size_t ndx = 0; ndx < numElements; ++ndx)
889                 negativeFloats[ndx] = -positiveFloats[ndx];
890
891         spec.assembly =
892                 string(getComputeAsmShaderPreamble()) +
893
894                 "%fname1 = OpString \"negateInputs.comp\"\n"
895                 "%fname2 = OpString \"negateInputs\"\n"
896
897                 "OpSource GLSL 430\n"
898                 "OpName %main           \"main\"\n"
899                 "OpName %id             \"gl_GlobalInvocationID\"\n"
900
901                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
902
903                 + string(getComputeAsmInputOutputBufferTraits()) +
904
905                 "OpLine %fname1 0 0\n" // At the earliest possible position
906
907                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
908
909                 "OpLine %fname1 0 1\n" // Multiple OpLines in sequence
910                 "OpLine %fname2 1 0\n" // Different filenames
911                 "OpLine %fname1 1000 100000\n"
912
913                 "%id        = OpVariable %uvec3ptr Input\n"
914                 "%zero      = OpConstant %i32 0\n"
915
916                 "OpLine %fname1 1 1\n" // Before a function
917
918                 "%main      = OpFunction %void None %voidf\n"
919                 "%label     = OpLabel\n"
920
921                 "OpLine %fname1 1 1\n" // In a function
922
923                 "%idval     = OpLoad %uvec3 %id\n"
924                 "%x         = OpCompositeExtract %u32 %idval 0\n"
925                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
926                 "%inval     = OpLoad %f32 %inloc\n"
927                 "%neg       = OpFNegate %f32 %inval\n"
928                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
929                 "             OpStore %outloc %neg\n"
930                 "             OpReturn\n"
931                 "             OpFunctionEnd\n";
932         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
933         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
934         spec.numWorkGroups = IVec3(numElements, 1, 1);
935
936         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpLine appearing at different places", spec));
937
938         return group.release();
939 }
940
941 bool veryfiBinaryShader (const ProgramBinary& binary)
942 {
943         const size_t    paternCount                     = 3u;
944         bool paternsCheck[paternCount]          =
945         {
946                 false, false, false
947         };
948         const string patersns[paternCount]      =
949         {
950                 "VULKAN CTS",
951                 "Negative values",
952                 "Date: 2017/09/21"
953         };
954         size_t                  paternNdx               = 0u;
955
956         for (size_t ndx = 0u; ndx < binary.getSize(); ++ndx)
957         {
958                 if (false == paternsCheck[paternNdx] &&
959                         patersns[paternNdx][0] == static_cast<char>(binary.getBinary()[ndx]) &&
960                         deMemoryEqual((const char*)&binary.getBinary()[ndx], &patersns[paternNdx][0], patersns[paternNdx].length()))
961                 {
962                         paternsCheck[paternNdx]= true;
963                         paternNdx++;
964                         if (paternNdx == paternCount)
965                                 break;
966                 }
967         }
968
969         for (size_t ndx = 0u; ndx < paternCount; ++ndx)
970         {
971                 if (!paternsCheck[ndx])
972                         return false;
973         }
974
975         return true;
976 }
977
978 tcu::TestCaseGroup* createOpModuleProcessedGroup (tcu::TestContext& testCtx)
979 {
980         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "Test the OpModuleProcessed instruction"));
981         ComputeShaderSpec                               spec;
982         de::Random                                              rnd                             (deStringHash(group->getName()));
983         const int                                               numElements             = 10;
984         vector<float>                                   positiveFloats  (numElements, 0);
985         vector<float>                                   negativeFloats  (numElements, 0);
986
987         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
988
989         for (size_t ndx = 0; ndx < numElements; ++ndx)
990                 negativeFloats[ndx] = -positiveFloats[ndx];
991
992         spec.assembly =
993                 string(getComputeAsmShaderPreamble()) +
994                 "%fname = OpString \"negateInputs.comp\"\n"
995
996                 "OpSource GLSL 430\n"
997                 "OpName %main           \"main\"\n"
998                 "OpName %id             \"gl_GlobalInvocationID\"\n"
999                 "OpModuleProcessed \"VULKAN CTS\"\n"                                    //OpModuleProcessed;
1000                 "OpModuleProcessed \"Negative values\"\n"
1001                 "OpModuleProcessed \"Date: 2017/09/21\"\n"
1002                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1003
1004                 + string(getComputeAsmInputOutputBufferTraits())
1005
1006                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
1007
1008                 "OpLine %fname 0 1\n"
1009
1010                 "OpLine %fname 1000 1\n"
1011
1012                 "%id        = OpVariable %uvec3ptr Input\n"
1013                 "%zero      = OpConstant %i32 0\n"
1014                 "%main      = OpFunction %void None %voidf\n"
1015
1016                 "%label     = OpLabel\n"
1017                 "%idval     = OpLoad %uvec3 %id\n"
1018                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1019
1020                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
1021                 "%inval     = OpLoad %f32 %inloc\n"
1022                 "%neg       = OpFNegate %f32 %inval\n"
1023                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1024                 "             OpStore %outloc %neg\n"
1025                 "             OpReturn\n"
1026                 "             OpFunctionEnd\n";
1027         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
1028         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
1029         spec.numWorkGroups = IVec3(numElements, 1, 1);
1030         spec.verifyBinary = veryfiBinaryShader;
1031         spec.spirvVersion = SPIRV_VERSION_1_3;
1032
1033         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpModuleProcessed Tests", spec));
1034
1035         return group.release();
1036 }
1037
1038 tcu::TestCaseGroup* createOpNoLineGroup (tcu::TestContext& testCtx)
1039 {
1040         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnoline", "Test the OpNoLine instruction"));
1041         ComputeShaderSpec                               spec;
1042         de::Random                                              rnd                             (deStringHash(group->getName()));
1043         const int                                               numElements             = 100;
1044         vector<float>                                   positiveFloats  (numElements, 0);
1045         vector<float>                                   negativeFloats  (numElements, 0);
1046
1047         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
1048
1049         for (size_t ndx = 0; ndx < numElements; ++ndx)
1050                 negativeFloats[ndx] = -positiveFloats[ndx];
1051
1052         spec.assembly =
1053                 string(getComputeAsmShaderPreamble()) +
1054
1055                 "%fname = OpString \"negateInputs.comp\"\n"
1056
1057                 "OpSource GLSL 430\n"
1058                 "OpName %main           \"main\"\n"
1059                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1060
1061                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1062
1063                 + string(getComputeAsmInputOutputBufferTraits()) +
1064
1065                 "OpNoLine\n" // At the earliest possible position, without preceding OpLine
1066
1067                 + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
1068
1069                 "OpLine %fname 0 1\n"
1070                 "OpNoLine\n" // Immediately following a preceding OpLine
1071
1072                 "OpLine %fname 1000 1\n"
1073
1074                 "%id        = OpVariable %uvec3ptr Input\n"
1075                 "%zero      = OpConstant %i32 0\n"
1076
1077                 "OpNoLine\n" // Contents after the previous OpLine
1078
1079                 "%main      = OpFunction %void None %voidf\n"
1080                 "%label     = OpLabel\n"
1081                 "%idval     = OpLoad %uvec3 %id\n"
1082                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1083
1084                 "OpNoLine\n" // Multiple OpNoLine
1085                 "OpNoLine\n"
1086                 "OpNoLine\n"
1087
1088                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
1089                 "%inval     = OpLoad %f32 %inloc\n"
1090                 "%neg       = OpFNegate %f32 %inval\n"
1091                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1092                 "             OpStore %outloc %neg\n"
1093                 "             OpReturn\n"
1094                 "             OpFunctionEnd\n";
1095         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
1096         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
1097         spec.numWorkGroups = IVec3(numElements, 1, 1);
1098
1099         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpNoLine appearing at different places", spec));
1100
1101         return group.release();
1102 }
1103
1104 // Compare instruction for the contraction compute case.
1105 // Returns true if the output is what is expected from the test case.
1106 bool compareNoContractCase(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1107 {
1108         if (outputAllocs.size() != 1)
1109                 return false;
1110
1111         // Only size is needed because we are not comparing the exact values.
1112         size_t byteSize = expectedOutputs[0].getByteSize();
1113
1114         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1115
1116         for(size_t i = 0; i < byteSize / sizeof(float); ++i) {
1117                 if (outputAsFloat[i] != 0.f &&
1118                         outputAsFloat[i] != -ldexp(1, -24)) {
1119                         return false;
1120                 }
1121         }
1122
1123         return true;
1124 }
1125
1126 tcu::TestCaseGroup* createNoContractionGroup (tcu::TestContext& testCtx)
1127 {
1128         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
1129         vector<CaseParameter>                   cases;
1130         const int                                               numElements             = 100;
1131         vector<float>                                   inputFloats1    (numElements, 0);
1132         vector<float>                                   inputFloats2    (numElements, 0);
1133         vector<float>                                   outputFloats    (numElements, 0);
1134         const StringTemplate                    shaderTemplate  (
1135                 string(getComputeAsmShaderPreamble()) +
1136
1137                 "OpName %main           \"main\"\n"
1138                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1139
1140                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1141
1142                 "${DECORATION}\n"
1143
1144                 "OpDecorate %buf BufferBlock\n"
1145                 "OpDecorate %indata1 DescriptorSet 0\n"
1146                 "OpDecorate %indata1 Binding 0\n"
1147                 "OpDecorate %indata2 DescriptorSet 0\n"
1148                 "OpDecorate %indata2 Binding 1\n"
1149                 "OpDecorate %outdata DescriptorSet 0\n"
1150                 "OpDecorate %outdata Binding 2\n"
1151                 "OpDecorate %f32arr ArrayStride 4\n"
1152                 "OpMemberDecorate %buf 0 Offset 0\n"
1153
1154                 + string(getComputeAsmCommonTypes()) +
1155
1156                 "%buf        = OpTypeStruct %f32arr\n"
1157                 "%bufptr     = OpTypePointer Uniform %buf\n"
1158                 "%indata1    = OpVariable %bufptr Uniform\n"
1159                 "%indata2    = OpVariable %bufptr Uniform\n"
1160                 "%outdata    = OpVariable %bufptr Uniform\n"
1161
1162                 "%id         = OpVariable %uvec3ptr Input\n"
1163                 "%zero       = OpConstant %i32 0\n"
1164                 "%c_f_m1     = OpConstant %f32 -1.\n"
1165
1166                 "%main       = OpFunction %void None %voidf\n"
1167                 "%label      = OpLabel\n"
1168                 "%idval      = OpLoad %uvec3 %id\n"
1169                 "%x          = OpCompositeExtract %u32 %idval 0\n"
1170                 "%inloc1     = OpAccessChain %f32ptr %indata1 %zero %x\n"
1171                 "%inval1     = OpLoad %f32 %inloc1\n"
1172                 "%inloc2     = OpAccessChain %f32ptr %indata2 %zero %x\n"
1173                 "%inval2     = OpLoad %f32 %inloc2\n"
1174                 "%mul        = OpFMul %f32 %inval1 %inval2\n"
1175                 "%add        = OpFAdd %f32 %mul %c_f_m1\n"
1176                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
1177                 "              OpStore %outloc %add\n"
1178                 "              OpReturn\n"
1179                 "              OpFunctionEnd\n");
1180
1181         cases.push_back(CaseParameter("multiplication", "OpDecorate %mul NoContraction"));
1182         cases.push_back(CaseParameter("addition",               "OpDecorate %add NoContraction"));
1183         cases.push_back(CaseParameter("both",                   "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"));
1184
1185         for (size_t ndx = 0; ndx < numElements; ++ndx)
1186         {
1187                 inputFloats1[ndx]       = 1.f + std::ldexp(1.f, -23); // 1 + 2^-23.
1188                 inputFloats2[ndx]       = 1.f - std::ldexp(1.f, -23); // 1 - 2^-23.
1189                 // Result for (1 + 2^-23) * (1 - 2^-23) - 1. With NoContraction, the multiplication will be
1190                 // conducted separately and the result is rounded to 1, or 0x1.fffffcp-1
1191                 // So the final result will be 0.f or 0x1p-24.
1192                 // If the operation is combined into a precise fused multiply-add, then the result would be
1193                 // 2^-46 (0xa8800000).
1194                 outputFloats[ndx]       = 0.f;
1195         }
1196
1197         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
1198         {
1199                 map<string, string>             specializations;
1200                 ComputeShaderSpec               spec;
1201
1202                 specializations["DECORATION"] = cases[caseNdx].param;
1203                 spec.assembly = shaderTemplate.specialize(specializations);
1204                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1205                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1206                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1207                 spec.numWorkGroups = IVec3(numElements, 1, 1);
1208                 // Check against the two possible answers based on rounding mode.
1209                 spec.verifyIO = &compareNoContractCase;
1210
1211                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
1212         }
1213         return group.release();
1214 }
1215
1216 bool compareFRem(const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1217 {
1218         if (outputAllocs.size() != 1)
1219                 return false;
1220
1221         vector<deUint8> expectedBytes;
1222         expectedOutputs[0].getBytes(expectedBytes);
1223
1224         const float*    expectedOutputAsFloat   = reinterpret_cast<const float*>(&expectedBytes.front());
1225         const float*    outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1226
1227         for (size_t idx = 0; idx < expectedBytes.size() / sizeof(float); ++idx)
1228         {
1229                 const float f0 = expectedOutputAsFloat[idx];
1230                 const float f1 = outputAsFloat[idx];
1231                 // \todo relative error needs to be fairly high because FRem may be implemented as
1232                 // (roughly) frac(a/b)*b, so LSB errors can be magnified. But this should be fine for now.
1233                 if (deFloatAbs((f1 - f0) / f0) > 0.02)
1234                         return false;
1235         }
1236
1237         return true;
1238 }
1239
1240 tcu::TestCaseGroup* createOpFRemGroup (tcu::TestContext& testCtx)
1241 {
1242         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opfrem", "Test the OpFRem instruction"));
1243         ComputeShaderSpec                               spec;
1244         de::Random                                              rnd                             (deStringHash(group->getName()));
1245         const int                                               numElements             = 200;
1246         vector<float>                                   inputFloats1    (numElements, 0);
1247         vector<float>                                   inputFloats2    (numElements, 0);
1248         vector<float>                                   outputFloats    (numElements, 0);
1249
1250         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1251         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats2[0], numElements);
1252
1253         for (size_t ndx = 0; ndx < numElements; ++ndx)
1254         {
1255                 // Guard against divisors near zero.
1256                 if (std::fabs(inputFloats2[ndx]) < 1e-3)
1257                         inputFloats2[ndx] = 8.f;
1258
1259                 // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1260                 outputFloats[ndx] = std::fmod(inputFloats1[ndx], inputFloats2[ndx]);
1261         }
1262
1263         spec.assembly =
1264                 string(getComputeAsmShaderPreamble()) +
1265
1266                 "OpName %main           \"main\"\n"
1267                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1268
1269                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1270
1271                 "OpDecorate %buf BufferBlock\n"
1272                 "OpDecorate %indata1 DescriptorSet 0\n"
1273                 "OpDecorate %indata1 Binding 0\n"
1274                 "OpDecorate %indata2 DescriptorSet 0\n"
1275                 "OpDecorate %indata2 Binding 1\n"
1276                 "OpDecorate %outdata DescriptorSet 0\n"
1277                 "OpDecorate %outdata Binding 2\n"
1278                 "OpDecorate %f32arr ArrayStride 4\n"
1279                 "OpMemberDecorate %buf 0 Offset 0\n"
1280
1281                 + string(getComputeAsmCommonTypes()) +
1282
1283                 "%buf        = OpTypeStruct %f32arr\n"
1284                 "%bufptr     = OpTypePointer Uniform %buf\n"
1285                 "%indata1    = OpVariable %bufptr Uniform\n"
1286                 "%indata2    = OpVariable %bufptr Uniform\n"
1287                 "%outdata    = OpVariable %bufptr Uniform\n"
1288
1289                 "%id        = OpVariable %uvec3ptr Input\n"
1290                 "%zero      = OpConstant %i32 0\n"
1291
1292                 "%main      = OpFunction %void None %voidf\n"
1293                 "%label     = OpLabel\n"
1294                 "%idval     = OpLoad %uvec3 %id\n"
1295                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1296                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1297                 "%inval1    = OpLoad %f32 %inloc1\n"
1298                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1299                 "%inval2    = OpLoad %f32 %inloc2\n"
1300                 "%rem       = OpFRem %f32 %inval1 %inval2\n"
1301                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1302                 "             OpStore %outloc %rem\n"
1303                 "             OpReturn\n"
1304                 "             OpFunctionEnd\n";
1305
1306         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1307         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1308         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1309         spec.numWorkGroups = IVec3(numElements, 1, 1);
1310         spec.verifyIO = &compareFRem;
1311
1312         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1313
1314         return group.release();
1315 }
1316
1317 bool compareNMin (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1318 {
1319         if (outputAllocs.size() != 1)
1320                 return false;
1321
1322         const BufferSp&                 expectedOutput                  (expectedOutputs[0].getBuffer());
1323         std::vector<deUint8>    data;
1324         expectedOutput->getBytes(data);
1325
1326         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1327         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1328
1329         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1330         {
1331                 const float f0 = expectedOutputAsFloat[idx];
1332                 const float f1 = outputAsFloat[idx];
1333
1334                 // For NMin, we accept NaN as output if both inputs were NaN.
1335                 // Otherwise the NaN is the wrong choise, as on architectures that
1336                 // do not handle NaN, those are huge values.
1337                 if (!(tcu::Float32(f1).isNaN() && tcu::Float32(f0).isNaN()) && deFloatAbs(f1 - f0) > 0.00001f)
1338                         return false;
1339         }
1340
1341         return true;
1342 }
1343
1344 tcu::TestCaseGroup* createOpNMinGroup (tcu::TestContext& testCtx)
1345 {
1346         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnmin", "Test the OpNMin instruction"));
1347         ComputeShaderSpec                               spec;
1348         de::Random                                              rnd                             (deStringHash(group->getName()));
1349         const int                                               numElements             = 200;
1350         vector<float>                                   inputFloats1    (numElements, 0);
1351         vector<float>                                   inputFloats2    (numElements, 0);
1352         vector<float>                                   outputFloats    (numElements, 0);
1353
1354         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1355         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1356
1357         // Make the first case a full-NAN case.
1358         inputFloats1[0] = TCU_NAN;
1359         inputFloats2[0] = TCU_NAN;
1360
1361         for (size_t ndx = 0; ndx < numElements; ++ndx)
1362         {
1363                 // By default, pick the smallest
1364                 outputFloats[ndx] = std::min(inputFloats1[ndx], inputFloats2[ndx]);
1365
1366                 // Make half of the cases NaN cases
1367                 if ((ndx & 1) == 0)
1368                 {
1369                         // Alternate between the NaN operand
1370                         if ((ndx & 2) == 0)
1371                         {
1372                                 outputFloats[ndx] = inputFloats2[ndx];
1373                                 inputFloats1[ndx] = TCU_NAN;
1374                         }
1375                         else
1376                         {
1377                                 outputFloats[ndx] = inputFloats1[ndx];
1378                                 inputFloats2[ndx] = TCU_NAN;
1379                         }
1380                 }
1381         }
1382
1383         spec.assembly =
1384                 "OpCapability Shader\n"
1385                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1386                 "OpMemoryModel Logical GLSL450\n"
1387                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1388                 "OpExecutionMode %main LocalSize 1 1 1\n"
1389
1390                 "OpName %main           \"main\"\n"
1391                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1392
1393                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1394
1395                 "OpDecorate %buf BufferBlock\n"
1396                 "OpDecorate %indata1 DescriptorSet 0\n"
1397                 "OpDecorate %indata1 Binding 0\n"
1398                 "OpDecorate %indata2 DescriptorSet 0\n"
1399                 "OpDecorate %indata2 Binding 1\n"
1400                 "OpDecorate %outdata DescriptorSet 0\n"
1401                 "OpDecorate %outdata Binding 2\n"
1402                 "OpDecorate %f32arr ArrayStride 4\n"
1403                 "OpMemberDecorate %buf 0 Offset 0\n"
1404
1405                 + string(getComputeAsmCommonTypes()) +
1406
1407                 "%buf        = OpTypeStruct %f32arr\n"
1408                 "%bufptr     = OpTypePointer Uniform %buf\n"
1409                 "%indata1    = OpVariable %bufptr Uniform\n"
1410                 "%indata2    = OpVariable %bufptr Uniform\n"
1411                 "%outdata    = OpVariable %bufptr Uniform\n"
1412
1413                 "%id        = OpVariable %uvec3ptr Input\n"
1414                 "%zero      = OpConstant %i32 0\n"
1415
1416                 "%main      = OpFunction %void None %voidf\n"
1417                 "%label     = OpLabel\n"
1418                 "%idval     = OpLoad %uvec3 %id\n"
1419                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1420                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1421                 "%inval1    = OpLoad %f32 %inloc1\n"
1422                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1423                 "%inval2    = OpLoad %f32 %inloc2\n"
1424                 "%rem       = OpExtInst %f32 %std450 NMin %inval1 %inval2\n"
1425                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1426                 "             OpStore %outloc %rem\n"
1427                 "             OpReturn\n"
1428                 "             OpFunctionEnd\n";
1429
1430         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1431         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1432         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1433         spec.numWorkGroups = IVec3(numElements, 1, 1);
1434         spec.verifyIO = &compareNMin;
1435
1436         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1437
1438         return group.release();
1439 }
1440
1441 bool compareNMax (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1442 {
1443         if (outputAllocs.size() != 1)
1444                 return false;
1445
1446         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1447         std::vector<deUint8>    data;
1448         expectedOutput->getBytes(data);
1449
1450         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1451         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1452
1453         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float); ++idx)
1454         {
1455                 const float f0 = expectedOutputAsFloat[idx];
1456                 const float f1 = outputAsFloat[idx];
1457
1458                 // For NMax, NaN is considered acceptable result, since in
1459                 // architectures that do not handle NaNs, those are huge values.
1460                 if (!tcu::Float32(f1).isNaN() && deFloatAbs(f1 - f0) > 0.00001f)
1461                         return false;
1462         }
1463
1464         return true;
1465 }
1466
1467 tcu::TestCaseGroup* createOpNMaxGroup (tcu::TestContext& testCtx)
1468 {
1469         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opnmax", "Test the OpNMax instruction"));
1470         ComputeShaderSpec                               spec;
1471         de::Random                                              rnd                             (deStringHash(group->getName()));
1472         const int                                               numElements             = 200;
1473         vector<float>                                   inputFloats1    (numElements, 0);
1474         vector<float>                                   inputFloats2    (numElements, 0);
1475         vector<float>                                   outputFloats    (numElements, 0);
1476
1477         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1478         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1479
1480         // Make the first case a full-NAN case.
1481         inputFloats1[0] = TCU_NAN;
1482         inputFloats2[0] = TCU_NAN;
1483
1484         for (size_t ndx = 0; ndx < numElements; ++ndx)
1485         {
1486                 // By default, pick the biggest
1487                 outputFloats[ndx] = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1488
1489                 // Make half of the cases NaN cases
1490                 if ((ndx & 1) == 0)
1491                 {
1492                         // Alternate between the NaN operand
1493                         if ((ndx & 2) == 0)
1494                         {
1495                                 outputFloats[ndx] = inputFloats2[ndx];
1496                                 inputFloats1[ndx] = TCU_NAN;
1497                         }
1498                         else
1499                         {
1500                                 outputFloats[ndx] = inputFloats1[ndx];
1501                                 inputFloats2[ndx] = TCU_NAN;
1502                         }
1503                 }
1504         }
1505
1506         spec.assembly =
1507                 "OpCapability Shader\n"
1508                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1509                 "OpMemoryModel Logical GLSL450\n"
1510                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1511                 "OpExecutionMode %main LocalSize 1 1 1\n"
1512
1513                 "OpName %main           \"main\"\n"
1514                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1515
1516                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1517
1518                 "OpDecorate %buf BufferBlock\n"
1519                 "OpDecorate %indata1 DescriptorSet 0\n"
1520                 "OpDecorate %indata1 Binding 0\n"
1521                 "OpDecorate %indata2 DescriptorSet 0\n"
1522                 "OpDecorate %indata2 Binding 1\n"
1523                 "OpDecorate %outdata DescriptorSet 0\n"
1524                 "OpDecorate %outdata Binding 2\n"
1525                 "OpDecorate %f32arr ArrayStride 4\n"
1526                 "OpMemberDecorate %buf 0 Offset 0\n"
1527
1528                 + string(getComputeAsmCommonTypes()) +
1529
1530                 "%buf        = OpTypeStruct %f32arr\n"
1531                 "%bufptr     = OpTypePointer Uniform %buf\n"
1532                 "%indata1    = OpVariable %bufptr Uniform\n"
1533                 "%indata2    = OpVariable %bufptr Uniform\n"
1534                 "%outdata    = OpVariable %bufptr Uniform\n"
1535
1536                 "%id        = OpVariable %uvec3ptr Input\n"
1537                 "%zero      = OpConstant %i32 0\n"
1538
1539                 "%main      = OpFunction %void None %voidf\n"
1540                 "%label     = OpLabel\n"
1541                 "%idval     = OpLoad %uvec3 %id\n"
1542                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1543                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1544                 "%inval1    = OpLoad %f32 %inloc1\n"
1545                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1546                 "%inval2    = OpLoad %f32 %inloc2\n"
1547                 "%rem       = OpExtInst %f32 %std450 NMax %inval1 %inval2\n"
1548                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1549                 "             OpStore %outloc %rem\n"
1550                 "             OpReturn\n"
1551                 "             OpFunctionEnd\n";
1552
1553         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1554         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1555         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1556         spec.numWorkGroups = IVec3(numElements, 1, 1);
1557         spec.verifyIO = &compareNMax;
1558
1559         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1560
1561         return group.release();
1562 }
1563
1564 bool compareNClamp (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
1565 {
1566         if (outputAllocs.size() != 1)
1567                 return false;
1568
1569         const BufferSp&                 expectedOutput                  = expectedOutputs[0].getBuffer();
1570         std::vector<deUint8>    data;
1571         expectedOutput->getBytes(data);
1572
1573         const float* const              expectedOutputAsFloat   = reinterpret_cast<const float*>(&data.front());
1574         const float* const              outputAsFloat                   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
1575
1576         for (size_t idx = 0; idx < expectedOutput->getByteSize() / sizeof(float) / 2; ++idx)
1577         {
1578                 const float e0 = expectedOutputAsFloat[idx * 2];
1579                 const float e1 = expectedOutputAsFloat[idx * 2 + 1];
1580                 const float res = outputAsFloat[idx];
1581
1582                 // For NClamp, we have two possible outcomes based on
1583                 // whether NaNs are handled or not.
1584                 // If either min or max value is NaN, the result is undefined,
1585                 // so this test doesn't stress those. If the clamped value is
1586                 // NaN, and NaNs are handled, the result is min; if NaNs are not
1587                 // handled, they are big values that result in max.
1588                 // If all three parameters are NaN, the result should be NaN.
1589                 if (!((tcu::Float32(e0).isNaN() && tcu::Float32(res).isNaN()) ||
1590                          (deFloatAbs(e0 - res) < 0.00001f) ||
1591                          (deFloatAbs(e1 - res) < 0.00001f)))
1592                         return false;
1593         }
1594
1595         return true;
1596 }
1597
1598 tcu::TestCaseGroup* createOpNClampGroup (tcu::TestContext& testCtx)
1599 {
1600         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opnclamp", "Test the OpNClamp instruction"));
1601         ComputeShaderSpec                               spec;
1602         de::Random                                              rnd                             (deStringHash(group->getName()));
1603         const int                                               numElements             = 200;
1604         vector<float>                                   inputFloats1    (numElements, 0);
1605         vector<float>                                   inputFloats2    (numElements, 0);
1606         vector<float>                                   inputFloats3    (numElements, 0);
1607         vector<float>                                   outputFloats    (numElements * 2, 0);
1608
1609         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats1[0], numElements);
1610         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats2[0], numElements);
1611         fillRandomScalars(rnd, -10000.f, 10000.f, &inputFloats3[0], numElements);
1612
1613         for (size_t ndx = 0; ndx < numElements; ++ndx)
1614         {
1615                 // Results are only defined if max value is bigger than min value.
1616                 if (inputFloats2[ndx] > inputFloats3[ndx])
1617                 {
1618                         float t = inputFloats2[ndx];
1619                         inputFloats2[ndx] = inputFloats3[ndx];
1620                         inputFloats3[ndx] = t;
1621                 }
1622
1623                 // By default, do the clamp, setting both possible answers
1624                 float defaultRes = std::min(std::max(inputFloats1[ndx], inputFloats2[ndx]), inputFloats3[ndx]);
1625
1626                 float maxResA = std::max(inputFloats1[ndx], inputFloats2[ndx]);
1627                 float maxResB = maxResA;
1628
1629                 // Alternate between the NaN cases
1630                 if (ndx & 1)
1631                 {
1632                         inputFloats1[ndx] = TCU_NAN;
1633                         // If NaN is handled, the result should be same as the clamp minimum.
1634                         // If NaN is not handled, the result should clamp to the clamp maximum.
1635                         maxResA = inputFloats2[ndx];
1636                         maxResB = inputFloats3[ndx];
1637                 }
1638                 else
1639                 {
1640                         // Not a NaN case - only one legal result.
1641                         maxResA = defaultRes;
1642                         maxResB = defaultRes;
1643                 }
1644
1645                 outputFloats[ndx * 2] = maxResA;
1646                 outputFloats[ndx * 2 + 1] = maxResB;
1647         }
1648
1649         // Make the first case a full-NAN case.
1650         inputFloats1[0] = TCU_NAN;
1651         inputFloats2[0] = TCU_NAN;
1652         inputFloats3[0] = TCU_NAN;
1653         outputFloats[0] = TCU_NAN;
1654         outputFloats[1] = TCU_NAN;
1655
1656         spec.assembly =
1657                 "OpCapability Shader\n"
1658                 "%std450        = OpExtInstImport \"GLSL.std.450\"\n"
1659                 "OpMemoryModel Logical GLSL450\n"
1660                 "OpEntryPoint GLCompute %main \"main\" %id\n"
1661                 "OpExecutionMode %main LocalSize 1 1 1\n"
1662
1663                 "OpName %main           \"main\"\n"
1664                 "OpName %id             \"gl_GlobalInvocationID\"\n"
1665
1666                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
1667
1668                 "OpDecorate %buf BufferBlock\n"
1669                 "OpDecorate %indata1 DescriptorSet 0\n"
1670                 "OpDecorate %indata1 Binding 0\n"
1671                 "OpDecorate %indata2 DescriptorSet 0\n"
1672                 "OpDecorate %indata2 Binding 1\n"
1673                 "OpDecorate %indata3 DescriptorSet 0\n"
1674                 "OpDecorate %indata3 Binding 2\n"
1675                 "OpDecorate %outdata DescriptorSet 0\n"
1676                 "OpDecorate %outdata Binding 3\n"
1677                 "OpDecorate %f32arr ArrayStride 4\n"
1678                 "OpMemberDecorate %buf 0 Offset 0\n"
1679
1680                 + string(getComputeAsmCommonTypes()) +
1681
1682                 "%buf        = OpTypeStruct %f32arr\n"
1683                 "%bufptr     = OpTypePointer Uniform %buf\n"
1684                 "%indata1    = OpVariable %bufptr Uniform\n"
1685                 "%indata2    = OpVariable %bufptr Uniform\n"
1686                 "%indata3    = OpVariable %bufptr Uniform\n"
1687                 "%outdata    = OpVariable %bufptr Uniform\n"
1688
1689                 "%id        = OpVariable %uvec3ptr Input\n"
1690                 "%zero      = OpConstant %i32 0\n"
1691
1692                 "%main      = OpFunction %void None %voidf\n"
1693                 "%label     = OpLabel\n"
1694                 "%idval     = OpLoad %uvec3 %id\n"
1695                 "%x         = OpCompositeExtract %u32 %idval 0\n"
1696                 "%inloc1    = OpAccessChain %f32ptr %indata1 %zero %x\n"
1697                 "%inval1    = OpLoad %f32 %inloc1\n"
1698                 "%inloc2    = OpAccessChain %f32ptr %indata2 %zero %x\n"
1699                 "%inval2    = OpLoad %f32 %inloc2\n"
1700                 "%inloc3    = OpAccessChain %f32ptr %indata3 %zero %x\n"
1701                 "%inval3    = OpLoad %f32 %inloc3\n"
1702                 "%rem       = OpExtInst %f32 %std450 NClamp %inval1 %inval2 %inval3\n"
1703                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
1704                 "             OpStore %outloc %rem\n"
1705                 "             OpReturn\n"
1706                 "             OpFunctionEnd\n";
1707
1708         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
1709         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
1710         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
1711         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
1712         spec.numWorkGroups = IVec3(numElements, 1, 1);
1713         spec.verifyIO = &compareNClamp;
1714
1715         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "", spec));
1716
1717         return group.release();
1718 }
1719
1720 tcu::TestCaseGroup* createOpSRemComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1721 {
1722         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem", "Test the OpSRem instruction"));
1723         de::Random                                              rnd                             (deStringHash(group->getName()));
1724         const int                                               numElements             = 200;
1725
1726         const struct CaseParams
1727         {
1728                 const char*             name;
1729                 const char*             failMessage;            // customized status message
1730                 qpTestResult    failResult;                     // override status on failure
1731                 int                             op1Min, op1Max;         // operand ranges
1732                 int                             op2Min, op2Max;
1733         } cases[] =
1734         {
1735                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1736                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1737         };
1738         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1739
1740         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1741         {
1742                 const CaseParams&       params          = cases[caseNdx];
1743                 ComputeShaderSpec       spec;
1744                 vector<deInt32>         inputInts1      (numElements, 0);
1745                 vector<deInt32>         inputInts2      (numElements, 0);
1746                 vector<deInt32>         outputInts      (numElements, 0);
1747
1748                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1749                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1750
1751                 for (int ndx = 0; ndx < numElements; ++ndx)
1752                 {
1753                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1754                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1755                 }
1756
1757                 spec.assembly =
1758                         string(getComputeAsmShaderPreamble()) +
1759
1760                         "OpName %main           \"main\"\n"
1761                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1762
1763                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1764
1765                         "OpDecorate %buf BufferBlock\n"
1766                         "OpDecorate %indata1 DescriptorSet 0\n"
1767                         "OpDecorate %indata1 Binding 0\n"
1768                         "OpDecorate %indata2 DescriptorSet 0\n"
1769                         "OpDecorate %indata2 Binding 1\n"
1770                         "OpDecorate %outdata DescriptorSet 0\n"
1771                         "OpDecorate %outdata Binding 2\n"
1772                         "OpDecorate %i32arr ArrayStride 4\n"
1773                         "OpMemberDecorate %buf 0 Offset 0\n"
1774
1775                         + string(getComputeAsmCommonTypes()) +
1776
1777                         "%buf        = OpTypeStruct %i32arr\n"
1778                         "%bufptr     = OpTypePointer Uniform %buf\n"
1779                         "%indata1    = OpVariable %bufptr Uniform\n"
1780                         "%indata2    = OpVariable %bufptr Uniform\n"
1781                         "%outdata    = OpVariable %bufptr Uniform\n"
1782
1783                         "%id        = OpVariable %uvec3ptr Input\n"
1784                         "%zero      = OpConstant %i32 0\n"
1785
1786                         "%main      = OpFunction %void None %voidf\n"
1787                         "%label     = OpLabel\n"
1788                         "%idval     = OpLoad %uvec3 %id\n"
1789                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1790                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
1791                         "%inval1    = OpLoad %i32 %inloc1\n"
1792                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
1793                         "%inval2    = OpLoad %i32 %inloc2\n"
1794                         "%rem       = OpSRem %i32 %inval1 %inval2\n"
1795                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
1796                         "             OpStore %outloc %rem\n"
1797                         "             OpReturn\n"
1798                         "             OpFunctionEnd\n";
1799
1800                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
1801                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
1802                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
1803                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1804                 spec.failResult                 = params.failResult;
1805                 spec.failMessage                = params.failMessage;
1806
1807                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1808         }
1809
1810         return group.release();
1811 }
1812
1813 tcu::TestCaseGroup* createOpSRemComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
1814 {
1815         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsrem64", "Test the 64-bit OpSRem instruction"));
1816         de::Random                                              rnd                             (deStringHash(group->getName()));
1817         const int                                               numElements             = 200;
1818
1819         const struct CaseParams
1820         {
1821                 const char*             name;
1822                 const char*             failMessage;            // customized status message
1823                 qpTestResult    failResult;                     // override status on failure
1824                 bool                    positive;
1825         } cases[] =
1826         {
1827                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
1828                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
1829         };
1830         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1831
1832         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1833         {
1834                 const CaseParams&       params          = cases[caseNdx];
1835                 ComputeShaderSpec       spec;
1836                 vector<deInt64>         inputInts1      (numElements, 0);
1837                 vector<deInt64>         inputInts2      (numElements, 0);
1838                 vector<deInt64>         outputInts      (numElements, 0);
1839
1840                 if (params.positive)
1841                 {
1842                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
1843                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
1844                 }
1845                 else
1846                 {
1847                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
1848                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
1849                 }
1850
1851                 for (int ndx = 0; ndx < numElements; ++ndx)
1852                 {
1853                         // The return value of std::fmod() has the same sign as its first operand, which is how OpFRem spec'd.
1854                         outputInts[ndx] = inputInts1[ndx] % inputInts2[ndx];
1855                 }
1856
1857                 spec.assembly =
1858                         "OpCapability Int64\n"
1859
1860                         + string(getComputeAsmShaderPreamble()) +
1861
1862                         "OpName %main           \"main\"\n"
1863                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1864
1865                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1866
1867                         "OpDecorate %buf BufferBlock\n"
1868                         "OpDecorate %indata1 DescriptorSet 0\n"
1869                         "OpDecorate %indata1 Binding 0\n"
1870                         "OpDecorate %indata2 DescriptorSet 0\n"
1871                         "OpDecorate %indata2 Binding 1\n"
1872                         "OpDecorate %outdata DescriptorSet 0\n"
1873                         "OpDecorate %outdata Binding 2\n"
1874                         "OpDecorate %i64arr ArrayStride 8\n"
1875                         "OpMemberDecorate %buf 0 Offset 0\n"
1876
1877                         + string(getComputeAsmCommonTypes())
1878                         + string(getComputeAsmCommonInt64Types()) +
1879
1880                         "%buf        = OpTypeStruct %i64arr\n"
1881                         "%bufptr     = OpTypePointer Uniform %buf\n"
1882                         "%indata1    = OpVariable %bufptr Uniform\n"
1883                         "%indata2    = OpVariable %bufptr Uniform\n"
1884                         "%outdata    = OpVariable %bufptr Uniform\n"
1885
1886                         "%id        = OpVariable %uvec3ptr Input\n"
1887                         "%zero      = OpConstant %i64 0\n"
1888
1889                         "%main      = OpFunction %void None %voidf\n"
1890                         "%label     = OpLabel\n"
1891                         "%idval     = OpLoad %uvec3 %id\n"
1892                         "%x         = OpCompositeExtract %u32 %idval 0\n"
1893                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
1894                         "%inval1    = OpLoad %i64 %inloc1\n"
1895                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
1896                         "%inval2    = OpLoad %i64 %inloc2\n"
1897                         "%rem       = OpSRem %i64 %inval1 %inval2\n"
1898                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
1899                         "             OpStore %outloc %rem\n"
1900                         "             OpReturn\n"
1901                         "             OpFunctionEnd\n";
1902
1903                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
1904                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
1905                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
1906                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
1907                 spec.failResult                 = params.failResult;
1908                 spec.failMessage                = params.failMessage;
1909
1910                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
1911
1912                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
1913         }
1914
1915         return group.release();
1916 }
1917
1918 tcu::TestCaseGroup* createOpSModComputeGroup (tcu::TestContext& testCtx, qpTestResult negFailResult)
1919 {
1920         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod", "Test the OpSMod instruction"));
1921         de::Random                                              rnd                             (deStringHash(group->getName()));
1922         const int                                               numElements             = 200;
1923
1924         const struct CaseParams
1925         {
1926                 const char*             name;
1927                 const char*             failMessage;            // customized status message
1928                 qpTestResult    failResult;                     // override status on failure
1929                 int                             op1Min, op1Max;         // operand ranges
1930                 int                             op2Min, op2Max;
1931         } cases[] =
1932         {
1933                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    0,              65536,  0,              100 },
1934                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  -65536, 65536,  -100,   100 },  // see below
1935         };
1936         // If either operand is negative the result is undefined. Some implementations may still return correct values.
1937
1938         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
1939         {
1940                 const CaseParams&       params          = cases[caseNdx];
1941
1942                 ComputeShaderSpec       spec;
1943                 vector<deInt32>         inputInts1      (numElements, 0);
1944                 vector<deInt32>         inputInts2      (numElements, 0);
1945                 vector<deInt32>         outputInts      (numElements, 0);
1946
1947                 fillRandomScalars(rnd, params.op1Min, params.op1Max, &inputInts1[0], numElements);
1948                 fillRandomScalars(rnd, params.op2Min, params.op2Max, &inputInts2[0], numElements, filterNotZero);
1949
1950                 for (int ndx = 0; ndx < numElements; ++ndx)
1951                 {
1952                         deInt32 rem = inputInts1[ndx] % inputInts2[ndx];
1953                         if (rem == 0)
1954                         {
1955                                 outputInts[ndx] = 0;
1956                         }
1957                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
1958                         {
1959                                 // They have the same sign
1960                                 outputInts[ndx] = rem;
1961                         }
1962                         else
1963                         {
1964                                 // They have opposite sign.  The remainder operation takes the
1965                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
1966                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
1967                                 // the result has the correct sign and that it is still
1968                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
1969                                 //
1970                                 // See also http://mathforum.org/library/drmath/view/52343.html
1971                                 outputInts[ndx] = rem + inputInts2[ndx];
1972                         }
1973                 }
1974
1975                 spec.assembly =
1976                         string(getComputeAsmShaderPreamble()) +
1977
1978                         "OpName %main           \"main\"\n"
1979                         "OpName %id             \"gl_GlobalInvocationID\"\n"
1980
1981                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
1982
1983                         "OpDecorate %buf BufferBlock\n"
1984                         "OpDecorate %indata1 DescriptorSet 0\n"
1985                         "OpDecorate %indata1 Binding 0\n"
1986                         "OpDecorate %indata2 DescriptorSet 0\n"
1987                         "OpDecorate %indata2 Binding 1\n"
1988                         "OpDecorate %outdata DescriptorSet 0\n"
1989                         "OpDecorate %outdata Binding 2\n"
1990                         "OpDecorate %i32arr ArrayStride 4\n"
1991                         "OpMemberDecorate %buf 0 Offset 0\n"
1992
1993                         + string(getComputeAsmCommonTypes()) +
1994
1995                         "%buf        = OpTypeStruct %i32arr\n"
1996                         "%bufptr     = OpTypePointer Uniform %buf\n"
1997                         "%indata1    = OpVariable %bufptr Uniform\n"
1998                         "%indata2    = OpVariable %bufptr Uniform\n"
1999                         "%outdata    = OpVariable %bufptr Uniform\n"
2000
2001                         "%id        = OpVariable %uvec3ptr Input\n"
2002                         "%zero      = OpConstant %i32 0\n"
2003
2004                         "%main      = OpFunction %void None %voidf\n"
2005                         "%label     = OpLabel\n"
2006                         "%idval     = OpLoad %uvec3 %id\n"
2007                         "%x         = OpCompositeExtract %u32 %idval 0\n"
2008                         "%inloc1    = OpAccessChain %i32ptr %indata1 %zero %x\n"
2009                         "%inval1    = OpLoad %i32 %inloc1\n"
2010                         "%inloc2    = OpAccessChain %i32ptr %indata2 %zero %x\n"
2011                         "%inval2    = OpLoad %i32 %inloc2\n"
2012                         "%rem       = OpSMod %i32 %inval1 %inval2\n"
2013                         "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2014                         "             OpStore %outloc %rem\n"
2015                         "             OpReturn\n"
2016                         "             OpFunctionEnd\n";
2017
2018                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts1)));
2019                 spec.inputs.push_back   (BufferSp(new Int32Buffer(inputInts2)));
2020                 spec.outputs.push_back  (BufferSp(new Int32Buffer(outputInts)));
2021                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
2022                 spec.failResult                 = params.failResult;
2023                 spec.failMessage                = params.failMessage;
2024
2025                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2026         }
2027
2028         return group.release();
2029 }
2030
2031 tcu::TestCaseGroup* createOpSModComputeGroup64 (tcu::TestContext& testCtx, qpTestResult negFailResult)
2032 {
2033         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsmod64", "Test the OpSMod instruction"));
2034         de::Random                                              rnd                             (deStringHash(group->getName()));
2035         const int                                               numElements             = 200;
2036
2037         const struct CaseParams
2038         {
2039                 const char*             name;
2040                 const char*             failMessage;            // customized status message
2041                 qpTestResult    failResult;                     // override status on failure
2042                 bool                    positive;
2043         } cases[] =
2044         {
2045                 { "positive",   "Output doesn't match with expected",                           QP_TEST_RESULT_FAIL,    true },
2046                 { "all",                "Inconsistent results, but within specification",       negFailResult,                  false },        // see below
2047         };
2048         // If either operand is negative the result is undefined. Some implementations may still return correct values.
2049
2050         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
2051         {
2052                 const CaseParams&       params          = cases[caseNdx];
2053
2054                 ComputeShaderSpec       spec;
2055                 vector<deInt64>         inputInts1      (numElements, 0);
2056                 vector<deInt64>         inputInts2      (numElements, 0);
2057                 vector<deInt64>         outputInts      (numElements, 0);
2058
2059
2060                 if (params.positive)
2061                 {
2062                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements, filterNonNegative);
2063                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterPositive);
2064                 }
2065                 else
2066                 {
2067                         fillRandomInt64sLogDistributed(rnd, inputInts1, numElements);
2068                         fillRandomInt64sLogDistributed(rnd, inputInts2, numElements, filterNotZero);
2069                 }
2070
2071                 for (int ndx = 0; ndx < numElements; ++ndx)
2072                 {
2073                         deInt64 rem = inputInts1[ndx] % inputInts2[ndx];
2074                         if (rem == 0)
2075                         {
2076                                 outputInts[ndx] = 0;
2077                         }
2078                         else if ((inputInts1[ndx] >= 0) == (inputInts2[ndx] >= 0))
2079                         {
2080                                 // They have the same sign
2081                                 outputInts[ndx] = rem;
2082                         }
2083                         else
2084                         {
2085                                 // They have opposite sign.  The remainder operation takes the
2086                                 // sign inputInts1[ndx] but OpSMod is supposed to take ths sign
2087                                 // of inputInts2[ndx].  Adding inputInts2[ndx] will ensure that
2088                                 // the result has the correct sign and that it is still
2089                                 // congruent to inputInts1[ndx] modulo inputInts2[ndx]
2090                                 //
2091                                 // See also http://mathforum.org/library/drmath/view/52343.html
2092                                 outputInts[ndx] = rem + inputInts2[ndx];
2093                         }
2094                 }
2095
2096                 spec.assembly =
2097                         "OpCapability Int64\n"
2098
2099                         + string(getComputeAsmShaderPreamble()) +
2100
2101                         "OpName %main           \"main\"\n"
2102                         "OpName %id             \"gl_GlobalInvocationID\"\n"
2103
2104                         "OpDecorate %id BuiltIn GlobalInvocationId\n"
2105
2106                         "OpDecorate %buf BufferBlock\n"
2107                         "OpDecorate %indata1 DescriptorSet 0\n"
2108                         "OpDecorate %indata1 Binding 0\n"
2109                         "OpDecorate %indata2 DescriptorSet 0\n"
2110                         "OpDecorate %indata2 Binding 1\n"
2111                         "OpDecorate %outdata DescriptorSet 0\n"
2112                         "OpDecorate %outdata Binding 2\n"
2113                         "OpDecorate %i64arr ArrayStride 8\n"
2114                         "OpMemberDecorate %buf 0 Offset 0\n"
2115
2116                         + string(getComputeAsmCommonTypes())
2117                         + string(getComputeAsmCommonInt64Types()) +
2118
2119                         "%buf        = OpTypeStruct %i64arr\n"
2120                         "%bufptr     = OpTypePointer Uniform %buf\n"
2121                         "%indata1    = OpVariable %bufptr Uniform\n"
2122                         "%indata2    = OpVariable %bufptr Uniform\n"
2123                         "%outdata    = OpVariable %bufptr Uniform\n"
2124
2125                         "%id        = OpVariable %uvec3ptr Input\n"
2126                         "%zero      = OpConstant %i64 0\n"
2127
2128                         "%main      = OpFunction %void None %voidf\n"
2129                         "%label     = OpLabel\n"
2130                         "%idval     = OpLoad %uvec3 %id\n"
2131                         "%x         = OpCompositeExtract %u32 %idval 0\n"
2132                         "%inloc1    = OpAccessChain %i64ptr %indata1 %zero %x\n"
2133                         "%inval1    = OpLoad %i64 %inloc1\n"
2134                         "%inloc2    = OpAccessChain %i64ptr %indata2 %zero %x\n"
2135                         "%inval2    = OpLoad %i64 %inloc2\n"
2136                         "%rem       = OpSMod %i64 %inval1 %inval2\n"
2137                         "%outloc    = OpAccessChain %i64ptr %outdata %zero %x\n"
2138                         "             OpStore %outloc %rem\n"
2139                         "             OpReturn\n"
2140                         "             OpFunctionEnd\n";
2141
2142                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts1)));
2143                 spec.inputs.push_back   (BufferSp(new Int64Buffer(inputInts2)));
2144                 spec.outputs.push_back  (BufferSp(new Int64Buffer(outputInts)));
2145                 spec.numWorkGroups              = IVec3(numElements, 1, 1);
2146                 spec.failResult                 = params.failResult;
2147                 spec.failMessage                = params.failMessage;
2148
2149                 spec.requestedVulkanFeatures.coreFeatures.shaderInt64 = VK_TRUE;
2150
2151                 group->addChild(new SpvAsmComputeShaderCase(testCtx, params.name, "", spec));
2152         }
2153
2154         return group.release();
2155 }
2156
2157 // Copy contents in the input buffer to the output buffer.
2158 tcu::TestCaseGroup* createOpCopyMemoryGroup (tcu::TestContext& testCtx)
2159 {
2160         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopymemory", "Test the OpCopyMemory instruction"));
2161         de::Random                                              rnd                             (deStringHash(group->getName()));
2162         const int                                               numElements             = 100;
2163
2164         // 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.
2165         ComputeShaderSpec                               spec1;
2166         vector<Vec4>                                    inputFloats1    (numElements);
2167         vector<Vec4>                                    outputFloats1   (numElements);
2168
2169         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats1[0], numElements * 4);
2170
2171         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2172         floorAll(inputFloats1);
2173
2174         for (size_t ndx = 0; ndx < numElements; ++ndx)
2175                 outputFloats1[ndx] = inputFloats1[ndx] + Vec4(0.f, 0.5f, 1.5f, 2.5f);
2176
2177         spec1.assembly =
2178                 string(getComputeAsmShaderPreamble()) +
2179
2180                 "OpName %main           \"main\"\n"
2181                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2182
2183                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2184                 "OpDecorate %vec4arr ArrayStride 16\n"
2185
2186                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2187
2188                 "%vec4       = OpTypeVector %f32 4\n"
2189                 "%vec4ptr_u  = OpTypePointer Uniform %vec4\n"
2190                 "%vec4ptr_f  = OpTypePointer Function %vec4\n"
2191                 "%vec4arr    = OpTypeRuntimeArray %vec4\n"
2192                 "%buf        = OpTypeStruct %vec4arr\n"
2193                 "%bufptr     = OpTypePointer Uniform %buf\n"
2194                 "%indata     = OpVariable %bufptr Uniform\n"
2195                 "%outdata    = OpVariable %bufptr Uniform\n"
2196
2197                 "%id         = OpVariable %uvec3ptr Input\n"
2198                 "%zero       = OpConstant %i32 0\n"
2199                 "%c_f_0      = OpConstant %f32 0.\n"
2200                 "%c_f_0_5    = OpConstant %f32 0.5\n"
2201                 "%c_f_1_5    = OpConstant %f32 1.5\n"
2202                 "%c_f_2_5    = OpConstant %f32 2.5\n"
2203                 "%c_vec4     = OpConstantComposite %vec4 %c_f_0 %c_f_0_5 %c_f_1_5 %c_f_2_5\n"
2204
2205                 "%main       = OpFunction %void None %voidf\n"
2206                 "%label      = OpLabel\n"
2207                 "%v_vec4     = OpVariable %vec4ptr_f Function\n"
2208                 "%idval      = OpLoad %uvec3 %id\n"
2209                 "%x          = OpCompositeExtract %u32 %idval 0\n"
2210                 "%inloc      = OpAccessChain %vec4ptr_u %indata %zero %x\n"
2211                 "%outloc     = OpAccessChain %vec4ptr_u %outdata %zero %x\n"
2212                 "              OpCopyMemory %v_vec4 %inloc\n"
2213                 "%v_vec4_val = OpLoad %vec4 %v_vec4\n"
2214                 "%add        = OpFAdd %vec4 %v_vec4_val %c_vec4\n"
2215                 "              OpStore %outloc %add\n"
2216                 "              OpReturn\n"
2217                 "              OpFunctionEnd\n";
2218
2219         spec1.inputs.push_back(BufferSp(new Vec4Buffer(inputFloats1)));
2220         spec1.outputs.push_back(BufferSp(new Vec4Buffer(outputFloats1)));
2221         spec1.numWorkGroups = IVec3(numElements, 1, 1);
2222
2223         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector", "OpCopyMemory elements of vector type", spec1));
2224
2225         // The following case copies a float[100] variable from the input buffer to the output buffer.
2226         ComputeShaderSpec                               spec2;
2227         vector<float>                                   inputFloats2    (numElements);
2228         vector<float>                                   outputFloats2   (numElements);
2229
2230         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats2[0], numElements);
2231
2232         for (size_t ndx = 0; ndx < numElements; ++ndx)
2233                 outputFloats2[ndx] = inputFloats2[ndx];
2234
2235         spec2.assembly =
2236                 string(getComputeAsmShaderPreamble()) +
2237
2238                 "OpName %main           \"main\"\n"
2239                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2240
2241                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2242                 "OpDecorate %f32arr100 ArrayStride 4\n"
2243
2244                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2245
2246                 "%hundred        = OpConstant %u32 100\n"
2247                 "%f32arr100      = OpTypeArray %f32 %hundred\n"
2248                 "%f32arr100ptr_f = OpTypePointer Function %f32arr100\n"
2249                 "%f32arr100ptr_u = OpTypePointer Uniform %f32arr100\n"
2250                 "%buf            = OpTypeStruct %f32arr100\n"
2251                 "%bufptr         = OpTypePointer Uniform %buf\n"
2252                 "%indata         = OpVariable %bufptr Uniform\n"
2253                 "%outdata        = OpVariable %bufptr Uniform\n"
2254
2255                 "%id             = OpVariable %uvec3ptr Input\n"
2256                 "%zero           = OpConstant %i32 0\n"
2257
2258                 "%main           = OpFunction %void None %voidf\n"
2259                 "%label          = OpLabel\n"
2260                 "%var            = OpVariable %f32arr100ptr_f Function\n"
2261                 "%inarr          = OpAccessChain %f32arr100ptr_u %indata %zero\n"
2262                 "%outarr         = OpAccessChain %f32arr100ptr_u %outdata %zero\n"
2263                 "                  OpCopyMemory %var %inarr\n"
2264                 "                  OpCopyMemory %outarr %var\n"
2265                 "                  OpReturn\n"
2266                 "                  OpFunctionEnd\n";
2267
2268         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2269         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
2270         spec2.numWorkGroups = IVec3(1, 1, 1);
2271
2272         group->addChild(new SpvAsmComputeShaderCase(testCtx, "array", "OpCopyMemory elements of array type", spec2));
2273
2274         // The following case copies a struct{vec4, vec4, vec4, vec4} variable from the input buffer to the output buffer.
2275         ComputeShaderSpec                               spec3;
2276         vector<float>                                   inputFloats3    (16);
2277         vector<float>                                   outputFloats3   (16);
2278
2279         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats3[0], 16);
2280
2281         for (size_t ndx = 0; ndx < 16; ++ndx)
2282                 outputFloats3[ndx] = inputFloats3[ndx];
2283
2284         spec3.assembly =
2285                 string(getComputeAsmShaderPreamble()) +
2286
2287                 "OpName %main           \"main\"\n"
2288                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2289
2290                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2291                 //"OpMemberDecorate %buf 0 Offset 0\n"  - exists in getComputeAsmInputOutputBufferTraits
2292                 "OpMemberDecorate %buf 1 Offset 16\n"
2293                 "OpMemberDecorate %buf 2 Offset 32\n"
2294                 "OpMemberDecorate %buf 3 Offset 48\n"
2295
2296                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2297
2298                 "%vec4      = OpTypeVector %f32 4\n"
2299                 "%buf       = OpTypeStruct %vec4 %vec4 %vec4 %vec4\n"
2300                 "%bufptr    = OpTypePointer Uniform %buf\n"
2301                 "%indata    = OpVariable %bufptr Uniform\n"
2302                 "%outdata   = OpVariable %bufptr Uniform\n"
2303                 "%vec4stptr = OpTypePointer Function %buf\n"
2304
2305                 "%id        = OpVariable %uvec3ptr Input\n"
2306                 "%zero      = OpConstant %i32 0\n"
2307
2308                 "%main      = OpFunction %void None %voidf\n"
2309                 "%label     = OpLabel\n"
2310                 "%var       = OpVariable %vec4stptr Function\n"
2311                 "             OpCopyMemory %var %indata\n"
2312                 "             OpCopyMemory %outdata %var\n"
2313                 "             OpReturn\n"
2314                 "             OpFunctionEnd\n";
2315
2316         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2317         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
2318         spec3.numWorkGroups = IVec3(1, 1, 1);
2319
2320         group->addChild(new SpvAsmComputeShaderCase(testCtx, "struct", "OpCopyMemory elements of struct type", spec3));
2321
2322         // The following case negates multiple float variables from the input buffer and stores the results to the output buffer.
2323         ComputeShaderSpec                               spec4;
2324         vector<float>                                   inputFloats4    (numElements);
2325         vector<float>                                   outputFloats4   (numElements);
2326
2327         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats4[0], numElements);
2328
2329         for (size_t ndx = 0; ndx < numElements; ++ndx)
2330                 outputFloats4[ndx] = -inputFloats4[ndx];
2331
2332         spec4.assembly =
2333                 string(getComputeAsmShaderPreamble()) +
2334
2335                 "OpName %main           \"main\"\n"
2336                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2337
2338                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2339
2340                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
2341
2342                 "%f32ptr_f  = OpTypePointer Function %f32\n"
2343                 "%id        = OpVariable %uvec3ptr Input\n"
2344                 "%zero      = OpConstant %i32 0\n"
2345
2346                 "%main      = OpFunction %void None %voidf\n"
2347                 "%label     = OpLabel\n"
2348                 "%var       = OpVariable %f32ptr_f Function\n"
2349                 "%idval     = OpLoad %uvec3 %id\n"
2350                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2351                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
2352                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
2353                 "             OpCopyMemory %var %inloc\n"
2354                 "%val       = OpLoad %f32 %var\n"
2355                 "%neg       = OpFNegate %f32 %val\n"
2356                 "             OpStore %outloc %neg\n"
2357                 "             OpReturn\n"
2358                 "             OpFunctionEnd\n";
2359
2360         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2361         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
2362         spec4.numWorkGroups = IVec3(numElements, 1, 1);
2363
2364         group->addChild(new SpvAsmComputeShaderCase(testCtx, "float", "OpCopyMemory elements of float type", spec4));
2365
2366         return group.release();
2367 }
2368
2369 tcu::TestCaseGroup* createOpCopyObjectGroup (tcu::TestContext& testCtx)
2370 {
2371         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opcopyobject", "Test the OpCopyObject instruction"));
2372         ComputeShaderSpec                               spec;
2373         de::Random                                              rnd                             (deStringHash(group->getName()));
2374         const int                                               numElements             = 100;
2375         vector<float>                                   inputFloats             (numElements, 0);
2376         vector<float>                                   outputFloats    (numElements, 0);
2377
2378         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
2379
2380         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2381         floorAll(inputFloats);
2382
2383         for (size_t ndx = 0; ndx < numElements; ++ndx)
2384                 outputFloats[ndx] = inputFloats[ndx] + 7.5f;
2385
2386         spec.assembly =
2387                 string(getComputeAsmShaderPreamble()) +
2388
2389                 "OpName %main           \"main\"\n"
2390                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2391
2392                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2393
2394                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2395
2396                 "%fmat     = OpTypeMatrix %fvec3 3\n"
2397                 "%three    = OpConstant %u32 3\n"
2398                 "%farr     = OpTypeArray %f32 %three\n"
2399                 "%fst      = OpTypeStruct %f32 %f32\n"
2400
2401                 + string(getComputeAsmInputOutputBuffer()) +
2402
2403                 "%id            = OpVariable %uvec3ptr Input\n"
2404                 "%zero          = OpConstant %i32 0\n"
2405                 "%c_f           = OpConstant %f32 1.5\n"
2406                 "%c_fvec3       = OpConstantComposite %fvec3 %c_f %c_f %c_f\n"
2407                 "%c_fmat        = OpConstantComposite %fmat %c_fvec3 %c_fvec3 %c_fvec3\n"
2408                 "%c_farr        = OpConstantComposite %farr %c_f %c_f %c_f\n"
2409                 "%c_fst         = OpConstantComposite %fst %c_f %c_f\n"
2410
2411                 "%main          = OpFunction %void None %voidf\n"
2412                 "%label         = OpLabel\n"
2413                 "%c_f_copy      = OpCopyObject %f32   %c_f\n"
2414                 "%c_fvec3_copy  = OpCopyObject %fvec3 %c_fvec3\n"
2415                 "%c_fmat_copy   = OpCopyObject %fmat  %c_fmat\n"
2416                 "%c_farr_copy   = OpCopyObject %farr  %c_farr\n"
2417                 "%c_fst_copy    = OpCopyObject %fst   %c_fst\n"
2418                 "%fvec3_elem    = OpCompositeExtract %f32 %c_fvec3_copy 0\n"
2419                 "%fmat_elem     = OpCompositeExtract %f32 %c_fmat_copy 1 2\n"
2420                 "%farr_elem     = OpCompositeExtract %f32 %c_farr_copy 2\n"
2421                 "%fst_elem      = OpCompositeExtract %f32 %c_fst_copy 1\n"
2422                 // Add up. 1.5 * 5 = 7.5.
2423                 "%add1          = OpFAdd %f32 %c_f_copy %fvec3_elem\n"
2424                 "%add2          = OpFAdd %f32 %add1     %fmat_elem\n"
2425                 "%add3          = OpFAdd %f32 %add2     %farr_elem\n"
2426                 "%add4          = OpFAdd %f32 %add3     %fst_elem\n"
2427
2428                 "%idval         = OpLoad %uvec3 %id\n"
2429                 "%x             = OpCompositeExtract %u32 %idval 0\n"
2430                 "%inloc         = OpAccessChain %f32ptr %indata %zero %x\n"
2431                 "%outloc        = OpAccessChain %f32ptr %outdata %zero %x\n"
2432                 "%inval         = OpLoad %f32 %inloc\n"
2433                 "%add           = OpFAdd %f32 %add4 %inval\n"
2434                 "                 OpStore %outloc %add\n"
2435                 "                 OpReturn\n"
2436                 "                 OpFunctionEnd\n";
2437         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
2438         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2439         spec.numWorkGroups = IVec3(numElements, 1, 1);
2440
2441         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "OpCopyObject on different types", spec));
2442
2443         return group.release();
2444 }
2445 // Assembly code used for testing OpUnreachable is based on GLSL source code:
2446 //
2447 // #version 430
2448 //
2449 // layout(std140, set = 0, binding = 0) readonly buffer Input {
2450 //   float elements[];
2451 // } input_data;
2452 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
2453 //   float elements[];
2454 // } output_data;
2455 //
2456 // void not_called_func() {
2457 //   // place OpUnreachable here
2458 // }
2459 //
2460 // uint modulo4(uint val) {
2461 //   switch (val % uint(4)) {
2462 //     case 0:  return 3;
2463 //     case 1:  return 2;
2464 //     case 2:  return 1;
2465 //     case 3:  return 0;
2466 //     default: return 100; // place OpUnreachable here
2467 //   }
2468 // }
2469 //
2470 // uint const5() {
2471 //   return 5;
2472 //   // place OpUnreachable here
2473 // }
2474 //
2475 // void main() {
2476 //   uint x = gl_GlobalInvocationID.x;
2477 //   if (const5() > modulo4(1000)) {
2478 //     output_data.elements[x] = -input_data.elements[x];
2479 //   } else {
2480 //     // place OpUnreachable here
2481 //     output_data.elements[x] = input_data.elements[x];
2482 //   }
2483 // }
2484
2485 tcu::TestCaseGroup* createOpUnreachableGroup (tcu::TestContext& testCtx)
2486 {
2487         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opunreachable", "Test the OpUnreachable instruction"));
2488         ComputeShaderSpec                               spec;
2489         de::Random                                              rnd                             (deStringHash(group->getName()));
2490         const int                                               numElements             = 100;
2491         vector<float>                                   positiveFloats  (numElements, 0);
2492         vector<float>                                   negativeFloats  (numElements, 0);
2493
2494         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
2495
2496         for (size_t ndx = 0; ndx < numElements; ++ndx)
2497                 negativeFloats[ndx] = -positiveFloats[ndx];
2498
2499         spec.assembly =
2500                 string(getComputeAsmShaderPreamble()) +
2501
2502                 "OpSource GLSL 430\n"
2503                 "OpName %main            \"main\"\n"
2504                 "OpName %func_not_called_func \"not_called_func(\"\n"
2505                 "OpName %func_modulo4         \"modulo4(u1;\"\n"
2506                 "OpName %func_const5          \"const5(\"\n"
2507                 "OpName %id                   \"gl_GlobalInvocationID\"\n"
2508
2509                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2510
2511                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2512
2513                 "%u32ptr    = OpTypePointer Function %u32\n"
2514                 "%uintfuint = OpTypeFunction %u32 %u32ptr\n"
2515                 "%unitf     = OpTypeFunction %u32\n"
2516
2517                 "%id        = OpVariable %uvec3ptr Input\n"
2518                 "%zero      = OpConstant %u32 0\n"
2519                 "%one       = OpConstant %u32 1\n"
2520                 "%two       = OpConstant %u32 2\n"
2521                 "%three     = OpConstant %u32 3\n"
2522                 "%four      = OpConstant %u32 4\n"
2523                 "%five      = OpConstant %u32 5\n"
2524                 "%hundred   = OpConstant %u32 100\n"
2525                 "%thousand  = OpConstant %u32 1000\n"
2526
2527                 + string(getComputeAsmInputOutputBuffer()) +
2528
2529                 // Main()
2530                 "%main   = OpFunction %void None %voidf\n"
2531                 "%main_entry  = OpLabel\n"
2532                 "%v_thousand  = OpVariable %u32ptr Function %thousand\n"
2533                 "%idval       = OpLoad %uvec3 %id\n"
2534                 "%x           = OpCompositeExtract %u32 %idval 0\n"
2535                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
2536                 "%inval       = OpLoad %f32 %inloc\n"
2537                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
2538                 "%ret_const5  = OpFunctionCall %u32 %func_const5\n"
2539                 "%ret_modulo4 = OpFunctionCall %u32 %func_modulo4 %v_thousand\n"
2540                 "%cmp_gt      = OpUGreaterThan %bool %ret_const5 %ret_modulo4\n"
2541                 "               OpSelectionMerge %if_end None\n"
2542                 "               OpBranchConditional %cmp_gt %if_true %if_false\n"
2543                 "%if_true     = OpLabel\n"
2544                 "%negate      = OpFNegate %f32 %inval\n"
2545                 "               OpStore %outloc %negate\n"
2546                 "               OpBranch %if_end\n"
2547                 "%if_false    = OpLabel\n"
2548                 "               OpUnreachable\n" // Unreachable else branch for if statement
2549                 "%if_end      = OpLabel\n"
2550                 "               OpReturn\n"
2551                 "               OpFunctionEnd\n"
2552
2553                 // not_called_function()
2554                 "%func_not_called_func  = OpFunction %void None %voidf\n"
2555                 "%not_called_func_entry = OpLabel\n"
2556                 "                         OpUnreachable\n" // Unreachable entry block in not called static function
2557                 "                         OpFunctionEnd\n"
2558
2559                 // modulo4()
2560                 "%func_modulo4  = OpFunction %u32 None %uintfuint\n"
2561                 "%valptr        = OpFunctionParameter %u32ptr\n"
2562                 "%modulo4_entry = OpLabel\n"
2563                 "%val           = OpLoad %u32 %valptr\n"
2564                 "%modulo        = OpUMod %u32 %val %four\n"
2565                 "                 OpSelectionMerge %switch_merge None\n"
2566                 "                 OpSwitch %modulo %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
2567                 "%case0         = OpLabel\n"
2568                 "                 OpReturnValue %three\n"
2569                 "%case1         = OpLabel\n"
2570                 "                 OpReturnValue %two\n"
2571                 "%case2         = OpLabel\n"
2572                 "                 OpReturnValue %one\n"
2573                 "%case3         = OpLabel\n"
2574                 "                 OpReturnValue %zero\n"
2575                 "%default       = OpLabel\n"
2576                 "                 OpUnreachable\n" // Unreachable default case for switch statement
2577                 "%switch_merge  = OpLabel\n"
2578                 "                 OpUnreachable\n" // Unreachable merge block for switch statement
2579                 "                 OpFunctionEnd\n"
2580
2581                 // const5()
2582                 "%func_const5  = OpFunction %u32 None %unitf\n"
2583                 "%const5_entry = OpLabel\n"
2584                 "                OpReturnValue %five\n"
2585                 "%unreachable  = OpLabel\n"
2586                 "                OpUnreachable\n" // Unreachable block in function
2587                 "                OpFunctionEnd\n";
2588         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
2589         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
2590         spec.numWorkGroups = IVec3(numElements, 1, 1);
2591
2592         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "OpUnreachable appearing at different places", spec));
2593
2594         return group.release();
2595 }
2596
2597 // Assembly code used for testing decoration group is based on GLSL source code:
2598 //
2599 // #version 430
2600 //
2601 // layout(std140, set = 0, binding = 0) readonly buffer Input0 {
2602 //   float elements[];
2603 // } input_data0;
2604 // layout(std140, set = 0, binding = 1) readonly buffer Input1 {
2605 //   float elements[];
2606 // } input_data1;
2607 // layout(std140, set = 0, binding = 2) readonly buffer Input2 {
2608 //   float elements[];
2609 // } input_data2;
2610 // layout(std140, set = 0, binding = 3) readonly buffer Input3 {
2611 //   float elements[];
2612 // } input_data3;
2613 // layout(std140, set = 0, binding = 4) readonly buffer Input4 {
2614 //   float elements[];
2615 // } input_data4;
2616 // layout(std140, set = 0, binding = 5) writeonly buffer Output {
2617 //   float elements[];
2618 // } output_data;
2619 //
2620 // void main() {
2621 //   uint x = gl_GlobalInvocationID.x;
2622 //   output_data.elements[x] = input_data0.elements[x] + input_data1.elements[x] + input_data2.elements[x] + input_data3.elements[x] + input_data4.elements[x];
2623 // }
2624 tcu::TestCaseGroup* createDecorationGroupGroup (tcu::TestContext& testCtx)
2625 {
2626         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "decoration_group", "Test the OpDecorationGroup & OpGroupDecorate instruction"));
2627         ComputeShaderSpec                               spec;
2628         de::Random                                              rnd                             (deStringHash(group->getName()));
2629         const int                                               numElements             = 100;
2630         vector<float>                                   inputFloats0    (numElements, 0);
2631         vector<float>                                   inputFloats1    (numElements, 0);
2632         vector<float>                                   inputFloats2    (numElements, 0);
2633         vector<float>                                   inputFloats3    (numElements, 0);
2634         vector<float>                                   inputFloats4    (numElements, 0);
2635         vector<float>                                   outputFloats    (numElements, 0);
2636
2637         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats0[0], numElements);
2638         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats1[0], numElements);
2639         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats2[0], numElements);
2640         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats3[0], numElements);
2641         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats4[0], numElements);
2642
2643         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
2644         floorAll(inputFloats0);
2645         floorAll(inputFloats1);
2646         floorAll(inputFloats2);
2647         floorAll(inputFloats3);
2648         floorAll(inputFloats4);
2649
2650         for (size_t ndx = 0; ndx < numElements; ++ndx)
2651                 outputFloats[ndx] = inputFloats0[ndx] + inputFloats1[ndx] + inputFloats2[ndx] + inputFloats3[ndx] + inputFloats4[ndx];
2652
2653         spec.assembly =
2654                 string(getComputeAsmShaderPreamble()) +
2655
2656                 "OpSource GLSL 430\n"
2657                 "OpName %main \"main\"\n"
2658                 "OpName %id \"gl_GlobalInvocationID\"\n"
2659
2660                 // Not using group decoration on variable.
2661                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2662                 // Not using group decoration on type.
2663                 "OpDecorate %f32arr ArrayStride 4\n"
2664
2665                 "OpDecorate %groups BufferBlock\n"
2666                 "OpDecorate %groupm Offset 0\n"
2667                 "%groups = OpDecorationGroup\n"
2668                 "%groupm = OpDecorationGroup\n"
2669
2670                 // Group decoration on multiple structs.
2671                 "OpGroupDecorate %groups %outbuf %inbuf0 %inbuf1 %inbuf2 %inbuf3 %inbuf4\n"
2672                 // Group decoration on multiple struct members.
2673                 "OpGroupMemberDecorate %groupm %outbuf 0 %inbuf0 0 %inbuf1 0 %inbuf2 0 %inbuf3 0 %inbuf4 0\n"
2674
2675                 "OpDecorate %group1 DescriptorSet 0\n"
2676                 "OpDecorate %group3 DescriptorSet 0\n"
2677                 "OpDecorate %group3 NonWritable\n"
2678                 "OpDecorate %group3 Restrict\n"
2679                 "%group0 = OpDecorationGroup\n"
2680                 "%group1 = OpDecorationGroup\n"
2681                 "%group3 = OpDecorationGroup\n"
2682
2683                 // Applying the same decoration group multiple times.
2684                 "OpGroupDecorate %group1 %outdata\n"
2685                 "OpGroupDecorate %group1 %outdata\n"
2686                 "OpGroupDecorate %group1 %outdata\n"
2687                 "OpDecorate %outdata DescriptorSet 0\n"
2688                 "OpDecorate %outdata Binding 5\n"
2689                 // Applying decoration group containing nothing.
2690                 "OpGroupDecorate %group0 %indata0\n"
2691                 "OpDecorate %indata0 DescriptorSet 0\n"
2692                 "OpDecorate %indata0 Binding 0\n"
2693                 // Applying decoration group containing one decoration.
2694                 "OpGroupDecorate %group1 %indata1\n"
2695                 "OpDecorate %indata1 Binding 1\n"
2696                 // Applying decoration group containing multiple decorations.
2697                 "OpGroupDecorate %group3 %indata2 %indata3\n"
2698                 "OpDecorate %indata2 Binding 2\n"
2699                 "OpDecorate %indata3 Binding 3\n"
2700                 // Applying multiple decoration groups (with overlapping).
2701                 "OpGroupDecorate %group0 %indata4\n"
2702                 "OpGroupDecorate %group1 %indata4\n"
2703                 "OpGroupDecorate %group3 %indata4\n"
2704                 "OpDecorate %indata4 Binding 4\n"
2705
2706                 + string(getComputeAsmCommonTypes()) +
2707
2708                 "%id   = OpVariable %uvec3ptr Input\n"
2709                 "%zero = OpConstant %i32 0\n"
2710
2711                 "%outbuf    = OpTypeStruct %f32arr\n"
2712                 "%outbufptr = OpTypePointer Uniform %outbuf\n"
2713                 "%outdata   = OpVariable %outbufptr Uniform\n"
2714                 "%inbuf0    = OpTypeStruct %f32arr\n"
2715                 "%inbuf0ptr = OpTypePointer Uniform %inbuf0\n"
2716                 "%indata0   = OpVariable %inbuf0ptr Uniform\n"
2717                 "%inbuf1    = OpTypeStruct %f32arr\n"
2718                 "%inbuf1ptr = OpTypePointer Uniform %inbuf1\n"
2719                 "%indata1   = OpVariable %inbuf1ptr Uniform\n"
2720                 "%inbuf2    = OpTypeStruct %f32arr\n"
2721                 "%inbuf2ptr = OpTypePointer Uniform %inbuf2\n"
2722                 "%indata2   = OpVariable %inbuf2ptr Uniform\n"
2723                 "%inbuf3    = OpTypeStruct %f32arr\n"
2724                 "%inbuf3ptr = OpTypePointer Uniform %inbuf3\n"
2725                 "%indata3   = OpVariable %inbuf3ptr Uniform\n"
2726                 "%inbuf4    = OpTypeStruct %f32arr\n"
2727                 "%inbufptr  = OpTypePointer Uniform %inbuf4\n"
2728                 "%indata4   = OpVariable %inbufptr Uniform\n"
2729
2730                 "%main   = OpFunction %void None %voidf\n"
2731                 "%label  = OpLabel\n"
2732                 "%idval  = OpLoad %uvec3 %id\n"
2733                 "%x      = OpCompositeExtract %u32 %idval 0\n"
2734                 "%inloc0 = OpAccessChain %f32ptr %indata0 %zero %x\n"
2735                 "%inloc1 = OpAccessChain %f32ptr %indata1 %zero %x\n"
2736                 "%inloc2 = OpAccessChain %f32ptr %indata2 %zero %x\n"
2737                 "%inloc3 = OpAccessChain %f32ptr %indata3 %zero %x\n"
2738                 "%inloc4 = OpAccessChain %f32ptr %indata4 %zero %x\n"
2739                 "%outloc = OpAccessChain %f32ptr %outdata %zero %x\n"
2740                 "%inval0 = OpLoad %f32 %inloc0\n"
2741                 "%inval1 = OpLoad %f32 %inloc1\n"
2742                 "%inval2 = OpLoad %f32 %inloc2\n"
2743                 "%inval3 = OpLoad %f32 %inloc3\n"
2744                 "%inval4 = OpLoad %f32 %inloc4\n"
2745                 "%add0   = OpFAdd %f32 %inval0 %inval1\n"
2746                 "%add1   = OpFAdd %f32 %add0 %inval2\n"
2747                 "%add2   = OpFAdd %f32 %add1 %inval3\n"
2748                 "%add    = OpFAdd %f32 %add2 %inval4\n"
2749                 "          OpStore %outloc %add\n"
2750                 "          OpReturn\n"
2751                 "          OpFunctionEnd\n";
2752         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats0)));
2753         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats1)));
2754         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats2)));
2755         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats3)));
2756         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats4)));
2757         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
2758         spec.numWorkGroups = IVec3(numElements, 1, 1);
2759
2760         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "decoration group cases", spec));
2761
2762         return group.release();
2763 }
2764
2765 struct SpecConstantTwoIntCase
2766 {
2767         const char*             caseName;
2768         const char*             scDefinition0;
2769         const char*             scDefinition1;
2770         const char*             scResultType;
2771         const char*             scOperation;
2772         deInt32                 scActualValue0;
2773         deInt32                 scActualValue1;
2774         const char*             resultOperation;
2775         vector<deInt32> expectedOutput;
2776         deInt32                 scActualValueLength;
2777
2778                                         SpecConstantTwoIntCase (const char* name,
2779                                                                                         const char* definition0,
2780                                                                                         const char* definition1,
2781                                                                                         const char* resultType,
2782                                                                                         const char* operation,
2783                                                                                         deInt32 value0,
2784                                                                                         deInt32 value1,
2785                                                                                         const char* resultOp,
2786                                                                                         const vector<deInt32>& output,
2787                                                                                         const deInt32   valueLength = sizeof(deInt32))
2788                                                 : caseName                              (name)
2789                                                 , scDefinition0                 (definition0)
2790                                                 , scDefinition1                 (definition1)
2791                                                 , scResultType                  (resultType)
2792                                                 , scOperation                   (operation)
2793                                                 , scActualValue0                (value0)
2794                                                 , scActualValue1                (value1)
2795                                                 , resultOperation               (resultOp)
2796                                                 , expectedOutput                (output)
2797                                                 , scActualValueLength   (valueLength)
2798                                                 {}
2799 };
2800
2801 tcu::TestCaseGroup* createSpecConstantGroup (tcu::TestContext& testCtx)
2802 {
2803         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
2804         vector<SpecConstantTwoIntCase>  cases;
2805         de::Random                                              rnd                             (deStringHash(group->getName()));
2806         const int                                               numElements             = 100;
2807         const deInt32                                   p1AsFloat16             = 0x3c00; // +1(fp16) == 0 01111 0000000000 == 0011 1100 0000 0000
2808         vector<deInt32>                                 inputInts               (numElements, 0);
2809         vector<deInt32>                                 outputInts1             (numElements, 0);
2810         vector<deInt32>                                 outputInts2             (numElements, 0);
2811         vector<deInt32>                                 outputInts3             (numElements, 0);
2812         vector<deInt32>                                 outputInts4             (numElements, 0);
2813         const StringTemplate                    shaderTemplate  (
2814                 "${CAPABILITIES:opt}"
2815                 + string(getComputeAsmShaderPreamble()) +
2816
2817                 "OpName %main           \"main\"\n"
2818                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2819
2820                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2821                 "OpDecorate %sc_0  SpecId 0\n"
2822                 "OpDecorate %sc_1  SpecId 1\n"
2823                 "OpDecorate %i32arr ArrayStride 4\n"
2824
2825                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2826
2827                 "${OPTYPE_DEFINITIONS:opt}"
2828                 "%buf     = OpTypeStruct %i32arr\n"
2829                 "%bufptr  = OpTypePointer Uniform %buf\n"
2830                 "%indata    = OpVariable %bufptr Uniform\n"
2831                 "%outdata   = OpVariable %bufptr Uniform\n"
2832
2833                 "%id        = OpVariable %uvec3ptr Input\n"
2834                 "%zero      = OpConstant %i32 0\n"
2835
2836                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
2837                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
2838                 "%sc_final  = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n"
2839
2840                 "%main      = OpFunction %void None %voidf\n"
2841                 "%label     = OpLabel\n"
2842                 "${TYPE_CONVERT:opt}"
2843                 "%idval     = OpLoad %uvec3 %id\n"
2844                 "%x         = OpCompositeExtract %u32 %idval 0\n"
2845                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
2846                 "%inval     = OpLoad %i32 %inloc\n"
2847                 "%final     = ${GEN_RESULT}\n"
2848                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
2849                 "             OpStore %outloc %final\n"
2850                 "             OpReturn\n"
2851                 "             OpFunctionEnd\n");
2852
2853         fillRandomScalars(rnd, -65536, 65536, &inputInts[0], numElements);
2854
2855         for (size_t ndx = 0; ndx < numElements; ++ndx)
2856         {
2857                 outputInts1[ndx] = inputInts[ndx] + 42;
2858                 outputInts2[ndx] = inputInts[ndx];
2859                 outputInts3[ndx] = inputInts[ndx] - 11200;
2860                 outputInts4[ndx] = inputInts[ndx] + 1;
2861         }
2862
2863         const char addScToInput[]               = "OpIAdd %i32 %inval %sc_final";
2864         const char addSc32ToInput[]             = "OpIAdd %i32 %inval %sc_final32";
2865         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_final %inval %zero";
2866         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_final %zero %inval";
2867
2868         cases.push_back(SpecConstantTwoIntCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                     62,             -20,    addScToInput,           outputInts1));
2869         cases.push_back(SpecConstantTwoIntCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                     100,    58,             addScToInput,           outputInts1));
2870         cases.push_back(SpecConstantTwoIntCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                     -2,             -21,    addScToInput,           outputInts1));
2871         cases.push_back(SpecConstantTwoIntCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                     -126,   -3,             addScToInput,           outputInts1));
2872         cases.push_back(SpecConstantTwoIntCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                     126,    3,              addScToInput,           outputInts1));
2873         cases.push_back(SpecConstantTwoIntCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2874         cases.push_back(SpecConstantTwoIntCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                     7,              3,              addScToInput,           outputInts4));
2875         cases.push_back(SpecConstantTwoIntCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                     342,    50,             addScToInput,           outputInts1));
2876         cases.push_back(SpecConstantTwoIntCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                     42,             63,             addScToInput,           outputInts1));
2877         cases.push_back(SpecConstantTwoIntCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                     34,             8,              addScToInput,           outputInts1));
2878         cases.push_back(SpecConstantTwoIntCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                     18,             56,             addScToInput,           outputInts1));
2879         cases.push_back(SpecConstantTwoIntCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2880         cases.push_back(SpecConstantTwoIntCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                     168,    2,              addScToInput,           outputInts1));
2881         cases.push_back(SpecConstantTwoIntCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                     21,             1,              addScToInput,           outputInts1));
2882         cases.push_back(SpecConstantTwoIntCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                     -20,    -10,    selectTrueUsingSc,      outputInts2));
2883         cases.push_back(SpecConstantTwoIntCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                     10,             20,             selectTrueUsingSc,      outputInts2));
2884         cases.push_back(SpecConstantTwoIntCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2885         cases.push_back(SpecConstantTwoIntCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                     10,             5,              selectTrueUsingSc,      outputInts2));
2886         cases.push_back(SpecConstantTwoIntCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                     -10,    -10,    selectTrueUsingSc,      outputInts2));
2887         cases.push_back(SpecConstantTwoIntCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                     50,             100,    selectTrueUsingSc,      outputInts2));
2888         cases.push_back(SpecConstantTwoIntCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                     -1000,  50,             selectFalseUsingSc,     outputInts2));
2889         cases.push_back(SpecConstantTwoIntCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                     10,             10,             selectTrueUsingSc,      outputInts2));
2890         cases.push_back(SpecConstantTwoIntCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                     42,             24,             selectFalseUsingSc,     outputInts2));
2891         cases.push_back(SpecConstantTwoIntCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                     42,             24,             selectTrueUsingSc,      outputInts2));
2892         cases.push_back(SpecConstantTwoIntCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2893         cases.push_back(SpecConstantTwoIntCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2894         cases.push_back(SpecConstantTwoIntCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                     0,              1,              selectFalseUsingSc,     outputInts2));
2895         cases.push_back(SpecConstantTwoIntCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                     1,              0,              selectTrueUsingSc,      outputInts2));
2896         cases.push_back(SpecConstantTwoIntCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                           -42,    0,              addScToInput,           outputInts1));
2897         cases.push_back(SpecConstantTwoIntCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                           -43,    0,              addScToInput,           outputInts1));
2898         cases.push_back(SpecConstantTwoIntCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                           1,              0,              selectFalseUsingSc,     outputInts2));
2899         cases.push_back(SpecConstantTwoIntCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %zero",       1,              42,             addScToInput,           outputInts1));
2900         cases.push_back(SpecConstantTwoIntCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                           -11200, 0,              addSc32ToInput,         outputInts3));
2901         // -969998336 stored as 32-bit two's complement is the binary representation of -11200 as IEEE-754 Float
2902         cases.push_back(SpecConstantTwoIntCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                           -969998336, 0,  addSc32ToInput,         outputInts3));
2903         cases.push_back(SpecConstantTwoIntCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                           p1AsFloat16, 0, addSc32ToInput,         outputInts4, sizeof(deFloat16)));
2904
2905         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
2906         {
2907                 map<string, string>             specializations;
2908                 ComputeShaderSpec               spec;
2909
2910                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
2911                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
2912                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
2913                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
2914                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
2915
2916                 // Special SPIR-V code for SConvert-case
2917                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
2918                 {
2919                         spec.requestedVulkanFeatures.coreFeatures.shaderInt16   = VK_TRUE;
2920                         specializations["CAPABILITIES"]                                                 = "OpCapability Int16\n";                                                       // Adds 16-bit integer capability
2921                         specializations["OPTYPE_DEFINITIONS"]                                   = "%i16 = OpTypeInt 16 1\n";                                            // Adds 16-bit integer type
2922                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpSConvert %i32 %sc_final\n";          // Converts 16-bit integer to 32-bit integer
2923                 }
2924
2925                 // Special SPIR-V code for FConvert-case
2926                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
2927                 {
2928                         spec.requestedVulkanFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
2929                         specializations["CAPABILITIES"]                                                 = "OpCapability Float64\n";                                                     // Adds 64-bit float capability
2930                         specializations["OPTYPE_DEFINITIONS"]                                   = "%f64 = OpTypeFloat 64\n";                                            // Adds 64-bit float type
2931                         specializations["TYPE_CONVERT"]                                                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 64-bit float to 32-bit integer
2932                 }
2933
2934                 // Special SPIR-V code for FConvert-case for 16-bit floats
2935                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
2936                 {
2937                         spec.extensions.push_back("VK_KHR_shader_float16_int8");
2938                         spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
2939                         specializations["CAPABILITIES"]                 = "OpCapability Float16\n";                                                     // Adds 16-bit float capability
2940                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                                            // Adds 16-bit float type
2941                         specializations["TYPE_CONVERT"]                 = "%sc_final32 = OpConvertFToS %i32 %sc_final\n";       // Converts 16-bit float to 32-bit integer
2942                 }
2943
2944                 spec.assembly = shaderTemplate.specialize(specializations);
2945                 spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
2946                 spec.outputs.push_back(BufferSp(new Int32Buffer(cases[caseNdx].expectedOutput)));
2947                 spec.numWorkGroups = IVec3(numElements, 1, 1);
2948                 spec.specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
2949                 spec.specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
2950
2951                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].caseName, cases[caseNdx].caseName, spec));
2952         }
2953
2954         ComputeShaderSpec                               spec;
2955
2956         spec.assembly =
2957                 string(getComputeAsmShaderPreamble()) +
2958
2959                 "OpName %main           \"main\"\n"
2960                 "OpName %id             \"gl_GlobalInvocationID\"\n"
2961
2962                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
2963                 "OpDecorate %sc_0  SpecId 0\n"
2964                 "OpDecorate %sc_1  SpecId 1\n"
2965                 "OpDecorate %sc_2  SpecId 2\n"
2966                 "OpDecorate %i32arr ArrayStride 4\n"
2967
2968                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
2969
2970                 "%ivec3       = OpTypeVector %i32 3\n"
2971                 "%buf         = OpTypeStruct %i32arr\n"
2972                 "%bufptr      = OpTypePointer Uniform %buf\n"
2973                 "%indata      = OpVariable %bufptr Uniform\n"
2974                 "%outdata     = OpVariable %bufptr Uniform\n"
2975
2976                 "%id          = OpVariable %uvec3ptr Input\n"
2977                 "%zero        = OpConstant %i32 0\n"
2978                 "%ivec3_0     = OpConstantComposite %ivec3 %zero %zero %zero\n"
2979                 "%vec3_undef  = OpUndef %ivec3\n"
2980
2981                 "%sc_0        = OpSpecConstant %i32 0\n"
2982                 "%sc_1        = OpSpecConstant %i32 0\n"
2983                 "%sc_2        = OpSpecConstant %i32 0\n"
2984                 "%sc_vec3_0   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_0        %ivec3_0     0\n"                                                 // (sc_0, 0, 0)
2985                 "%sc_vec3_1   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_1        %ivec3_0     1\n"                                                 // (0, sc_1, 0)
2986                 "%sc_vec3_2   = OpSpecConstantOp %ivec3 CompositeInsert  %sc_2        %ivec3_0     2\n"                                                 // (0, 0, sc_2)
2987                 "%sc_vec3_0_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
2988                 "%sc_vec3_1_s = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
2989                 "%sc_vec3_2_s = OpSpecConstantOp %ivec3 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
2990                 "%sc_vec3_01  = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
2991                 "%sc_vec3_012 = OpSpecConstantOp %ivec3 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
2992                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
2993                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
2994                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
2995                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
2996                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n"                                                              // (sc_2 - sc_0) * sc_1
2997
2998                 "%main      = OpFunction %void None %voidf\n"
2999                 "%label     = OpLabel\n"
3000                 "%idval     = OpLoad %uvec3 %id\n"
3001                 "%x         = OpCompositeExtract %u32 %idval 0\n"
3002                 "%inloc     = OpAccessChain %i32ptr %indata %zero %x\n"
3003                 "%inval     = OpLoad %i32 %inloc\n"
3004                 "%final     = OpIAdd %i32 %inval %sc_final\n"
3005                 "%outloc    = OpAccessChain %i32ptr %outdata %zero %x\n"
3006                 "             OpStore %outloc %final\n"
3007                 "             OpReturn\n"
3008                 "             OpFunctionEnd\n";
3009         spec.inputs.push_back(BufferSp(new Int32Buffer(inputInts)));
3010         spec.outputs.push_back(BufferSp(new Int32Buffer(outputInts3)));
3011         spec.numWorkGroups = IVec3(numElements, 1, 1);
3012         spec.specConstants.append<deInt32>(123);
3013         spec.specConstants.append<deInt32>(56);
3014         spec.specConstants.append<deInt32>(-77);
3015
3016         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vector_related", "VectorShuffle, CompositeExtract, & CompositeInsert", spec));
3017
3018         return group.release();
3019 }
3020
3021 void createOpPhiVartypeTests (de::MovePtr<tcu::TestCaseGroup>& group, tcu::TestContext& testCtx)
3022 {
3023         ComputeShaderSpec       specInt;
3024         ComputeShaderSpec       specFloat;
3025         ComputeShaderSpec       specFloat16;
3026         ComputeShaderSpec       specVec3;
3027         ComputeShaderSpec       specMat4;
3028         ComputeShaderSpec       specArray;
3029         ComputeShaderSpec       specStruct;
3030         de::Random                      rnd                             (deStringHash(group->getName()));
3031         const int                       numElements             = 100;
3032         vector<float>           inputFloats             (numElements, 0);
3033         vector<float>           outputFloats    (numElements, 0);
3034         vector<deFloat16>       inputFloats16   (numElements, 0);
3035         vector<deFloat16>       outputFloats16  (numElements, 0);
3036
3037         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3038
3039         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3040         floorAll(inputFloats);
3041
3042         for (size_t ndx = 0; ndx < numElements; ++ndx)
3043         {
3044                 // Just check if the value is positive or not
3045                 outputFloats[ndx] = (inputFloats[ndx] > 0) ? 1.0f : -1.0f;
3046         }
3047
3048         for (size_t ndx = 0; ndx < numElements; ++ndx)
3049         {
3050                 inputFloats16[ndx] = tcu::Float16(inputFloats[ndx]).bits();
3051                 outputFloats16[ndx] = tcu::Float16(outputFloats[ndx]).bits();
3052         }
3053
3054         // All of the tests are of the form:
3055         //
3056         // testtype r
3057         //
3058         // if (inputdata > 0)
3059         //   r = 1
3060         // else
3061         //   r = -1
3062         //
3063         // return (float)r
3064
3065         specFloat.assembly =
3066                 string(getComputeAsmShaderPreamble()) +
3067
3068                 "OpSource GLSL 430\n"
3069                 "OpName %main \"main\"\n"
3070                 "OpName %id \"gl_GlobalInvocationID\"\n"
3071
3072                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3073
3074                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3075
3076                 "%id = OpVariable %uvec3ptr Input\n"
3077                 "%zero       = OpConstant %i32 0\n"
3078                 "%float_0    = OpConstant %f32 0.0\n"
3079                 "%float_1    = OpConstant %f32 1.0\n"
3080                 "%float_n1   = OpConstant %f32 -1.0\n"
3081
3082                 "%main     = OpFunction %void None %voidf\n"
3083                 "%entry    = OpLabel\n"
3084                 "%idval    = OpLoad %uvec3 %id\n"
3085                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3086                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3087                 "%inval    = OpLoad %f32 %inloc\n"
3088
3089                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3090                 "            OpSelectionMerge %cm None\n"
3091                 "            OpBranchConditional %comp %tb %fb\n"
3092                 "%tb       = OpLabel\n"
3093                 "            OpBranch %cm\n"
3094                 "%fb       = OpLabel\n"
3095                 "            OpBranch %cm\n"
3096                 "%cm       = OpLabel\n"
3097                 "%res      = OpPhi %f32 %float_1 %tb %float_n1 %fb\n"
3098
3099                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3100                 "            OpStore %outloc %res\n"
3101                 "            OpReturn\n"
3102
3103                 "            OpFunctionEnd\n";
3104         specFloat.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3105         specFloat.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3106         specFloat.numWorkGroups = IVec3(numElements, 1, 1);
3107
3108         specFloat16.assembly =
3109                 "OpCapability Shader\n"
3110                 "OpCapability StorageUniformBufferBlock16\n"
3111                 "OpExtension \"SPV_KHR_16bit_storage\"\n"
3112                 "OpMemoryModel Logical GLSL450\n"
3113                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3114                 "OpExecutionMode %main LocalSize 1 1 1\n"
3115
3116                 "OpSource GLSL 430\n"
3117                 "OpName %main \"main\"\n"
3118                 "OpName %id \"gl_GlobalInvocationID\"\n"
3119
3120                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3121
3122                 "OpDecorate %buf BufferBlock\n"
3123                 "OpDecorate %indata DescriptorSet 0\n"
3124                 "OpDecorate %indata Binding 0\n"
3125                 "OpDecorate %outdata DescriptorSet 0\n"
3126                 "OpDecorate %outdata Binding 1\n"
3127                 "OpDecorate %f16arr ArrayStride 2\n"
3128                 "OpMemberDecorate %buf 0 Offset 0\n"
3129
3130                 "%f16      = OpTypeFloat 16\n"
3131                 "%f16ptr   = OpTypePointer Uniform %f16\n"
3132                 "%f16arr   = OpTypeRuntimeArray %f16\n"
3133
3134                 + string(getComputeAsmCommonTypes()) +
3135
3136                 "%buf      = OpTypeStruct %f16arr\n"
3137                 "%bufptr   = OpTypePointer Uniform %buf\n"
3138                 "%indata   = OpVariable %bufptr Uniform\n"
3139                 "%outdata  = OpVariable %bufptr Uniform\n"
3140
3141                 "%id       = OpVariable %uvec3ptr Input\n"
3142                 "%zero     = OpConstant %i32 0\n"
3143                 "%float_0  = OpConstant %f16 0.0\n"
3144                 "%float_1  = OpConstant %f16 1.0\n"
3145                 "%float_n1 = OpConstant %f16 -1.0\n"
3146
3147                 "%main     = OpFunction %void None %voidf\n"
3148                 "%entry    = OpLabel\n"
3149                 "%idval    = OpLoad %uvec3 %id\n"
3150                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3151                 "%inloc    = OpAccessChain %f16ptr %indata %zero %x\n"
3152                 "%inval    = OpLoad %f16 %inloc\n"
3153
3154                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3155                 "            OpSelectionMerge %cm None\n"
3156                 "            OpBranchConditional %comp %tb %fb\n"
3157                 "%tb       = OpLabel\n"
3158                 "            OpBranch %cm\n"
3159                 "%fb       = OpLabel\n"
3160                 "            OpBranch %cm\n"
3161                 "%cm       = OpLabel\n"
3162                 "%res      = OpPhi %f16 %float_1 %tb %float_n1 %fb\n"
3163
3164                 "%outloc   = OpAccessChain %f16ptr %outdata %zero %x\n"
3165                 "            OpStore %outloc %res\n"
3166                 "            OpReturn\n"
3167
3168                 "            OpFunctionEnd\n";
3169         specFloat16.inputs.push_back(BufferSp(new Float16Buffer(inputFloats16)));
3170         specFloat16.outputs.push_back(BufferSp(new Float16Buffer(outputFloats16)));
3171         specFloat16.numWorkGroups = IVec3(numElements, 1, 1);
3172         specFloat16.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
3173         specFloat16.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
3174
3175         specMat4.assembly =
3176                 string(getComputeAsmShaderPreamble()) +
3177
3178                 "OpSource GLSL 430\n"
3179                 "OpName %main \"main\"\n"
3180                 "OpName %id \"gl_GlobalInvocationID\"\n"
3181
3182                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3183
3184                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3185
3186                 "%id = OpVariable %uvec3ptr Input\n"
3187                 "%v4f32      = OpTypeVector %f32 4\n"
3188                 "%mat4v4f32  = OpTypeMatrix %v4f32 4\n"
3189                 "%zero       = OpConstant %i32 0\n"
3190                 "%float_0    = OpConstant %f32 0.0\n"
3191                 "%float_1    = OpConstant %f32 1.0\n"
3192                 "%float_n1   = OpConstant %f32 -1.0\n"
3193                 "%m11        = OpConstantComposite %v4f32 %float_1 %float_0 %float_0 %float_0\n"
3194                 "%m12        = OpConstantComposite %v4f32 %float_0 %float_1 %float_0 %float_0\n"
3195                 "%m13        = OpConstantComposite %v4f32 %float_0 %float_0 %float_1 %float_0\n"
3196                 "%m14        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_1\n"
3197                 "%m1         = OpConstantComposite %mat4v4f32 %m11 %m12 %m13 %m14\n"
3198                 "%m21        = OpConstantComposite %v4f32 %float_n1 %float_0 %float_0 %float_0\n"
3199                 "%m22        = OpConstantComposite %v4f32 %float_0 %float_n1 %float_0 %float_0\n"
3200                 "%m23        = OpConstantComposite %v4f32 %float_0 %float_0 %float_n1 %float_0\n"
3201                 "%m24        = OpConstantComposite %v4f32 %float_0 %float_0 %float_0 %float_n1\n"
3202                 "%m2         = OpConstantComposite %mat4v4f32 %m21 %m22 %m23 %m24\n"
3203
3204                 "%main     = OpFunction %void None %voidf\n"
3205                 "%entry    = OpLabel\n"
3206                 "%idval    = OpLoad %uvec3 %id\n"
3207                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3208                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3209                 "%inval    = OpLoad %f32 %inloc\n"
3210
3211                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3212                 "            OpSelectionMerge %cm None\n"
3213                 "            OpBranchConditional %comp %tb %fb\n"
3214                 "%tb       = OpLabel\n"
3215                 "            OpBranch %cm\n"
3216                 "%fb       = OpLabel\n"
3217                 "            OpBranch %cm\n"
3218                 "%cm       = OpLabel\n"
3219                 "%mres     = OpPhi %mat4v4f32 %m1 %tb %m2 %fb\n"
3220                 "%res      = OpCompositeExtract %f32 %mres 2 2\n"
3221
3222                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3223                 "            OpStore %outloc %res\n"
3224                 "            OpReturn\n"
3225
3226                 "            OpFunctionEnd\n";
3227         specMat4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3228         specMat4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3229         specMat4.numWorkGroups = IVec3(numElements, 1, 1);
3230
3231         specVec3.assembly =
3232                 string(getComputeAsmShaderPreamble()) +
3233
3234                 "OpSource GLSL 430\n"
3235                 "OpName %main \"main\"\n"
3236                 "OpName %id \"gl_GlobalInvocationID\"\n"
3237
3238                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3239
3240                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3241
3242                 "%id = OpVariable %uvec3ptr Input\n"
3243                 "%zero       = OpConstant %i32 0\n"
3244                 "%float_0    = OpConstant %f32 0.0\n"
3245                 "%float_1    = OpConstant %f32 1.0\n"
3246                 "%float_n1   = OpConstant %f32 -1.0\n"
3247                 "%v1         = OpConstantComposite %fvec3 %float_1 %float_1 %float_1\n"
3248                 "%v2         = OpConstantComposite %fvec3 %float_n1 %float_n1 %float_n1\n"
3249
3250                 "%main     = OpFunction %void None %voidf\n"
3251                 "%entry    = OpLabel\n"
3252                 "%idval    = OpLoad %uvec3 %id\n"
3253                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3254                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3255                 "%inval    = OpLoad %f32 %inloc\n"
3256
3257                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3258                 "            OpSelectionMerge %cm None\n"
3259                 "            OpBranchConditional %comp %tb %fb\n"
3260                 "%tb       = OpLabel\n"
3261                 "            OpBranch %cm\n"
3262                 "%fb       = OpLabel\n"
3263                 "            OpBranch %cm\n"
3264                 "%cm       = OpLabel\n"
3265                 "%vres     = OpPhi %fvec3 %v1 %tb %v2 %fb\n"
3266                 "%res      = OpCompositeExtract %f32 %vres 2\n"
3267
3268                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3269                 "            OpStore %outloc %res\n"
3270                 "            OpReturn\n"
3271
3272                 "            OpFunctionEnd\n";
3273         specVec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3274         specVec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3275         specVec3.numWorkGroups = IVec3(numElements, 1, 1);
3276
3277         specInt.assembly =
3278                 string(getComputeAsmShaderPreamble()) +
3279
3280                 "OpSource GLSL 430\n"
3281                 "OpName %main \"main\"\n"
3282                 "OpName %id \"gl_GlobalInvocationID\"\n"
3283
3284                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3285
3286                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3287
3288                 "%id = OpVariable %uvec3ptr Input\n"
3289                 "%zero       = OpConstant %i32 0\n"
3290                 "%float_0    = OpConstant %f32 0.0\n"
3291                 "%i1         = OpConstant %i32 1\n"
3292                 "%i2         = OpConstant %i32 -1\n"
3293
3294                 "%main     = OpFunction %void None %voidf\n"
3295                 "%entry    = OpLabel\n"
3296                 "%idval    = OpLoad %uvec3 %id\n"
3297                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3298                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3299                 "%inval    = OpLoad %f32 %inloc\n"
3300
3301                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3302                 "            OpSelectionMerge %cm None\n"
3303                 "            OpBranchConditional %comp %tb %fb\n"
3304                 "%tb       = OpLabel\n"
3305                 "            OpBranch %cm\n"
3306                 "%fb       = OpLabel\n"
3307                 "            OpBranch %cm\n"
3308                 "%cm       = OpLabel\n"
3309                 "%ires     = OpPhi %i32 %i1 %tb %i2 %fb\n"
3310                 "%res      = OpConvertSToF %f32 %ires\n"
3311
3312                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3313                 "            OpStore %outloc %res\n"
3314                 "            OpReturn\n"
3315
3316                 "            OpFunctionEnd\n";
3317         specInt.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3318         specInt.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3319         specInt.numWorkGroups = IVec3(numElements, 1, 1);
3320
3321         specArray.assembly =
3322                 string(getComputeAsmShaderPreamble()) +
3323
3324                 "OpSource GLSL 430\n"
3325                 "OpName %main \"main\"\n"
3326                 "OpName %id \"gl_GlobalInvocationID\"\n"
3327
3328                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3329
3330                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3331
3332                 "%id = OpVariable %uvec3ptr Input\n"
3333                 "%zero       = OpConstant %i32 0\n"
3334                 "%u7         = OpConstant %u32 7\n"
3335                 "%float_0    = OpConstant %f32 0.0\n"
3336                 "%float_1    = OpConstant %f32 1.0\n"
3337                 "%float_n1   = OpConstant %f32 -1.0\n"
3338                 "%f32a7      = OpTypeArray %f32 %u7\n"
3339                 "%a1         = OpConstantComposite %f32a7 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1 %float_1\n"
3340                 "%a2         = OpConstantComposite %f32a7 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1 %float_n1\n"
3341                 "%main     = OpFunction %void None %voidf\n"
3342                 "%entry    = OpLabel\n"
3343                 "%idval    = OpLoad %uvec3 %id\n"
3344                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3345                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3346                 "%inval    = OpLoad %f32 %inloc\n"
3347
3348                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3349                 "            OpSelectionMerge %cm None\n"
3350                 "            OpBranchConditional %comp %tb %fb\n"
3351                 "%tb       = OpLabel\n"
3352                 "            OpBranch %cm\n"
3353                 "%fb       = OpLabel\n"
3354                 "            OpBranch %cm\n"
3355                 "%cm       = OpLabel\n"
3356                 "%ares     = OpPhi %f32a7 %a1 %tb %a2 %fb\n"
3357                 "%res      = OpCompositeExtract %f32 %ares 5\n"
3358
3359                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3360                 "            OpStore %outloc %res\n"
3361                 "            OpReturn\n"
3362
3363                 "            OpFunctionEnd\n";
3364         specArray.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3365         specArray.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3366         specArray.numWorkGroups = IVec3(numElements, 1, 1);
3367
3368         specStruct.assembly =
3369                 string(getComputeAsmShaderPreamble()) +
3370
3371                 "OpSource GLSL 430\n"
3372                 "OpName %main \"main\"\n"
3373                 "OpName %id \"gl_GlobalInvocationID\"\n"
3374
3375                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3376
3377                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3378
3379                 "%id = OpVariable %uvec3ptr Input\n"
3380                 "%zero       = OpConstant %i32 0\n"
3381                 "%float_0    = OpConstant %f32 0.0\n"
3382                 "%float_1    = OpConstant %f32 1.0\n"
3383                 "%float_n1   = OpConstant %f32 -1.0\n"
3384
3385                 "%v2f32      = OpTypeVector %f32 2\n"
3386                 "%Data2      = OpTypeStruct %f32 %v2f32\n"
3387                 "%Data       = OpTypeStruct %Data2 %f32\n"
3388
3389                 "%in1a       = OpConstantComposite %v2f32 %float_1 %float_1\n"
3390                 "%in1b       = OpConstantComposite %Data2 %float_1 %in1a\n"
3391                 "%s1         = OpConstantComposite %Data %in1b %float_1\n"
3392                 "%in2a       = OpConstantComposite %v2f32 %float_n1 %float_n1\n"
3393                 "%in2b       = OpConstantComposite %Data2 %float_n1 %in2a\n"
3394                 "%s2         = OpConstantComposite %Data %in2b %float_n1\n"
3395
3396                 "%main     = OpFunction %void None %voidf\n"
3397                 "%entry    = OpLabel\n"
3398                 "%idval    = OpLoad %uvec3 %id\n"
3399                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3400                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3401                 "%inval    = OpLoad %f32 %inloc\n"
3402
3403                 "%comp     = OpFOrdGreaterThan %bool %inval %float_0\n"
3404                 "            OpSelectionMerge %cm None\n"
3405                 "            OpBranchConditional %comp %tb %fb\n"
3406                 "%tb       = OpLabel\n"
3407                 "            OpBranch %cm\n"
3408                 "%fb       = OpLabel\n"
3409                 "            OpBranch %cm\n"
3410                 "%cm       = OpLabel\n"
3411                 "%sres     = OpPhi %Data %s1 %tb %s2 %fb\n"
3412                 "%res      = OpCompositeExtract %f32 %sres 0 0\n"
3413
3414                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3415                 "            OpStore %outloc %res\n"
3416                 "            OpReturn\n"
3417
3418                 "            OpFunctionEnd\n";
3419         specStruct.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3420         specStruct.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
3421         specStruct.numWorkGroups = IVec3(numElements, 1, 1);
3422
3423         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_int", "OpPhi with int variables", specInt));
3424         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float", "OpPhi with float variables", specFloat));
3425         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_float16", "OpPhi with 16bit float variables", specFloat16));
3426         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_vec3", "OpPhi with vec3 variables", specVec3));
3427         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_mat4", "OpPhi with mat4 variables", specMat4));
3428         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_array", "OpPhi with array variables", specArray));
3429         group->addChild(new SpvAsmComputeShaderCase(testCtx, "vartype_struct", "OpPhi with struct variables", specStruct));
3430 }
3431
3432 string generateConstantDefinitions (int count)
3433 {
3434         std::ostringstream      r;
3435         for (int i = 0; i < count; i++)
3436                 r << "%cf" << (i * 10 + 5) << " = OpConstant %f32 " <<(i * 10 + 5) << ".0\n";
3437         r << "\n";
3438         return r.str();
3439 }
3440
3441 string generateSwitchCases (int count)
3442 {
3443         std::ostringstream      r;
3444         for (int i = 0; i < count; i++)
3445                 r << " " << i << " %case" << i;
3446         r << "\n";
3447         return r.str();
3448 }
3449
3450 string generateSwitchTargets (int count)
3451 {
3452         std::ostringstream      r;
3453         for (int i = 0; i < count; i++)
3454                 r << "%case" << i << " = OpLabel\n            OpBranch %phi\n";
3455         r << "\n";
3456         return r.str();
3457 }
3458
3459 string generateOpPhiParams (int count)
3460 {
3461         std::ostringstream      r;
3462         for (int i = 0; i < count; i++)
3463                 r << " %cf" << (i * 10 + 5) << " %case" << i;
3464         r << "\n";
3465         return r.str();
3466 }
3467
3468 string generateIntWidth (int value)
3469 {
3470         std::ostringstream      r;
3471         r << value;
3472         return r.str();
3473 }
3474
3475 // Expand input string by injecting "ABC" between the input
3476 // string characters. The acc/add/treshold parameters are used
3477 // to skip some of the injections to make the result less
3478 // uniform (and a lot shorter).
3479 string expandOpPhiCase5 (const string& s, int &acc, int add, int treshold)
3480 {
3481         std::ostringstream      res;
3482         const char*                     p = s.c_str();
3483
3484         while (*p)
3485         {
3486                 res << *p;
3487                 acc += add;
3488                 if (acc > treshold)
3489                 {
3490                         acc -= treshold;
3491                         res << "ABC";
3492                 }
3493                 p++;
3494         }
3495         return res.str();
3496 }
3497
3498 // Calculate expected result based on the code string
3499 float calcOpPhiCase5 (float val, const string& s)
3500 {
3501         const char*             p               = s.c_str();
3502         float                   x[8];
3503         bool                    b[8];
3504         const float             tv[8]   = { 0.5f, 1.5f, 3.5f, 7.5f, 15.5f, 31.5f, 63.5f, 127.5f };
3505         const float             v               = deFloatAbs(val);
3506         float                   res             = 0;
3507         int                             depth   = -1;
3508         int                             skip    = 0;
3509
3510         for (int i = 7; i >= 0; --i)
3511                 x[i] = std::fmod((float)v, (float)(2 << i));
3512         for (int i = 7; i >= 0; --i)
3513                 b[i] = x[i] > tv[i];
3514
3515         while (*p)
3516         {
3517                 if (*p == 'A')
3518                 {
3519                         depth++;
3520                         if (skip == 0 && b[depth])
3521                         {
3522                                 res++;
3523                         }
3524                         else
3525                                 skip++;
3526                 }
3527                 if (*p == 'B')
3528                 {
3529                         if (skip)
3530                                 skip--;
3531                         if (b[depth] || skip)
3532                                 skip++;
3533                 }
3534                 if (*p == 'C')
3535                 {
3536                         depth--;
3537                         if (skip)
3538                                 skip--;
3539                 }
3540                 p++;
3541         }
3542         return res;
3543 }
3544
3545 // In the code string, the letters represent the following:
3546 //
3547 // A:
3548 //     if (certain bit is set)
3549 //     {
3550 //       result++;
3551 //
3552 // B:
3553 //     } else {
3554 //
3555 // C:
3556 //     }
3557 //
3558 // examples:
3559 // AABCBC leads to if(){r++;if(){r++;}else{}}else{}
3560 // ABABCC leads to if(){r++;}else{if(){r++;}else{}}
3561 // ABCABC leads to if(){r++;}else{}if(){r++;}else{}
3562 //
3563 // Code generation gets a bit complicated due to the else-branches,
3564 // which do not generate new values. Thus, the generator needs to
3565 // keep track of the previous variable change seen by the else
3566 // branch.
3567 string generateOpPhiCase5 (const string& s)
3568 {
3569         std::stack<int>                         idStack;
3570         std::stack<std::string>         value;
3571         std::stack<std::string>         valueLabel;
3572         std::stack<std::string>         mergeLeft;
3573         std::stack<std::string>         mergeRight;
3574         std::ostringstream                      res;
3575         const char*                                     p                       = s.c_str();
3576         int                                                     depth           = -1;
3577         int                                                     currId          = 0;
3578         int                                                     iter            = 0;
3579
3580         idStack.push(-1);
3581         value.push("%f32_0");
3582         valueLabel.push("%f32_0 %entry");
3583
3584         while (*p)
3585         {
3586                 if (*p == 'A')
3587                 {
3588                         depth++;
3589                         currId = iter;
3590                         idStack.push(currId);
3591                         res << "\tOpSelectionMerge %m" << currId << " None\n";
3592                         res << "\tOpBranchConditional %b" << depth << " %t" << currId << " %f" << currId << "\n";
3593                         res << "%t" << currId << " = OpLabel\n";
3594                         res << "%rt" << currId << " = OpFAdd %f32 " << value.top() << " %f32_1\n";
3595                         std::ostringstream tag;
3596                         tag << "%rt" << currId;
3597                         value.push(tag.str());
3598                         tag << " %t" << currId;
3599                         valueLabel.push(tag.str());
3600                 }
3601
3602                 if (*p == 'B')
3603                 {
3604                         mergeLeft.push(valueLabel.top());
3605                         value.pop();
3606                         valueLabel.pop();
3607                         res << "\tOpBranch %m" << currId << "\n";
3608                         res << "%f" << currId << " = OpLabel\n";
3609                         std::ostringstream tag;
3610                         tag << value.top() << " %f" << currId;
3611                         valueLabel.pop();
3612                         valueLabel.push(tag.str());
3613                 }
3614
3615                 if (*p == 'C')
3616                 {
3617                         mergeRight.push(valueLabel.top());
3618                         res << "\tOpBranch %m" << currId << "\n";
3619                         res << "%m" << currId << " = OpLabel\n";
3620                         if (*(p + 1) == 0)
3621                                 res << "%res"; // last result goes to %res
3622                         else
3623                                 res << "%rm" << currId;
3624                         res << " = OpPhi %f32  " << mergeLeft.top() << "  " << mergeRight.top() << "\n";
3625                         std::ostringstream tag;
3626                         tag << "%rm" << currId;
3627                         value.pop();
3628                         value.push(tag.str());
3629                         tag << " %m" << currId;
3630                         valueLabel.pop();
3631                         valueLabel.push(tag.str());
3632                         mergeLeft.pop();
3633                         mergeRight.pop();
3634                         depth--;
3635                         idStack.pop();
3636                         currId = idStack.top();
3637                 }
3638                 p++;
3639                 iter++;
3640         }
3641         return res.str();
3642 }
3643
3644 tcu::TestCaseGroup* createOpPhiGroup (tcu::TestContext& testCtx)
3645 {
3646         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
3647         ComputeShaderSpec                               spec1;
3648         ComputeShaderSpec                               spec2;
3649         ComputeShaderSpec                               spec3;
3650         ComputeShaderSpec                               spec4;
3651         ComputeShaderSpec                               spec5;
3652         de::Random                                              rnd                             (deStringHash(group->getName()));
3653         const int                                               numElements             = 100;
3654         vector<float>                                   inputFloats             (numElements, 0);
3655         vector<float>                                   outputFloats1   (numElements, 0);
3656         vector<float>                                   outputFloats2   (numElements, 0);
3657         vector<float>                                   outputFloats3   (numElements, 0);
3658         vector<float>                                   outputFloats4   (numElements, 0);
3659         vector<float>                                   outputFloats5   (numElements, 0);
3660         std::string                                             codestring              = "ABC";
3661         const int                                               test4Width              = 1024;
3662
3663         // Build case 5 code string. Each iteration makes the hierarchy more complicated.
3664         // 9 iterations with (7, 24) parameters makes the hierarchy 8 deep with about 1500 lines of
3665         // shader code.
3666         for (int i = 0, acc = 0; i < 9; i++)
3667                 codestring = expandOpPhiCase5(codestring, acc, 7, 24);
3668
3669         fillRandomScalars(rnd, -300.f, 300.f, &inputFloats[0], numElements);
3670
3671         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
3672         floorAll(inputFloats);
3673
3674         for (size_t ndx = 0; ndx < numElements; ++ndx)
3675         {
3676                 switch (ndx % 3)
3677                 {
3678                         case 0:         outputFloats1[ndx] = inputFloats[ndx] + 5.5f;   break;
3679                         case 1:         outputFloats1[ndx] = inputFloats[ndx] + 20.5f;  break;
3680                         case 2:         outputFloats1[ndx] = inputFloats[ndx] + 1.75f;  break;
3681                         default:        break;
3682                 }
3683                 outputFloats2[ndx] = inputFloats[ndx] + 6.5f * 3;
3684                 outputFloats3[ndx] = 8.5f - inputFloats[ndx];
3685
3686                 int index4 = (int)deFloor(deAbs((float)ndx * inputFloats[ndx]));
3687                 outputFloats4[ndx] = (float)(index4 % test4Width) * 10.0f + 5.0f;
3688
3689                 outputFloats5[ndx] = calcOpPhiCase5(inputFloats[ndx], codestring);
3690         }
3691
3692         spec1.assembly =
3693                 string(getComputeAsmShaderPreamble()) +
3694
3695                 "OpSource GLSL 430\n"
3696                 "OpName %main \"main\"\n"
3697                 "OpName %id \"gl_GlobalInvocationID\"\n"
3698
3699                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3700
3701                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3702
3703                 "%id = OpVariable %uvec3ptr Input\n"
3704                 "%zero       = OpConstant %i32 0\n"
3705                 "%three      = OpConstant %u32 3\n"
3706                 "%constf5p5  = OpConstant %f32 5.5\n"
3707                 "%constf20p5 = OpConstant %f32 20.5\n"
3708                 "%constf1p75 = OpConstant %f32 1.75\n"
3709                 "%constf8p5  = OpConstant %f32 8.5\n"
3710                 "%constf6p5  = OpConstant %f32 6.5\n"
3711
3712                 "%main     = OpFunction %void None %voidf\n"
3713                 "%entry    = OpLabel\n"
3714                 "%idval    = OpLoad %uvec3 %id\n"
3715                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3716                 "%selector = OpUMod %u32 %x %three\n"
3717                 "            OpSelectionMerge %phi None\n"
3718                 "            OpSwitch %selector %default 0 %case0 1 %case1 2 %case2\n"
3719
3720                 // Case 1 before OpPhi.
3721                 "%case1    = OpLabel\n"
3722                 "            OpBranch %phi\n"
3723
3724                 "%default  = OpLabel\n"
3725                 "            OpUnreachable\n"
3726
3727                 "%phi      = OpLabel\n"
3728                 "%operand  = OpPhi %f32   %constf1p75 %case2   %constf20p5 %case1   %constf5p5 %case0\n" // not in the order of blocks
3729                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3730                 "%inval    = OpLoad %f32 %inloc\n"
3731                 "%add      = OpFAdd %f32 %inval %operand\n"
3732                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3733                 "            OpStore %outloc %add\n"
3734                 "            OpReturn\n"
3735
3736                 // Case 0 after OpPhi.
3737                 "%case0    = OpLabel\n"
3738                 "            OpBranch %phi\n"
3739
3740
3741                 // Case 2 after OpPhi.
3742                 "%case2    = OpLabel\n"
3743                 "            OpBranch %phi\n"
3744
3745                 "            OpFunctionEnd\n";
3746         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3747         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
3748         spec1.numWorkGroups = IVec3(numElements, 1, 1);
3749
3750         group->addChild(new SpvAsmComputeShaderCase(testCtx, "block", "out-of-order and unreachable blocks for OpPhi", spec1));
3751
3752         spec2.assembly =
3753                 string(getComputeAsmShaderPreamble()) +
3754
3755                 "OpName %main \"main\"\n"
3756                 "OpName %id \"gl_GlobalInvocationID\"\n"
3757
3758                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3759
3760                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3761
3762                 "%id         = OpVariable %uvec3ptr Input\n"
3763                 "%zero       = OpConstant %i32 0\n"
3764                 "%one        = OpConstant %i32 1\n"
3765                 "%three      = OpConstant %i32 3\n"
3766                 "%constf6p5  = OpConstant %f32 6.5\n"
3767
3768                 "%main       = OpFunction %void None %voidf\n"
3769                 "%entry      = OpLabel\n"
3770                 "%idval      = OpLoad %uvec3 %id\n"
3771                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3772                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3773                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3774                 "%inval      = OpLoad %f32 %inloc\n"
3775                 "              OpBranch %phi\n"
3776
3777                 "%phi        = OpLabel\n"
3778                 "%step       = OpPhi %i32 %zero  %entry %step_next  %phi\n"
3779                 "%accum      = OpPhi %f32 %inval %entry %accum_next %phi\n"
3780                 "%step_next  = OpIAdd %i32 %step %one\n"
3781                 "%accum_next = OpFAdd %f32 %accum %constf6p5\n"
3782                 "%still_loop = OpSLessThan %bool %step %three\n"
3783                 "              OpLoopMerge %exit %phi None\n"
3784                 "              OpBranchConditional %still_loop %phi %exit\n"
3785
3786                 "%exit       = OpLabel\n"
3787                 "              OpStore %outloc %accum\n"
3788                 "              OpReturn\n"
3789                 "              OpFunctionEnd\n";
3790         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3791         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
3792         spec2.numWorkGroups = IVec3(numElements, 1, 1);
3793
3794         group->addChild(new SpvAsmComputeShaderCase(testCtx, "induction", "The usual way induction variables are handled in LLVM IR", spec2));
3795
3796         spec3.assembly =
3797                 string(getComputeAsmShaderPreamble()) +
3798
3799                 "OpName %main \"main\"\n"
3800                 "OpName %id \"gl_GlobalInvocationID\"\n"
3801
3802                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3803
3804                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3805
3806                 "%f32ptr_f   = OpTypePointer Function %f32\n"
3807                 "%id         = OpVariable %uvec3ptr Input\n"
3808                 "%true       = OpConstantTrue %bool\n"
3809                 "%false      = OpConstantFalse %bool\n"
3810                 "%zero       = OpConstant %i32 0\n"
3811                 "%constf8p5  = OpConstant %f32 8.5\n"
3812
3813                 "%main       = OpFunction %void None %voidf\n"
3814                 "%entry      = OpLabel\n"
3815                 "%b          = OpVariable %f32ptr_f Function %constf8p5\n"
3816                 "%idval      = OpLoad %uvec3 %id\n"
3817                 "%x          = OpCompositeExtract %u32 %idval 0\n"
3818                 "%inloc      = OpAccessChain %f32ptr %indata %zero %x\n"
3819                 "%outloc     = OpAccessChain %f32ptr %outdata %zero %x\n"
3820                 "%a_init     = OpLoad %f32 %inloc\n"
3821                 "%b_init     = OpLoad %f32 %b\n"
3822                 "              OpBranch %phi\n"
3823
3824                 "%phi        = OpLabel\n"
3825                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
3826                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
3827                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
3828                 "              OpLoopMerge %exit %phi None\n"
3829                 "              OpBranchConditional %still_loop %phi %exit\n"
3830
3831                 "%exit       = OpLabel\n"
3832                 "%sub        = OpFSub %f32 %a_next %b_next\n"
3833                 "              OpStore %outloc %sub\n"
3834                 "              OpReturn\n"
3835                 "              OpFunctionEnd\n";
3836         spec3.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3837         spec3.outputs.push_back(BufferSp(new Float32Buffer(outputFloats3)));
3838         spec3.numWorkGroups = IVec3(numElements, 1, 1);
3839
3840         group->addChild(new SpvAsmComputeShaderCase(testCtx, "swap", "Swap the values of two variables using OpPhi", spec3));
3841
3842         spec4.assembly =
3843                 "OpCapability Shader\n"
3844                 "%ext = OpExtInstImport \"GLSL.std.450\"\n"
3845                 "OpMemoryModel Logical GLSL450\n"
3846                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3847                 "OpExecutionMode %main LocalSize 1 1 1\n"
3848
3849                 "OpSource GLSL 430\n"
3850                 "OpName %main \"main\"\n"
3851                 "OpName %id \"gl_GlobalInvocationID\"\n"
3852
3853                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3854
3855                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3856
3857                 "%id       = OpVariable %uvec3ptr Input\n"
3858                 "%zero     = OpConstant %i32 0\n"
3859                 "%cimod    = OpConstant %u32 " + generateIntWidth(test4Width) + "\n"
3860
3861                 + generateConstantDefinitions(test4Width) +
3862
3863                 "%main     = OpFunction %void None %voidf\n"
3864                 "%entry    = OpLabel\n"
3865                 "%idval    = OpLoad %uvec3 %id\n"
3866                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3867                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3868                 "%inval    = OpLoad %f32 %inloc\n"
3869                 "%xf       = OpConvertUToF %f32 %x\n"
3870                 "%xm       = OpFMul %f32 %xf %inval\n"
3871                 "%xa       = OpExtInst %f32 %ext FAbs %xm\n"
3872                 "%xi       = OpConvertFToU %u32 %xa\n"
3873                 "%selector = OpUMod %u32 %xi %cimod\n"
3874                 "            OpSelectionMerge %phi None\n"
3875                 "            OpSwitch %selector %default "
3876
3877                 + generateSwitchCases(test4Width) +
3878
3879                 "%default  = OpLabel\n"
3880                 "            OpUnreachable\n"
3881
3882                 + generateSwitchTargets(test4Width) +
3883
3884                 "%phi      = OpLabel\n"
3885                 "%result   = OpPhi %f32"
3886
3887                 + generateOpPhiParams(test4Width) +
3888
3889                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3890                 "            OpStore %outloc %result\n"
3891                 "            OpReturn\n"
3892
3893                 "            OpFunctionEnd\n";
3894         spec4.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3895         spec4.outputs.push_back(BufferSp(new Float32Buffer(outputFloats4)));
3896         spec4.numWorkGroups = IVec3(numElements, 1, 1);
3897
3898         group->addChild(new SpvAsmComputeShaderCase(testCtx, "wide", "OpPhi with a lot of parameters", spec4));
3899
3900         spec5.assembly =
3901                 "OpCapability Shader\n"
3902                 "%ext      = OpExtInstImport \"GLSL.std.450\"\n"
3903                 "OpMemoryModel Logical GLSL450\n"
3904                 "OpEntryPoint GLCompute %main \"main\" %id\n"
3905                 "OpExecutionMode %main LocalSize 1 1 1\n"
3906                 "%code     = OpString \"" + codestring + "\"\n"
3907
3908                 "OpSource GLSL 430\n"
3909                 "OpName %main \"main\"\n"
3910                 "OpName %id \"gl_GlobalInvocationID\"\n"
3911
3912                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
3913
3914                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
3915
3916                 "%id       = OpVariable %uvec3ptr Input\n"
3917                 "%zero     = OpConstant %i32 0\n"
3918                 "%f32_0    = OpConstant %f32 0.0\n"
3919                 "%f32_0_5  = OpConstant %f32 0.5\n"
3920                 "%f32_1    = OpConstant %f32 1.0\n"
3921                 "%f32_1_5  = OpConstant %f32 1.5\n"
3922                 "%f32_2    = OpConstant %f32 2.0\n"
3923                 "%f32_3_5  = OpConstant %f32 3.5\n"
3924                 "%f32_4    = OpConstant %f32 4.0\n"
3925                 "%f32_7_5  = OpConstant %f32 7.5\n"
3926                 "%f32_8    = OpConstant %f32 8.0\n"
3927                 "%f32_15_5 = OpConstant %f32 15.5\n"
3928                 "%f32_16   = OpConstant %f32 16.0\n"
3929                 "%f32_31_5 = OpConstant %f32 31.5\n"
3930                 "%f32_32   = OpConstant %f32 32.0\n"
3931                 "%f32_63_5 = OpConstant %f32 63.5\n"
3932                 "%f32_64   = OpConstant %f32 64.0\n"
3933                 "%f32_127_5 = OpConstant %f32 127.5\n"
3934                 "%f32_128  = OpConstant %f32 128.0\n"
3935                 "%f32_256  = OpConstant %f32 256.0\n"
3936
3937                 "%main     = OpFunction %void None %voidf\n"
3938                 "%entry    = OpLabel\n"
3939                 "%idval    = OpLoad %uvec3 %id\n"
3940                 "%x        = OpCompositeExtract %u32 %idval 0\n"
3941                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
3942                 "%inval    = OpLoad %f32 %inloc\n"
3943
3944                 "%xabs     = OpExtInst %f32 %ext FAbs %inval\n"
3945                 "%x8       = OpFMod %f32 %xabs %f32_256\n"
3946                 "%x7       = OpFMod %f32 %xabs %f32_128\n"
3947                 "%x6       = OpFMod %f32 %xabs %f32_64\n"
3948                 "%x5       = OpFMod %f32 %xabs %f32_32\n"
3949                 "%x4       = OpFMod %f32 %xabs %f32_16\n"
3950                 "%x3       = OpFMod %f32 %xabs %f32_8\n"
3951                 "%x2       = OpFMod %f32 %xabs %f32_4\n"
3952                 "%x1       = OpFMod %f32 %xabs %f32_2\n"
3953
3954                 "%b7       = OpFOrdGreaterThanEqual %bool %x8 %f32_127_5\n"
3955                 "%b6       = OpFOrdGreaterThanEqual %bool %x7 %f32_63_5\n"
3956                 "%b5       = OpFOrdGreaterThanEqual %bool %x6 %f32_31_5\n"
3957                 "%b4       = OpFOrdGreaterThanEqual %bool %x5 %f32_15_5\n"
3958                 "%b3       = OpFOrdGreaterThanEqual %bool %x4 %f32_7_5\n"
3959                 "%b2       = OpFOrdGreaterThanEqual %bool %x3 %f32_3_5\n"
3960                 "%b1       = OpFOrdGreaterThanEqual %bool %x2 %f32_1_5\n"
3961                 "%b0       = OpFOrdGreaterThanEqual %bool %x1 %f32_0_5\n"
3962
3963                 + generateOpPhiCase5(codestring) +
3964
3965                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
3966                 "            OpStore %outloc %res\n"
3967                 "            OpReturn\n"
3968
3969                 "            OpFunctionEnd\n";
3970         spec5.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
3971         spec5.outputs.push_back(BufferSp(new Float32Buffer(outputFloats5)));
3972         spec5.numWorkGroups = IVec3(numElements, 1, 1);
3973
3974         group->addChild(new SpvAsmComputeShaderCase(testCtx, "nested", "Stress OpPhi with a lot of nesting", spec5));
3975
3976         createOpPhiVartypeTests(group, testCtx);
3977
3978         return group.release();
3979 }
3980
3981 // Assembly code used for testing block order is based on GLSL source code:
3982 //
3983 // #version 430
3984 //
3985 // layout(std140, set = 0, binding = 0) readonly buffer Input {
3986 //   float elements[];
3987 // } input_data;
3988 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
3989 //   float elements[];
3990 // } output_data;
3991 //
3992 // void main() {
3993 //   uint x = gl_GlobalInvocationID.x;
3994 //   output_data.elements[x] = input_data.elements[x];
3995 //   if (x > uint(50)) {
3996 //     switch (x % uint(3)) {
3997 //       case 0: output_data.elements[x] += 1.5f; break;
3998 //       case 1: output_data.elements[x] += 42.f; break;
3999 //       case 2: output_data.elements[x] -= 27.f; break;
4000 //       default: break;
4001 //     }
4002 //   } else {
4003 //     output_data.elements[x] = -input_data.elements[x];
4004 //   }
4005 // }
4006 tcu::TestCaseGroup* createBlockOrderGroup (tcu::TestContext& testCtx)
4007 {
4008         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "block_order", "Test block orders"));
4009         ComputeShaderSpec                               spec;
4010         de::Random                                              rnd                             (deStringHash(group->getName()));
4011         const int                                               numElements             = 100;
4012         vector<float>                                   inputFloats             (numElements, 0);
4013         vector<float>                                   outputFloats    (numElements, 0);
4014
4015         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
4016
4017         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
4018         floorAll(inputFloats);
4019
4020         for (size_t ndx = 0; ndx <= 50; ++ndx)
4021                 outputFloats[ndx] = -inputFloats[ndx];
4022
4023         for (size_t ndx = 51; ndx < numElements; ++ndx)
4024         {
4025                 switch (ndx % 3)
4026                 {
4027                         case 0:         outputFloats[ndx] = inputFloats[ndx] + 1.5f; break;
4028                         case 1:         outputFloats[ndx] = inputFloats[ndx] + 42.f; break;
4029                         case 2:         outputFloats[ndx] = inputFloats[ndx] - 27.f; break;
4030                         default:        break;
4031                 }
4032         }
4033
4034         spec.assembly =
4035                 string(getComputeAsmShaderPreamble()) +
4036
4037                 "OpSource GLSL 430\n"
4038                 "OpName %main \"main\"\n"
4039                 "OpName %id \"gl_GlobalInvocationID\"\n"
4040
4041                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4042
4043                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4044
4045                 "%u32ptr       = OpTypePointer Function %u32\n"
4046                 "%u32ptr_input = OpTypePointer Input %u32\n"
4047
4048                 + string(getComputeAsmInputOutputBuffer()) +
4049
4050                 "%id        = OpVariable %uvec3ptr Input\n"
4051                 "%zero      = OpConstant %i32 0\n"
4052                 "%const3    = OpConstant %u32 3\n"
4053                 "%const50   = OpConstant %u32 50\n"
4054                 "%constf1p5 = OpConstant %f32 1.5\n"
4055                 "%constf27  = OpConstant %f32 27.0\n"
4056                 "%constf42  = OpConstant %f32 42.0\n"
4057
4058                 "%main = OpFunction %void None %voidf\n"
4059
4060                 // entry block.
4061                 "%entry    = OpLabel\n"
4062
4063                 // Create a temporary variable to hold the value of gl_GlobalInvocationID.x.
4064                 "%xvar     = OpVariable %u32ptr Function\n"
4065                 "%xptr     = OpAccessChain %u32ptr_input %id %zero\n"
4066                 "%x        = OpLoad %u32 %xptr\n"
4067                 "            OpStore %xvar %x\n"
4068
4069                 "%cmp      = OpUGreaterThan %bool %x %const50\n"
4070                 "            OpSelectionMerge %if_merge None\n"
4071                 "            OpBranchConditional %cmp %if_true %if_false\n"
4072
4073                 // False branch for if-statement: placed in the middle of switch cases and before true branch.
4074                 "%if_false = OpLabel\n"
4075                 "%x_f      = OpLoad %u32 %xvar\n"
4076                 "%inloc_f  = OpAccessChain %f32ptr %indata %zero %x_f\n"
4077                 "%inval_f  = OpLoad %f32 %inloc_f\n"
4078                 "%negate   = OpFNegate %f32 %inval_f\n"
4079                 "%outloc_f = OpAccessChain %f32ptr %outdata %zero %x_f\n"
4080                 "            OpStore %outloc_f %negate\n"
4081                 "            OpBranch %if_merge\n"
4082
4083                 // Merge block for if-statement: placed in the middle of true and false branch.
4084                 "%if_merge = OpLabel\n"
4085                 "            OpReturn\n"
4086
4087                 // True branch for if-statement: placed in the middle of swtich cases and after the false branch.
4088                 "%if_true  = OpLabel\n"
4089                 "%xval_t   = OpLoad %u32 %xvar\n"
4090                 "%mod      = OpUMod %u32 %xval_t %const3\n"
4091                 "            OpSelectionMerge %switch_merge None\n"
4092                 "            OpSwitch %mod %default 0 %case0 1 %case1 2 %case2\n"
4093
4094                 // Merge block for switch-statement: placed before the case
4095                 // bodies.  But it must follow OpSwitch which dominates it.
4096                 "%switch_merge = OpLabel\n"
4097                 "                OpBranch %if_merge\n"
4098
4099                 // Case 1 for switch-statement: placed before case 0.
4100                 // It must follow the OpSwitch that dominates it.
4101                 "%case1    = OpLabel\n"
4102                 "%x_1      = OpLoad %u32 %xvar\n"
4103                 "%inloc_1  = OpAccessChain %f32ptr %indata %zero %x_1\n"
4104                 "%inval_1  = OpLoad %f32 %inloc_1\n"
4105                 "%addf42   = OpFAdd %f32 %inval_1 %constf42\n"
4106                 "%outloc_1 = OpAccessChain %f32ptr %outdata %zero %x_1\n"
4107                 "            OpStore %outloc_1 %addf42\n"
4108                 "            OpBranch %switch_merge\n"
4109
4110                 // Case 2 for switch-statement.
4111                 "%case2    = OpLabel\n"
4112                 "%x_2      = OpLoad %u32 %xvar\n"
4113                 "%inloc_2  = OpAccessChain %f32ptr %indata %zero %x_2\n"
4114                 "%inval_2  = OpLoad %f32 %inloc_2\n"
4115                 "%subf27   = OpFSub %f32 %inval_2 %constf27\n"
4116                 "%outloc_2 = OpAccessChain %f32ptr %outdata %zero %x_2\n"
4117                 "            OpStore %outloc_2 %subf27\n"
4118                 "            OpBranch %switch_merge\n"
4119
4120                 // Default case for switch-statement: placed in the middle of normal cases.
4121                 "%default = OpLabel\n"
4122                 "           OpBranch %switch_merge\n"
4123
4124                 // Case 0 for switch-statement: out of order.
4125                 "%case0    = OpLabel\n"
4126                 "%x_0      = OpLoad %u32 %xvar\n"
4127                 "%inloc_0  = OpAccessChain %f32ptr %indata %zero %x_0\n"
4128                 "%inval_0  = OpLoad %f32 %inloc_0\n"
4129                 "%addf1p5  = OpFAdd %f32 %inval_0 %constf1p5\n"
4130                 "%outloc_0 = OpAccessChain %f32ptr %outdata %zero %x_0\n"
4131                 "            OpStore %outloc_0 %addf1p5\n"
4132                 "            OpBranch %switch_merge\n"
4133
4134                 "            OpFunctionEnd\n";
4135         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4136         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4137         spec.numWorkGroups = IVec3(numElements, 1, 1);
4138
4139         group->addChild(new SpvAsmComputeShaderCase(testCtx, "all", "various out-of-order blocks", spec));
4140
4141         return group.release();
4142 }
4143
4144 tcu::TestCaseGroup* createMultipleShaderGroup (tcu::TestContext& testCtx)
4145 {
4146         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "multiple_shaders", "Test multiple shaders in the same module"));
4147         ComputeShaderSpec                               spec1;
4148         ComputeShaderSpec                               spec2;
4149         de::Random                                              rnd                             (deStringHash(group->getName()));
4150         const int                                               numElements             = 100;
4151         vector<float>                                   inputFloats             (numElements, 0);
4152         vector<float>                                   outputFloats1   (numElements, 0);
4153         vector<float>                                   outputFloats2   (numElements, 0);
4154         fillRandomScalars(rnd, -500.f, 500.f, &inputFloats[0], numElements);
4155
4156         for (size_t ndx = 0; ndx < numElements; ++ndx)
4157         {
4158                 outputFloats1[ndx] = inputFloats[ndx] + inputFloats[ndx];
4159                 outputFloats2[ndx] = -inputFloats[ndx];
4160         }
4161
4162         const string assembly(
4163                 "OpCapability Shader\n"
4164                 "OpMemoryModel Logical GLSL450\n"
4165                 "OpEntryPoint GLCompute %comp_main1 \"entrypoint1\" %id\n"
4166                 "OpEntryPoint GLCompute %comp_main2 \"entrypoint2\" %id\n"
4167                 // A module cannot have two OpEntryPoint instructions with the same Execution Model and the same Name string.
4168                 "OpEntryPoint Vertex    %vert_main  \"entrypoint2\" %vert_builtins %vertexIndex %instanceIndex\n"
4169                 "OpExecutionMode %comp_main1 LocalSize 1 1 1\n"
4170                 "OpExecutionMode %comp_main2 LocalSize 1 1 1\n"
4171
4172                 "OpName %comp_main1              \"entrypoint1\"\n"
4173                 "OpName %comp_main2              \"entrypoint2\"\n"
4174                 "OpName %vert_main               \"entrypoint2\"\n"
4175                 "OpName %id                      \"gl_GlobalInvocationID\"\n"
4176                 "OpName %vert_builtin_st         \"gl_PerVertex\"\n"
4177                 "OpName %vertexIndex             \"gl_VertexIndex\"\n"
4178                 "OpName %instanceIndex           \"gl_InstanceIndex\"\n"
4179                 "OpMemberName %vert_builtin_st 0 \"gl_Position\"\n"
4180                 "OpMemberName %vert_builtin_st 1 \"gl_PointSize\"\n"
4181                 "OpMemberName %vert_builtin_st 2 \"gl_ClipDistance\"\n"
4182
4183                 "OpDecorate %id                      BuiltIn GlobalInvocationId\n"
4184                 "OpDecorate %vertexIndex             BuiltIn VertexIndex\n"
4185                 "OpDecorate %instanceIndex           BuiltIn InstanceIndex\n"
4186                 "OpDecorate %vert_builtin_st         Block\n"
4187                 "OpMemberDecorate %vert_builtin_st 0 BuiltIn Position\n"
4188                 "OpMemberDecorate %vert_builtin_st 1 BuiltIn PointSize\n"
4189                 "OpMemberDecorate %vert_builtin_st 2 BuiltIn ClipDistance\n"
4190
4191                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4192
4193                 "%zero       = OpConstant %i32 0\n"
4194                 "%one        = OpConstant %u32 1\n"
4195                 "%c_f32_1    = OpConstant %f32 1\n"
4196
4197                 "%i32inputptr         = OpTypePointer Input %i32\n"
4198                 "%vec4                = OpTypeVector %f32 4\n"
4199                 "%vec4ptr             = OpTypePointer Output %vec4\n"
4200                 "%f32arr1             = OpTypeArray %f32 %one\n"
4201                 "%vert_builtin_st     = OpTypeStruct %vec4 %f32 %f32arr1\n"
4202                 "%vert_builtin_st_ptr = OpTypePointer Output %vert_builtin_st\n"
4203                 "%vert_builtins       = OpVariable %vert_builtin_st_ptr Output\n"
4204
4205                 "%id         = OpVariable %uvec3ptr Input\n"
4206                 "%vertexIndex = OpVariable %i32inputptr Input\n"
4207                 "%instanceIndex = OpVariable %i32inputptr Input\n"
4208                 "%c_vec4_1   = OpConstantComposite %vec4 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
4209
4210                 // gl_Position = vec4(1.);
4211                 "%vert_main  = OpFunction %void None %voidf\n"
4212                 "%vert_entry = OpLabel\n"
4213                 "%position   = OpAccessChain %vec4ptr %vert_builtins %zero\n"
4214                 "              OpStore %position %c_vec4_1\n"
4215                 "              OpReturn\n"
4216                 "              OpFunctionEnd\n"
4217
4218                 // Double inputs.
4219                 "%comp_main1  = OpFunction %void None %voidf\n"
4220                 "%comp1_entry = OpLabel\n"
4221                 "%idval1      = OpLoad %uvec3 %id\n"
4222                 "%x1          = OpCompositeExtract %u32 %idval1 0\n"
4223                 "%inloc1      = OpAccessChain %f32ptr %indata %zero %x1\n"
4224                 "%inval1      = OpLoad %f32 %inloc1\n"
4225                 "%add         = OpFAdd %f32 %inval1 %inval1\n"
4226                 "%outloc1     = OpAccessChain %f32ptr %outdata %zero %x1\n"
4227                 "               OpStore %outloc1 %add\n"
4228                 "               OpReturn\n"
4229                 "               OpFunctionEnd\n"
4230
4231                 // Negate inputs.
4232                 "%comp_main2  = OpFunction %void None %voidf\n"
4233                 "%comp2_entry = OpLabel\n"
4234                 "%idval2      = OpLoad %uvec3 %id\n"
4235                 "%x2          = OpCompositeExtract %u32 %idval2 0\n"
4236                 "%inloc2      = OpAccessChain %f32ptr %indata %zero %x2\n"
4237                 "%inval2      = OpLoad %f32 %inloc2\n"
4238                 "%neg         = OpFNegate %f32 %inval2\n"
4239                 "%outloc2     = OpAccessChain %f32ptr %outdata %zero %x2\n"
4240                 "               OpStore %outloc2 %neg\n"
4241                 "               OpReturn\n"
4242                 "               OpFunctionEnd\n");
4243
4244         spec1.assembly = assembly;
4245         spec1.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4246         spec1.outputs.push_back(BufferSp(new Float32Buffer(outputFloats1)));
4247         spec1.numWorkGroups = IVec3(numElements, 1, 1);
4248         spec1.entryPoint = "entrypoint1";
4249
4250         spec2.assembly = assembly;
4251         spec2.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4252         spec2.outputs.push_back(BufferSp(new Float32Buffer(outputFloats2)));
4253         spec2.numWorkGroups = IVec3(numElements, 1, 1);
4254         spec2.entryPoint = "entrypoint2";
4255
4256         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader1", "multiple shaders in the same module", spec1));
4257         group->addChild(new SpvAsmComputeShaderCase(testCtx, "shader2", "multiple shaders in the same module", spec2));
4258
4259         return group.release();
4260 }
4261
4262 inline std::string makeLongUTF8String (size_t num4ByteChars)
4263 {
4264         // An example of a longest valid UTF-8 character.  Be explicit about the
4265         // character type because Microsoft compilers can otherwise interpret the
4266         // character string as being over wide (16-bit) characters. Ideally, we
4267         // would just use a C++11 UTF-8 string literal, but we want to support older
4268         // Microsoft compilers.
4269         const std::basic_string<char> earthAfrica("\xF0\x9F\x8C\x8D");
4270         std::string longString;
4271         longString.reserve(num4ByteChars * 4);
4272         for (size_t count = 0; count < num4ByteChars; count++)
4273         {
4274                 longString += earthAfrica;
4275         }
4276         return longString;
4277 }
4278
4279 tcu::TestCaseGroup* createOpSourceGroup (tcu::TestContext& testCtx)
4280 {
4281         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsource", "Tests the OpSource & OpSourceContinued instruction"));
4282         vector<CaseParameter>                   cases;
4283         de::Random                                              rnd                             (deStringHash(group->getName()));
4284         const int                                               numElements             = 100;
4285         vector<float>                                   positiveFloats  (numElements, 0);
4286         vector<float>                                   negativeFloats  (numElements, 0);
4287         const StringTemplate                    shaderTemplate  (
4288                 "OpCapability Shader\n"
4289                 "OpMemoryModel Logical GLSL450\n"
4290
4291                 "OpEntryPoint GLCompute %main \"main\" %id\n"
4292                 "OpExecutionMode %main LocalSize 1 1 1\n"
4293
4294                 "${SOURCE}\n"
4295
4296                 "OpName %main           \"main\"\n"
4297                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4298
4299                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4300
4301                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4302
4303                 "%id        = OpVariable %uvec3ptr Input\n"
4304                 "%zero      = OpConstant %i32 0\n"
4305
4306                 "%main      = OpFunction %void None %voidf\n"
4307                 "%label     = OpLabel\n"
4308                 "%idval     = OpLoad %uvec3 %id\n"
4309                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4310                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4311                 "%inval     = OpLoad %f32 %inloc\n"
4312                 "%neg       = OpFNegate %f32 %inval\n"
4313                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4314                 "             OpStore %outloc %neg\n"
4315                 "             OpReturn\n"
4316                 "             OpFunctionEnd\n");
4317
4318         cases.push_back(CaseParameter("unknown_source",                                                 "OpSource Unknown 0"));
4319         cases.push_back(CaseParameter("wrong_source",                                                   "OpSource OpenCL_C 210"));
4320         cases.push_back(CaseParameter("normal_filename",                                                "%fname = OpString \"filename\"\n"
4321                                                                                                                                                         "OpSource GLSL 430 %fname"));
4322         cases.push_back(CaseParameter("empty_filename",                                                 "%fname = OpString \"\"\n"
4323                                                                                                                                                         "OpSource GLSL 430 %fname"));
4324         cases.push_back(CaseParameter("normal_source_code",                                             "%fname = OpString \"filename\"\n"
4325                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\""));
4326         cases.push_back(CaseParameter("empty_source_code",                                              "%fname = OpString \"filename\"\n"
4327                                                                                                                                                         "OpSource GLSL 430 %fname \"\""));
4328         cases.push_back(CaseParameter("long_source_code",                                               "%fname = OpString \"filename\"\n"
4329                                                                                                                                                         "OpSource GLSL 430 %fname \"" + makeLongUTF8String(65530) + "ccc\"")); // word count: 65535
4330         cases.push_back(CaseParameter("utf8_source_code",                                               "%fname = OpString \"filename\"\n"
4331                                                                                                                                                         "OpSource GLSL 430 %fname \"\xE2\x98\x82\xE2\x98\x85\"")); // umbrella & black star symbol
4332         cases.push_back(CaseParameter("normal_sourcecontinued",                                 "%fname = OpString \"filename\"\n"
4333                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvo\"\n"
4334                                                                                                                                                         "OpSourceContinued \"id main() {}\""));
4335         cases.push_back(CaseParameter("empty_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4336                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4337                                                                                                                                                         "OpSourceContinued \"\""));
4338         cases.push_back(CaseParameter("long_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4339                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4340                                                                                                                                                         "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\"")); // word count: 65535
4341         cases.push_back(CaseParameter("utf8_sourcecontinued",                                   "%fname = OpString \"filename\"\n"
4342                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\nvoid main() {}\"\n"
4343                                                                                                                                                         "OpSourceContinued \"\xE2\x98\x8E\xE2\x9A\x91\"")); // white telephone & black flag symbol
4344         cases.push_back(CaseParameter("multi_sourcecontinued",                                  "%fname = OpString \"filename\"\n"
4345                                                                                                                                                         "OpSource GLSL 430 %fname \"#version 430\n\"\n"
4346                                                                                                                                                         "OpSourceContinued \"void\"\n"
4347                                                                                                                                                         "OpSourceContinued \"main()\"\n"
4348                                                                                                                                                         "OpSourceContinued \"{}\""));
4349         cases.push_back(CaseParameter("empty_source_before_sourcecontinued",    "%fname = OpString \"filename\"\n"
4350                                                                                                                                                         "OpSource GLSL 430 %fname \"\"\n"
4351                                                                                                                                                         "OpSourceContinued \"#version 430\nvoid main() {}\""));
4352
4353         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4354
4355         for (size_t ndx = 0; ndx < numElements; ++ndx)
4356                 negativeFloats[ndx] = -positiveFloats[ndx];
4357
4358         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4359         {
4360                 map<string, string>             specializations;
4361                 ComputeShaderSpec               spec;
4362
4363                 specializations["SOURCE"] = cases[caseNdx].param;
4364                 spec.assembly = shaderTemplate.specialize(specializations);
4365                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4366                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4367                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4368
4369                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4370         }
4371
4372         return group.release();
4373 }
4374
4375 tcu::TestCaseGroup* createOpSourceExtensionGroup (tcu::TestContext& testCtx)
4376 {
4377         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opsourceextension", "Tests the OpSource instruction"));
4378         vector<CaseParameter>                   cases;
4379         de::Random                                              rnd                             (deStringHash(group->getName()));
4380         const int                                               numElements             = 100;
4381         vector<float>                                   inputFloats             (numElements, 0);
4382         vector<float>                                   outputFloats    (numElements, 0);
4383         const StringTemplate                    shaderTemplate  (
4384                 string(getComputeAsmShaderPreamble()) +
4385
4386                 "OpSourceExtension \"${EXTENSION}\"\n"
4387
4388                 "OpName %main           \"main\"\n"
4389                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4390
4391                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4392
4393                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4394
4395                 "%id        = OpVariable %uvec3ptr Input\n"
4396                 "%zero      = OpConstant %i32 0\n"
4397
4398                 "%main      = OpFunction %void None %voidf\n"
4399                 "%label     = OpLabel\n"
4400                 "%idval     = OpLoad %uvec3 %id\n"
4401                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4402                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4403                 "%inval     = OpLoad %f32 %inloc\n"
4404                 "%neg       = OpFNegate %f32 %inval\n"
4405                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4406                 "             OpStore %outloc %neg\n"
4407                 "             OpReturn\n"
4408                 "             OpFunctionEnd\n");
4409
4410         cases.push_back(CaseParameter("empty_extension",        ""));
4411         cases.push_back(CaseParameter("real_extension",         "GL_ARB_texture_rectangle"));
4412         cases.push_back(CaseParameter("fake_extension",         "GL_ARB_im_the_ultimate_extension"));
4413         cases.push_back(CaseParameter("utf8_extension",         "GL_ARB_\xE2\x98\x82\xE2\x98\x85"));
4414         cases.push_back(CaseParameter("long_extension",         makeLongUTF8String(65533) + "ccc")); // word count: 65535
4415
4416         fillRandomScalars(rnd, -200.f, 200.f, &inputFloats[0], numElements);
4417
4418         for (size_t ndx = 0; ndx < numElements; ++ndx)
4419                 outputFloats[ndx] = -inputFloats[ndx];
4420
4421         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4422         {
4423                 map<string, string>             specializations;
4424                 ComputeShaderSpec               spec;
4425
4426                 specializations["EXTENSION"] = cases[caseNdx].param;
4427                 spec.assembly = shaderTemplate.specialize(specializations);
4428                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
4429                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
4430                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4431
4432                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4433         }
4434
4435         return group.release();
4436 }
4437
4438 // Checks that a compute shader can generate a constant null value of various types, without exercising a computation on it.
4439 tcu::TestCaseGroup* createOpConstantNullGroup (tcu::TestContext& testCtx)
4440 {
4441         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnull", "Tests the OpConstantNull instruction"));
4442         vector<CaseParameter>                   cases;
4443         de::Random                                              rnd                             (deStringHash(group->getName()));
4444         const int                                               numElements             = 100;
4445         vector<float>                                   positiveFloats  (numElements, 0);
4446         vector<float>                                   negativeFloats  (numElements, 0);
4447         const StringTemplate                    shaderTemplate  (
4448                 string(getComputeAsmShaderPreamble()) +
4449
4450                 "OpSource GLSL 430\n"
4451                 "OpName %main           \"main\"\n"
4452                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4453
4454                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4455
4456                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
4457                 "%uvec2     = OpTypeVector %u32 2\n"
4458                 "%bvec3     = OpTypeVector %bool 3\n"
4459                 "%fvec4     = OpTypeVector %f32 4\n"
4460                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
4461                 "%const100  = OpConstant %u32 100\n"
4462                 "%uarr100   = OpTypeArray %i32 %const100\n"
4463                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
4464                 "%pointer   = OpTypePointer Function %i32\n"
4465                 + string(getComputeAsmInputOutputBuffer()) +
4466
4467                 "%null      = OpConstantNull ${TYPE}\n"
4468
4469                 "%id        = OpVariable %uvec3ptr Input\n"
4470                 "%zero      = OpConstant %i32 0\n"
4471
4472                 "%main      = OpFunction %void None %voidf\n"
4473                 "%label     = OpLabel\n"
4474                 "%idval     = OpLoad %uvec3 %id\n"
4475                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4476                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4477                 "%inval     = OpLoad %f32 %inloc\n"
4478                 "%neg       = OpFNegate %f32 %inval\n"
4479                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4480                 "             OpStore %outloc %neg\n"
4481                 "             OpReturn\n"
4482                 "             OpFunctionEnd\n");
4483
4484         cases.push_back(CaseParameter("bool",                   "%bool"));
4485         cases.push_back(CaseParameter("sint32",                 "%i32"));
4486         cases.push_back(CaseParameter("uint32",                 "%u32"));
4487         cases.push_back(CaseParameter("float32",                "%f32"));
4488         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
4489         cases.push_back(CaseParameter("vec3bool",               "%bvec3"));
4490         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
4491         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
4492         cases.push_back(CaseParameter("array",                  "%uarr100"));
4493         cases.push_back(CaseParameter("struct",                 "%struct"));
4494         cases.push_back(CaseParameter("pointer",                "%pointer"));
4495
4496         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4497
4498         for (size_t ndx = 0; ndx < numElements; ++ndx)
4499                 negativeFloats[ndx] = -positiveFloats[ndx];
4500
4501         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4502         {
4503                 map<string, string>             specializations;
4504                 ComputeShaderSpec               spec;
4505
4506                 specializations["TYPE"] = cases[caseNdx].param;
4507                 spec.assembly = shaderTemplate.specialize(specializations);
4508                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4509                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4510                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4511
4512                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4513         }
4514
4515         return group.release();
4516 }
4517
4518 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4519 tcu::TestCaseGroup* createOpConstantCompositeGroup (tcu::TestContext& testCtx)
4520 {
4521         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
4522         vector<CaseParameter>                   cases;
4523         de::Random                                              rnd                             (deStringHash(group->getName()));
4524         const int                                               numElements             = 100;
4525         vector<float>                                   positiveFloats  (numElements, 0);
4526         vector<float>                                   negativeFloats  (numElements, 0);
4527         const StringTemplate                    shaderTemplate  (
4528                 string(getComputeAsmShaderPreamble()) +
4529
4530                 "OpSource GLSL 430\n"
4531                 "OpName %main           \"main\"\n"
4532                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4533
4534                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4535
4536                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4537
4538                 "%id        = OpVariable %uvec3ptr Input\n"
4539                 "%zero      = OpConstant %i32 0\n"
4540
4541                 "${CONSTANT}\n"
4542
4543                 "%main      = OpFunction %void None %voidf\n"
4544                 "%label     = OpLabel\n"
4545                 "%idval     = OpLoad %uvec3 %id\n"
4546                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4547                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4548                 "%inval     = OpLoad %f32 %inloc\n"
4549                 "%neg       = OpFNegate %f32 %inval\n"
4550                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4551                 "             OpStore %outloc %neg\n"
4552                 "             OpReturn\n"
4553                 "             OpFunctionEnd\n");
4554
4555         cases.push_back(CaseParameter("vector",                 "%five = OpConstant %u32 5\n"
4556                                                                                                         "%const = OpConstantComposite %uvec3 %five %zero %five"));
4557         cases.push_back(CaseParameter("matrix",                 "%m3fvec3 = OpTypeMatrix %fvec3 3\n"
4558                                                                                                         "%ten = OpConstant %f32 10.\n"
4559                                                                                                         "%fzero = OpConstant %f32 0.\n"
4560                                                                                                         "%vec = OpConstantComposite %fvec3 %ten %fzero %ten\n"
4561                                                                                                         "%mat = OpConstantComposite %m3fvec3 %vec %vec %vec"));
4562         cases.push_back(CaseParameter("struct",                 "%m2vec3 = OpTypeMatrix %fvec3 2\n"
4563                                                                                                         "%struct = OpTypeStruct %i32 %f32 %fvec3 %m2vec3\n"
4564                                                                                                         "%fzero = OpConstant %f32 0.\n"
4565                                                                                                         "%one = OpConstant %f32 1.\n"
4566                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4567                                                                                                         "%vec = OpConstantComposite %fvec3 %one %one %fzero\n"
4568                                                                                                         "%mat = OpConstantComposite %m2vec3 %vec %vec\n"
4569                                                                                                         "%const = OpConstantComposite %struct %zero %point5 %vec %mat"));
4570         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %u32 %f32\n"
4571                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
4572                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
4573                                                                                                         "%point5 = OpConstant %f32 0.5\n"
4574                                                                                                         "%one = OpConstant %u32 1\n"
4575                                                                                                         "%ten = OpConstant %i32 10\n"
4576                                                                                                         "%st1val = OpConstantComposite %st1 %one %point5\n"
4577                                                                                                         "%st2val = OpConstantComposite %st2 %ten %ten\n"
4578                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
4579
4580         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
4581
4582         for (size_t ndx = 0; ndx < numElements; ++ndx)
4583                 negativeFloats[ndx] = -positiveFloats[ndx];
4584
4585         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
4586         {
4587                 map<string, string>             specializations;
4588                 ComputeShaderSpec               spec;
4589
4590                 specializations["CONSTANT"] = cases[caseNdx].param;
4591                 spec.assembly = shaderTemplate.specialize(specializations);
4592                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
4593                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
4594                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4595
4596                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
4597         }
4598
4599         return group.release();
4600 }
4601
4602 // Creates a floating point number with the given exponent, and significand
4603 // bits set. It can only create normalized numbers. Only the least significant
4604 // 24 bits of the significand will be examined. The final bit of the
4605 // significand will also be ignored. This allows alignment to be written
4606 // similarly to C99 hex-floats.
4607 // For example if you wanted to write 0x1.7f34p-12 you would call
4608 // constructNormalizedFloat(-12, 0x7f3400)
4609 float constructNormalizedFloat (deInt32 exponent, deUint32 significand)
4610 {
4611         float f = 1.0f;
4612
4613         for (deInt32 idx = 0; idx < 23; ++idx)
4614         {
4615                 f += ((significand & 0x800000) == 0) ? 0.f : std::ldexp(1.0f, -(idx + 1));
4616                 significand <<= 1;
4617         }
4618
4619         return std::ldexp(f, exponent);
4620 }
4621
4622 // Compare instruction for the OpQuantizeF16 compute exact case.
4623 // Returns true if the output is what is expected from the test case.
4624 bool compareOpQuantizeF16ComputeExactCase (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4625 {
4626         if (outputAllocs.size() != 1)
4627                 return false;
4628
4629         // Only size is needed because we cannot compare Nans.
4630         size_t byteSize = expectedOutputs[0].getByteSize();
4631
4632         const float*    outputAsFloat   = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4633
4634         if (byteSize != 4*sizeof(float)) {
4635                 return false;
4636         }
4637
4638         if (*outputAsFloat != constructNormalizedFloat(8, 0x304000) &&
4639                 *outputAsFloat != constructNormalizedFloat(8, 0x300000)) {
4640                 return false;
4641         }
4642         outputAsFloat++;
4643
4644         if (*outputAsFloat != -constructNormalizedFloat(-7, 0x600000) &&
4645                 *outputAsFloat != -constructNormalizedFloat(-7, 0x604000)) {
4646                 return false;
4647         }
4648         outputAsFloat++;
4649
4650         if (*outputAsFloat != constructNormalizedFloat(2, 0x01C000) &&
4651                 *outputAsFloat != constructNormalizedFloat(2, 0x020000)) {
4652                 return false;
4653         }
4654         outputAsFloat++;
4655
4656         if (*outputAsFloat != constructNormalizedFloat(1, 0xFFC000) &&
4657                 *outputAsFloat != constructNormalizedFloat(2, 0x000000)) {
4658                 return false;
4659         }
4660
4661         return true;
4662 }
4663
4664 // Checks that every output from a test-case is a float NaN.
4665 bool compareNan (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
4666 {
4667         if (outputAllocs.size() != 1)
4668                 return false;
4669
4670         // Only size is needed because we cannot compare Nans.
4671         size_t byteSize = expectedOutputs[0].getByteSize();
4672
4673         const float* const      output_as_float = static_cast<const float*>(outputAllocs[0]->getHostPtr());
4674
4675         for (size_t idx = 0; idx < byteSize / sizeof(float); ++idx)
4676         {
4677                 if (!deFloatIsNaN(output_as_float[idx]))
4678                 {
4679                         return false;
4680                 }
4681         }
4682
4683         return true;
4684 }
4685
4686 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
4687 tcu::TestCaseGroup* createOpQuantizeToF16Group (tcu::TestContext& testCtx)
4688 {
4689         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opquantize", "Tests the OpQuantizeToF16 instruction"));
4690
4691         const std::string shader (
4692                 string(getComputeAsmShaderPreamble()) +
4693
4694                 "OpSource GLSL 430\n"
4695                 "OpName %main           \"main\"\n"
4696                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4697
4698                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4699
4700                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4701
4702                 "%id        = OpVariable %uvec3ptr Input\n"
4703                 "%zero      = OpConstant %i32 0\n"
4704
4705                 "%main      = OpFunction %void None %voidf\n"
4706                 "%label     = OpLabel\n"
4707                 "%idval     = OpLoad %uvec3 %id\n"
4708                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4709                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
4710                 "%inval     = OpLoad %f32 %inloc\n"
4711                 "%quant     = OpQuantizeToF16 %f32 %inval\n"
4712                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4713                 "             OpStore %outloc %quant\n"
4714                 "             OpReturn\n"
4715                 "             OpFunctionEnd\n");
4716
4717         {
4718                 ComputeShaderSpec       spec;
4719                 const deUint32          numElements             = 100;
4720                 vector<float>           infinities;
4721                 vector<float>           results;
4722
4723                 infinities.reserve(numElements);
4724                 results.reserve(numElements);
4725
4726                 for (size_t idx = 0; idx < numElements; ++idx)
4727                 {
4728                         switch(idx % 4)
4729                         {
4730                                 case 0:
4731                                         infinities.push_back(std::numeric_limits<float>::infinity());
4732                                         results.push_back(std::numeric_limits<float>::infinity());
4733                                         break;
4734                                 case 1:
4735                                         infinities.push_back(-std::numeric_limits<float>::infinity());
4736                                         results.push_back(-std::numeric_limits<float>::infinity());
4737                                         break;
4738                                 case 2:
4739                                         infinities.push_back(std::ldexp(1.0f, 16));
4740                                         results.push_back(std::numeric_limits<float>::infinity());
4741                                         break;
4742                                 case 3:
4743                                         infinities.push_back(std::ldexp(-1.0f, 32));
4744                                         results.push_back(-std::numeric_limits<float>::infinity());
4745                                         break;
4746                         }
4747                 }
4748
4749                 spec.assembly = shader;
4750                 spec.inputs.push_back(BufferSp(new Float32Buffer(infinities)));
4751                 spec.outputs.push_back(BufferSp(new Float32Buffer(results)));
4752                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4753
4754                 group->addChild(new SpvAsmComputeShaderCase(
4755                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4756         }
4757
4758         {
4759                 ComputeShaderSpec       spec;
4760                 vector<float>           nans;
4761                 const deUint32          numElements             = 100;
4762
4763                 nans.reserve(numElements);
4764
4765                 for (size_t idx = 0; idx < numElements; ++idx)
4766                 {
4767                         if (idx % 2 == 0)
4768                         {
4769                                 nans.push_back(std::numeric_limits<float>::quiet_NaN());
4770                         }
4771                         else
4772                         {
4773                                 nans.push_back(-std::numeric_limits<float>::quiet_NaN());
4774                         }
4775                 }
4776
4777                 spec.assembly = shader;
4778                 spec.inputs.push_back(BufferSp(new Float32Buffer(nans)));
4779                 spec.outputs.push_back(BufferSp(new Float32Buffer(nans)));
4780                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4781                 spec.verifyIO = &compareNan;
4782
4783                 group->addChild(new SpvAsmComputeShaderCase(
4784                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
4785         }
4786
4787         {
4788                 ComputeShaderSpec       spec;
4789                 vector<float>           small;
4790                 vector<float>           zeros;
4791                 const deUint32          numElements             = 100;
4792
4793                 small.reserve(numElements);
4794                 zeros.reserve(numElements);
4795
4796                 for (size_t idx = 0; idx < numElements; ++idx)
4797                 {
4798                         switch(idx % 6)
4799                         {
4800                                 case 0:
4801                                         small.push_back(0.f);
4802                                         zeros.push_back(0.f);
4803                                         break;
4804                                 case 1:
4805                                         small.push_back(-0.f);
4806                                         zeros.push_back(-0.f);
4807                                         break;
4808                                 case 2:
4809                                         small.push_back(std::ldexp(1.0f, -16));
4810                                         zeros.push_back(0.f);
4811                                         break;
4812                                 case 3:
4813                                         small.push_back(std::ldexp(-1.0f, -32));
4814                                         zeros.push_back(-0.f);
4815                                         break;
4816                                 case 4:
4817                                         small.push_back(std::ldexp(1.0f, -127));
4818                                         zeros.push_back(0.f);
4819                                         break;
4820                                 case 5:
4821                                         small.push_back(-std::ldexp(1.0f, -128));
4822                                         zeros.push_back(-0.f);
4823                                         break;
4824                         }
4825                 }
4826
4827                 spec.assembly = shader;
4828                 spec.inputs.push_back(BufferSp(new Float32Buffer(small)));
4829                 spec.outputs.push_back(BufferSp(new Float32Buffer(zeros)));
4830                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4831
4832                 group->addChild(new SpvAsmComputeShaderCase(
4833                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
4834         }
4835
4836         {
4837                 ComputeShaderSpec       spec;
4838                 vector<float>           exact;
4839                 const deUint32          numElements             = 200;
4840
4841                 exact.reserve(numElements);
4842
4843                 for (size_t idx = 0; idx < numElements; ++idx)
4844                         exact.push_back(static_cast<float>(static_cast<int>(idx) - 100));
4845
4846                 spec.assembly = shader;
4847                 spec.inputs.push_back(BufferSp(new Float32Buffer(exact)));
4848                 spec.outputs.push_back(BufferSp(new Float32Buffer(exact)));
4849                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4850
4851                 group->addChild(new SpvAsmComputeShaderCase(
4852                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
4853         }
4854
4855         {
4856                 ComputeShaderSpec       spec;
4857                 vector<float>           inputs;
4858                 const deUint32          numElements             = 4;
4859
4860                 inputs.push_back(constructNormalizedFloat(8,    0x300300));
4861                 inputs.push_back(-constructNormalizedFloat(-7,  0x600800));
4862                 inputs.push_back(constructNormalizedFloat(2,    0x01E000));
4863                 inputs.push_back(constructNormalizedFloat(1,    0xFFE000));
4864
4865                 spec.assembly = shader;
4866                 spec.verifyIO = &compareOpQuantizeF16ComputeExactCase;
4867                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4868                 spec.outputs.push_back(BufferSp(new Float32Buffer(inputs)));
4869                 spec.numWorkGroups = IVec3(numElements, 1, 1);
4870
4871                 group->addChild(new SpvAsmComputeShaderCase(
4872                         testCtx, "rounded", "Check that are rounded when needed", spec));
4873         }
4874
4875         return group.release();
4876 }
4877
4878 tcu::TestCaseGroup* createSpecConstantOpQuantizeToF16Group (tcu::TestContext& testCtx)
4879 {
4880         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opspecconstantop_opquantize", "Tests the OpQuantizeToF16 opcode for the OpSpecConstantOp instruction"));
4881
4882         const std::string shader (
4883                 string(getComputeAsmShaderPreamble()) +
4884
4885                 "OpName %main           \"main\"\n"
4886                 "OpName %id             \"gl_GlobalInvocationID\"\n"
4887
4888                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
4889
4890                 "OpDecorate %sc_0  SpecId 0\n"
4891                 "OpDecorate %sc_1  SpecId 1\n"
4892                 "OpDecorate %sc_2  SpecId 2\n"
4893                 "OpDecorate %sc_3  SpecId 3\n"
4894                 "OpDecorate %sc_4  SpecId 4\n"
4895                 "OpDecorate %sc_5  SpecId 5\n"
4896
4897                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
4898
4899                 "%id        = OpVariable %uvec3ptr Input\n"
4900                 "%zero      = OpConstant %i32 0\n"
4901                 "%c_u32_6   = OpConstant %u32 6\n"
4902
4903                 "%sc_0      = OpSpecConstant %f32 0.\n"
4904                 "%sc_1      = OpSpecConstant %f32 0.\n"
4905                 "%sc_2      = OpSpecConstant %f32 0.\n"
4906                 "%sc_3      = OpSpecConstant %f32 0.\n"
4907                 "%sc_4      = OpSpecConstant %f32 0.\n"
4908                 "%sc_5      = OpSpecConstant %f32 0.\n"
4909
4910                 "%sc_0_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_0\n"
4911                 "%sc_1_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_1\n"
4912                 "%sc_2_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_2\n"
4913                 "%sc_3_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_3\n"
4914                 "%sc_4_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_4\n"
4915                 "%sc_5_quant = OpSpecConstantOp %f32 QuantizeToF16 %sc_5\n"
4916
4917                 "%main      = OpFunction %void None %voidf\n"
4918                 "%label     = OpLabel\n"
4919                 "%idval     = OpLoad %uvec3 %id\n"
4920                 "%x         = OpCompositeExtract %u32 %idval 0\n"
4921                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
4922                 "%selector  = OpUMod %u32 %x %c_u32_6\n"
4923                 "            OpSelectionMerge %exit None\n"
4924                 "            OpSwitch %selector %exit 0 %case0 1 %case1 2 %case2 3 %case3 4 %case4 5 %case5\n"
4925
4926                 "%case0     = OpLabel\n"
4927                 "             OpStore %outloc %sc_0_quant\n"
4928                 "             OpBranch %exit\n"
4929
4930                 "%case1     = OpLabel\n"
4931                 "             OpStore %outloc %sc_1_quant\n"
4932                 "             OpBranch %exit\n"
4933
4934                 "%case2     = OpLabel\n"
4935                 "             OpStore %outloc %sc_2_quant\n"
4936                 "             OpBranch %exit\n"
4937
4938                 "%case3     = OpLabel\n"
4939                 "             OpStore %outloc %sc_3_quant\n"
4940                 "             OpBranch %exit\n"
4941
4942                 "%case4     = OpLabel\n"
4943                 "             OpStore %outloc %sc_4_quant\n"
4944                 "             OpBranch %exit\n"
4945
4946                 "%case5     = OpLabel\n"
4947                 "             OpStore %outloc %sc_5_quant\n"
4948                 "             OpBranch %exit\n"
4949
4950                 "%exit      = OpLabel\n"
4951                 "             OpReturn\n"
4952
4953                 "             OpFunctionEnd\n");
4954
4955         {
4956                 ComputeShaderSpec       spec;
4957                 const deUint8           numCases        = 4;
4958                 vector<float>           inputs          (numCases, 0.f);
4959                 vector<float>           outputs;
4960
4961                 spec.assembly           = shader;
4962                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4963
4964                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::numeric_limits<float>::infinity()));
4965                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::numeric_limits<float>::infinity()));
4966                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, 16)));
4967                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, 32)));
4968
4969                 outputs.push_back(std::numeric_limits<float>::infinity());
4970                 outputs.push_back(-std::numeric_limits<float>::infinity());
4971                 outputs.push_back(std::numeric_limits<float>::infinity());
4972                 outputs.push_back(-std::numeric_limits<float>::infinity());
4973
4974                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4975                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4976
4977                 group->addChild(new SpvAsmComputeShaderCase(
4978                         testCtx, "infinities", "Check that infinities propagated and created", spec));
4979         }
4980
4981         {
4982                 ComputeShaderSpec       spec;
4983                 const deUint8           numCases        = 2;
4984                 vector<float>           inputs          (numCases, 0.f);
4985                 vector<float>           outputs;
4986
4987                 spec.assembly           = shader;
4988                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
4989                 spec.verifyIO           = &compareNan;
4990
4991                 outputs.push_back(std::numeric_limits<float>::quiet_NaN());
4992                 outputs.push_back(-std::numeric_limits<float>::quiet_NaN());
4993
4994                 for (deUint8 idx = 0; idx < numCases; ++idx)
4995                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
4996
4997                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
4998                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
4999
5000                 group->addChild(new SpvAsmComputeShaderCase(
5001                         testCtx, "propagated_nans", "Check that nans are propagated", spec));
5002         }
5003
5004         {
5005                 ComputeShaderSpec       spec;
5006                 const deUint8           numCases        = 6;
5007                 vector<float>           inputs          (numCases, 0.f);
5008                 vector<float>           outputs;
5009
5010                 spec.assembly           = shader;
5011                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
5012
5013                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(0.f));
5014                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-0.f));
5015                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -16)));
5016                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(-1.0f, -32)));
5017                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(std::ldexp(1.0f, -127)));
5018                 spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(-std::ldexp(1.0f, -128)));
5019
5020                 outputs.push_back(0.f);
5021                 outputs.push_back(-0.f);
5022                 outputs.push_back(0.f);
5023                 outputs.push_back(-0.f);
5024                 outputs.push_back(0.f);
5025                 outputs.push_back(-0.f);
5026
5027                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5028                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5029
5030                 group->addChild(new SpvAsmComputeShaderCase(
5031                         testCtx, "flush_to_zero", "Check that values are zeroed correctly", spec));
5032         }
5033
5034         {
5035                 ComputeShaderSpec       spec;
5036                 const deUint8           numCases        = 6;
5037                 vector<float>           inputs          (numCases, 0.f);
5038                 vector<float>           outputs;
5039
5040                 spec.assembly           = shader;
5041                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
5042
5043                 for (deUint8 idx = 0; idx < 6; ++idx)
5044                 {
5045                         const float f = static_cast<float>(idx * 10 - 30) / 4.f;
5046                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(f));
5047                         outputs.push_back(f);
5048                 }
5049
5050                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5051                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5052
5053                 group->addChild(new SpvAsmComputeShaderCase(
5054                         testCtx, "exact", "Check that values exactly preserved where appropriate", spec));
5055         }
5056
5057         {
5058                 ComputeShaderSpec       spec;
5059                 const deUint8           numCases        = 4;
5060                 vector<float>           inputs          (numCases, 0.f);
5061                 vector<float>           outputs;
5062
5063                 spec.assembly           = shader;
5064                 spec.numWorkGroups      = IVec3(numCases, 1, 1);
5065                 spec.verifyIO           = &compareOpQuantizeF16ComputeExactCase;
5066
5067                 outputs.push_back(constructNormalizedFloat(8, 0x300300));
5068                 outputs.push_back(-constructNormalizedFloat(-7, 0x600800));
5069                 outputs.push_back(constructNormalizedFloat(2, 0x01E000));
5070                 outputs.push_back(constructNormalizedFloat(1, 0xFFE000));
5071
5072                 for (deUint8 idx = 0; idx < numCases; ++idx)
5073                         spec.specConstants.append<deInt32>(bitwiseCast<deUint32>(outputs[idx]));
5074
5075                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputs)));
5076                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputs)));
5077
5078                 group->addChild(new SpvAsmComputeShaderCase(
5079                         testCtx, "rounded", "Check that are rounded when needed", spec));
5080         }
5081
5082         return group.release();
5083 }
5084
5085 // Checks that constant null/composite values can be used in computation.
5086 tcu::TestCaseGroup* createOpConstantUsageGroup (tcu::TestContext& testCtx)
5087 {
5088         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantnullcomposite", "Spotcheck the OpConstantNull & OpConstantComposite instruction"));
5089         ComputeShaderSpec                               spec;
5090         de::Random                                              rnd                             (deStringHash(group->getName()));
5091         const int                                               numElements             = 100;
5092         vector<float>                                   positiveFloats  (numElements, 0);
5093         vector<float>                                   negativeFloats  (numElements, 0);
5094
5095         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
5096
5097         for (size_t ndx = 0; ndx < numElements; ++ndx)
5098                 negativeFloats[ndx] = -positiveFloats[ndx];
5099
5100         spec.assembly =
5101                 "OpCapability Shader\n"
5102                 "%std450 = OpExtInstImport \"GLSL.std.450\"\n"
5103                 "OpMemoryModel Logical GLSL450\n"
5104                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5105                 "OpExecutionMode %main LocalSize 1 1 1\n"
5106
5107                 "OpSource GLSL 430\n"
5108                 "OpName %main           \"main\"\n"
5109                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5110
5111                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5112
5113                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5114
5115                 "%fmat      = OpTypeMatrix %fvec3 3\n"
5116                 "%ten       = OpConstant %u32 10\n"
5117                 "%f32arr10  = OpTypeArray %f32 %ten\n"
5118                 "%fst       = OpTypeStruct %f32 %f32\n"
5119
5120                 + string(getComputeAsmInputOutputBuffer()) +
5121
5122                 "%id        = OpVariable %uvec3ptr Input\n"
5123                 "%zero      = OpConstant %i32 0\n"
5124
5125                 // Create a bunch of null values
5126                 "%unull     = OpConstantNull %u32\n"
5127                 "%fnull     = OpConstantNull %f32\n"
5128                 "%vnull     = OpConstantNull %fvec3\n"
5129                 "%mnull     = OpConstantNull %fmat\n"
5130                 "%anull     = OpConstantNull %f32arr10\n"
5131                 "%snull     = OpConstantComposite %fst %fnull %fnull\n"
5132
5133                 "%main      = OpFunction %void None %voidf\n"
5134                 "%label     = OpLabel\n"
5135                 "%idval     = OpLoad %uvec3 %id\n"
5136                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5137                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5138                 "%inval     = OpLoad %f32 %inloc\n"
5139                 "%neg       = OpFNegate %f32 %inval\n"
5140
5141                 // Get the abs() of (a certain element of) those null values
5142                 "%unull_cov = OpConvertUToF %f32 %unull\n"
5143                 "%unull_abs = OpExtInst %f32 %std450 FAbs %unull_cov\n"
5144                 "%fnull_abs = OpExtInst %f32 %std450 FAbs %fnull\n"
5145                 "%vnull_0   = OpCompositeExtract %f32 %vnull 0\n"
5146                 "%vnull_abs = OpExtInst %f32 %std450 FAbs %vnull_0\n"
5147                 "%mnull_12  = OpCompositeExtract %f32 %mnull 1 2\n"
5148                 "%mnull_abs = OpExtInst %f32 %std450 FAbs %mnull_12\n"
5149                 "%anull_3   = OpCompositeExtract %f32 %anull 3\n"
5150                 "%anull_abs = OpExtInst %f32 %std450 FAbs %anull_3\n"
5151                 "%snull_1   = OpCompositeExtract %f32 %snull 1\n"
5152                 "%snull_abs = OpExtInst %f32 %std450 FAbs %snull_1\n"
5153
5154                 // Add them all
5155                 "%add1      = OpFAdd %f32 %neg  %unull_abs\n"
5156                 "%add2      = OpFAdd %f32 %add1 %fnull_abs\n"
5157                 "%add3      = OpFAdd %f32 %add2 %vnull_abs\n"
5158                 "%add4      = OpFAdd %f32 %add3 %mnull_abs\n"
5159                 "%add5      = OpFAdd %f32 %add4 %anull_abs\n"
5160                 "%final     = OpFAdd %f32 %add5 %snull_abs\n"
5161
5162                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5163                 "             OpStore %outloc %final\n" // write to output
5164                 "             OpReturn\n"
5165                 "             OpFunctionEnd\n";
5166         spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
5167         spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
5168         spec.numWorkGroups = IVec3(numElements, 1, 1);
5169
5170         group->addChild(new SpvAsmComputeShaderCase(testCtx, "spotcheck", "Check that values constructed via OpConstantNull & OpConstantComposite can be used", spec));
5171
5172         return group.release();
5173 }
5174
5175 // Assembly code used for testing loop control is based on GLSL source code:
5176 // #version 430
5177 //
5178 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5179 //   float elements[];
5180 // } input_data;
5181 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5182 //   float elements[];
5183 // } output_data;
5184 //
5185 // void main() {
5186 //   uint x = gl_GlobalInvocationID.x;
5187 //   output_data.elements[x] = input_data.elements[x];
5188 //   for (uint i = 0; i < 4; ++i)
5189 //     output_data.elements[x] += 1.f;
5190 // }
5191 tcu::TestCaseGroup* createLoopControlGroup (tcu::TestContext& testCtx)
5192 {
5193         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "loop_control", "Tests loop control cases"));
5194         vector<CaseParameter>                   cases;
5195         de::Random                                              rnd                             (deStringHash(group->getName()));
5196         const int                                               numElements             = 100;
5197         vector<float>                                   inputFloats             (numElements, 0);
5198         vector<float>                                   outputFloats    (numElements, 0);
5199         const StringTemplate                    shaderTemplate  (
5200                 string(getComputeAsmShaderPreamble()) +
5201
5202                 "OpSource GLSL 430\n"
5203                 "OpName %main \"main\"\n"
5204                 "OpName %id \"gl_GlobalInvocationID\"\n"
5205
5206                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5207
5208                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5209
5210                 "%u32ptr      = OpTypePointer Function %u32\n"
5211
5212                 "%id          = OpVariable %uvec3ptr Input\n"
5213                 "%zero        = OpConstant %i32 0\n"
5214                 "%uzero       = OpConstant %u32 0\n"
5215                 "%one         = OpConstant %i32 1\n"
5216                 "%constf1     = OpConstant %f32 1.0\n"
5217                 "%four        = OpConstant %u32 4\n"
5218
5219                 "%main        = OpFunction %void None %voidf\n"
5220                 "%entry       = OpLabel\n"
5221                 "%i           = OpVariable %u32ptr Function\n"
5222                 "               OpStore %i %uzero\n"
5223
5224                 "%idval       = OpLoad %uvec3 %id\n"
5225                 "%x           = OpCompositeExtract %u32 %idval 0\n"
5226                 "%inloc       = OpAccessChain %f32ptr %indata %zero %x\n"
5227                 "%inval       = OpLoad %f32 %inloc\n"
5228                 "%outloc      = OpAccessChain %f32ptr %outdata %zero %x\n"
5229                 "               OpStore %outloc %inval\n"
5230                 "               OpBranch %loop_entry\n"
5231
5232                 "%loop_entry  = OpLabel\n"
5233                 "%i_val       = OpLoad %u32 %i\n"
5234                 "%cmp_lt      = OpULessThan %bool %i_val %four\n"
5235                 "               OpLoopMerge %loop_merge %loop_body ${CONTROL}\n"
5236                 "               OpBranchConditional %cmp_lt %loop_body %loop_merge\n"
5237                 "%loop_body   = OpLabel\n"
5238                 "%outval      = OpLoad %f32 %outloc\n"
5239                 "%addf1       = OpFAdd %f32 %outval %constf1\n"
5240                 "               OpStore %outloc %addf1\n"
5241                 "%new_i       = OpIAdd %u32 %i_val %one\n"
5242                 "               OpStore %i %new_i\n"
5243                 "               OpBranch %loop_entry\n"
5244                 "%loop_merge  = OpLabel\n"
5245                 "               OpReturn\n"
5246                 "               OpFunctionEnd\n");
5247
5248         cases.push_back(CaseParameter("none",                           "None"));
5249         cases.push_back(CaseParameter("unroll",                         "Unroll"));
5250         cases.push_back(CaseParameter("dont_unroll",            "DontUnroll"));
5251
5252         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5253
5254         for (size_t ndx = 0; ndx < numElements; ++ndx)
5255                 outputFloats[ndx] = inputFloats[ndx] + 4.f;
5256
5257         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5258         {
5259                 map<string, string>             specializations;
5260                 ComputeShaderSpec               spec;
5261
5262                 specializations["CONTROL"] = cases[caseNdx].param;
5263                 spec.assembly = shaderTemplate.specialize(specializations);
5264                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5265                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5266                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5267
5268                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5269         }
5270
5271         group->addChild(new SpvAsmLoopControlDependencyLengthCase(testCtx, "dependency_length", "dependency_length"));
5272         group->addChild(new SpvAsmLoopControlDependencyInfiniteCase(testCtx, "dependency_infinite", "dependency_infinite"));
5273
5274         return group.release();
5275 }
5276
5277 // Assembly code used for testing selection control is based on GLSL source code:
5278 // #version 430
5279 //
5280 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5281 //   float elements[];
5282 // } input_data;
5283 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5284 //   float elements[];
5285 // } output_data;
5286 //
5287 // void main() {
5288 //   uint x = gl_GlobalInvocationID.x;
5289 //   float val = input_data.elements[x];
5290 //   if (val > 10.f)
5291 //     output_data.elements[x] = val + 1.f;
5292 //   else
5293 //     output_data.elements[x] = val - 1.f;
5294 // }
5295 tcu::TestCaseGroup* createSelectionControlGroup (tcu::TestContext& testCtx)
5296 {
5297         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "selection_control", "Tests selection control cases"));
5298         vector<CaseParameter>                   cases;
5299         de::Random                                              rnd                             (deStringHash(group->getName()));
5300         const int                                               numElements             = 100;
5301         vector<float>                                   inputFloats             (numElements, 0);
5302         vector<float>                                   outputFloats    (numElements, 0);
5303         const StringTemplate                    shaderTemplate  (
5304                 string(getComputeAsmShaderPreamble()) +
5305
5306                 "OpSource GLSL 430\n"
5307                 "OpName %main \"main\"\n"
5308                 "OpName %id \"gl_GlobalInvocationID\"\n"
5309
5310                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5311
5312                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5313
5314                 "%id       = OpVariable %uvec3ptr Input\n"
5315                 "%zero     = OpConstant %i32 0\n"
5316                 "%constf1  = OpConstant %f32 1.0\n"
5317                 "%constf10 = OpConstant %f32 10.0\n"
5318
5319                 "%main     = OpFunction %void None %voidf\n"
5320                 "%entry    = OpLabel\n"
5321                 "%idval    = OpLoad %uvec3 %id\n"
5322                 "%x        = OpCompositeExtract %u32 %idval 0\n"
5323                 "%inloc    = OpAccessChain %f32ptr %indata %zero %x\n"
5324                 "%inval    = OpLoad %f32 %inloc\n"
5325                 "%outloc   = OpAccessChain %f32ptr %outdata %zero %x\n"
5326                 "%cmp_gt   = OpFOrdGreaterThan %bool %inval %constf10\n"
5327
5328                 "            OpSelectionMerge %if_end ${CONTROL}\n"
5329                 "            OpBranchConditional %cmp_gt %if_true %if_false\n"
5330                 "%if_true  = OpLabel\n"
5331                 "%addf1    = OpFAdd %f32 %inval %constf1\n"
5332                 "            OpStore %outloc %addf1\n"
5333                 "            OpBranch %if_end\n"
5334                 "%if_false = OpLabel\n"
5335                 "%subf1    = OpFSub %f32 %inval %constf1\n"
5336                 "            OpStore %outloc %subf1\n"
5337                 "            OpBranch %if_end\n"
5338                 "%if_end   = OpLabel\n"
5339                 "            OpReturn\n"
5340                 "            OpFunctionEnd\n");
5341
5342         cases.push_back(CaseParameter("none",                                   "None"));
5343         cases.push_back(CaseParameter("flatten",                                "Flatten"));
5344         cases.push_back(CaseParameter("dont_flatten",                   "DontFlatten"));
5345         cases.push_back(CaseParameter("flatten_dont_flatten",   "DontFlatten|Flatten"));
5346
5347         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5348
5349         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5350         floorAll(inputFloats);
5351
5352         for (size_t ndx = 0; ndx < numElements; ++ndx)
5353                 outputFloats[ndx] = inputFloats[ndx] + (inputFloats[ndx] > 10.f ? 1.f : -1.f);
5354
5355         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5356         {
5357                 map<string, string>             specializations;
5358                 ComputeShaderSpec               spec;
5359
5360                 specializations["CONTROL"] = cases[caseNdx].param;
5361                 spec.assembly = shaderTemplate.specialize(specializations);
5362                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5363                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5364                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5365
5366                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5367         }
5368
5369         return group.release();
5370 }
5371
5372 void getOpNameAbuseCases (vector<CaseParameter> &abuseCases)
5373 {
5374         // Generate a long name.
5375         std::string longname;
5376         longname.resize(65535, 'k'); // max string literal, spir-v 2.17
5377
5378         // Some bad names, abusing utf-8 encoding. This may also cause problems
5379         // with the logs.
5380         // 1. Various illegal code points in utf-8
5381         std::string utf8illegal =
5382                 "Illegal bytes in UTF-8: "
5383                 "\xc0 \xc1 \xf5 \xf6 \xf7 \xf8 \xf9 \xfa \xfb \xfc \xfd \xfe \xff"
5384                 "illegal surrogates: \xed\xad\xbf \xed\xbe\x80";
5385
5386         // 2. Zero encoded as overlong, not exactly legal but often supported to differentiate from terminating zero
5387         std::string utf8nul = "UTF-8 encoded nul \xC0\x80 (should not end name)";
5388
5389         // 3. Some overlong encodings
5390         std::string utf8overlong =
5391                 "UTF-8 overlong \xF0\x82\x82\xAC \xfc\x83\xbf\xbf\xbf\xbf \xf8\x87\xbf\xbf\xbf "
5392                 "\xf0\x8f\xbf\xbf";
5393
5394         // 4. Internet "zalgo" meme "bleeding text"
5395         std::string utf8zalgo =
5396                 "\x56\xcc\xb5\xcc\x85\xcc\x94\xcc\x88\xcd\x8a\xcc\x91\xcc\x88\xcd\x91\xcc\x83\xcd\x82"
5397                 "\xcc\x83\xcd\x90\xcc\x8a\xcc\x92\xcc\x92\xcd\x8b\xcc\x94\xcd\x9d\xcc\x98\xcc\xab\xcc"
5398                 "\xae\xcc\xa9\xcc\xad\xcc\x97\xcc\xb0\x75\xcc\xb6\xcc\xbe\xcc\x80\xcc\x82\xcc\x84\xcd"
5399                 "\x84\xcc\x90\xcd\x86\xcc\x9a\xcd\x84\xcc\x9b\xcd\x86\xcd\x92\xcc\x9a\xcd\x99\xcd\x99"
5400                 "\xcc\xbb\xcc\x98\xcd\x8e\xcd\x88\xcd\x9a\xcc\xa6\xcc\x9c\xcc\xab\xcc\x99\xcd\x94\xcd"
5401                 "\x99\xcd\x95\xcc\xa5\xcc\xab\xcd\x89\x6c\xcc\xb8\xcc\x8e\xcc\x8b\xcc\x8b\xcc\x9a\xcc"
5402                 "\x8e\xcd\x9d\xcc\x80\xcc\xa1\xcc\xad\xcd\x9c\xcc\xba\xcc\x96\xcc\xb3\xcc\xa2\xcd\x8e"
5403                 "\xcc\xa2\xcd\x96\x6b\xcc\xb8\xcc\x84\xcd\x81\xcc\xbf\xcc\x8d\xcc\x89\xcc\x85\xcc\x92"
5404                 "\xcc\x84\xcc\x90\xcd\x81\xcc\x93\xcd\x90\xcd\x92\xcd\x9d\xcc\x84\xcd\x98\xcd\x9d\xcd"
5405                 "\xa0\xcd\x91\xcc\x94\xcc\xb9\xcd\x93\xcc\xa5\xcd\x87\xcc\xad\xcc\xa7\xcd\x96\xcd\x99"
5406                 "\xcc\x9d\xcc\xbc\xcd\x96\xcd\x93\xcc\x9d\xcc\x99\xcc\xa8\xcc\xb1\xcd\x85\xcc\xba\xcc"
5407                 "\xa7\x61\xcc\xb8\xcc\x8e\xcc\x81\xcd\x90\xcd\x84\xcd\x8c\xcc\x8c\xcc\x85\xcd\x86\xcc"
5408                 "\x84\xcd\x84\xcc\x90\xcc\x84\xcc\x8d\xcd\x99\xcd\x8d\xcc\xb0\xcc\xa3\xcc\xa6\xcd\x89"
5409                 "\xcd\x8d\xcd\x87\xcc\x98\xcd\x8d\xcc\xa4\xcd\x9a\xcd\x8e\xcc\xab\xcc\xb9\xcc\xac\xcc"
5410                 "\xa2\xcd\x87\xcc\xa0\xcc\xb3\xcd\x89\xcc\xb9\xcc\xa7\xcc\xa6\xcd\x89\xcd\x95\x6e\xcc"
5411                 "\xb8\xcd\x8a\xcc\x8a\xcd\x82\xcc\x9b\xcd\x81\xcd\x90\xcc\x85\xcc\x9b\xcd\x80\xcd\x91"
5412                 "\xcd\x9b\xcc\x81\xcd\x81\xcc\x9a\xcc\xb3\xcd\x9c\xcc\x9e\xcc\x9d\xcd\x99\xcc\xa2\xcd"
5413                 "\x93\xcd\x96\xcc\x97\xff";
5414
5415         // General name abuses
5416         abuseCases.push_back(CaseParameter("_has_very_long_name", longname));
5417         abuseCases.push_back(CaseParameter("_utf8_illegal", utf8illegal));
5418         abuseCases.push_back(CaseParameter("_utf8_nul", utf8nul));
5419         abuseCases.push_back(CaseParameter("_utf8_overlong", utf8overlong));
5420         abuseCases.push_back(CaseParameter("_utf8_zalgo", utf8zalgo));
5421
5422         // GL keywords
5423         abuseCases.push_back(CaseParameter("_is_gl_Position", "gl_Position"));
5424         abuseCases.push_back(CaseParameter("_is_gl_InstanceID", "gl_InstanceID"));
5425         abuseCases.push_back(CaseParameter("_is_gl_PrimitiveID", "gl_PrimitiveID"));
5426         abuseCases.push_back(CaseParameter("_is_gl_TessCoord", "gl_TessCoord"));
5427         abuseCases.push_back(CaseParameter("_is_gl_PerVertex", "gl_PerVertex"));
5428         abuseCases.push_back(CaseParameter("_is_gl_InvocationID", "gl_InvocationID"));
5429         abuseCases.push_back(CaseParameter("_is_gl_PointSize", "gl_PointSize"));
5430         abuseCases.push_back(CaseParameter("_is_gl_PointCoord", "gl_PointCoord"));
5431         abuseCases.push_back(CaseParameter("_is_gl_Layer", "gl_Layer"));
5432         abuseCases.push_back(CaseParameter("_is_gl_FragDepth", "gl_FragDepth"));
5433         abuseCases.push_back(CaseParameter("_is_gl_NumWorkGroups", "gl_NumWorkGroups"));
5434         abuseCases.push_back(CaseParameter("_is_gl_WorkGroupID", "gl_WorkGroupID"));
5435         abuseCases.push_back(CaseParameter("_is_gl_LocalInvocationID", "gl_LocalInvocationID"));
5436         abuseCases.push_back(CaseParameter("_is_gl_GlobalInvocationID", "gl_GlobalInvocationID"));
5437         abuseCases.push_back(CaseParameter("_is_gl_MaxVertexAttribs", "gl_MaxVertexAttribs"));
5438         abuseCases.push_back(CaseParameter("_is_gl_MaxViewports", "gl_MaxViewports"));
5439         abuseCases.push_back(CaseParameter("_is_gl_MaxComputeWorkGroupCount", "gl_MaxComputeWorkGroupCount"));
5440         abuseCases.push_back(CaseParameter("_is_mat3", "mat3"));
5441         abuseCases.push_back(CaseParameter("_is_volatile", "volatile"));
5442         abuseCases.push_back(CaseParameter("_is_inout", "inout"));
5443         abuseCases.push_back(CaseParameter("_is_isampler3d", "isampler3d"));
5444 }
5445
5446 tcu::TestCaseGroup* createOpNameGroup (tcu::TestContext& testCtx)
5447 {
5448         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opname", "Tests OpName cases"));
5449         de::MovePtr<tcu::TestCaseGroup> entryMainGroup  (new tcu::TestCaseGroup(testCtx, "entry_main", "OpName tests with entry main"));
5450         de::MovePtr<tcu::TestCaseGroup> entryNotGroup   (new tcu::TestCaseGroup(testCtx, "entry_rdc", "OpName tests with entry rdc"));
5451         de::MovePtr<tcu::TestCaseGroup> abuseGroup              (new tcu::TestCaseGroup(testCtx, "abuse", "OpName abuse tests"));
5452         vector<CaseParameter>                   cases;
5453         vector<CaseParameter>                   abuseCases;
5454         vector<string>                                  testFunc;
5455         de::Random                                              rnd                             (deStringHash(group->getName()));
5456         const int                                               numElements             = 128;
5457         vector<float>                                   inputFloats             (numElements, 0);
5458         vector<float>                                   outputFloats    (numElements, 0);
5459
5460         getOpNameAbuseCases(abuseCases);
5461
5462         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5463
5464         for(size_t ndx = 0; ndx < numElements; ++ndx)
5465                 outputFloats[ndx] = -inputFloats[ndx];
5466
5467         const string commonShaderHeader =
5468                 "OpCapability Shader\n"
5469                 "OpMemoryModel Logical GLSL450\n"
5470                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5471                 "OpExecutionMode %main LocalSize 1 1 1\n";
5472
5473         const string commonShaderFooter =
5474                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5475
5476                 + string(getComputeAsmInputOutputBufferTraits())
5477                 + string(getComputeAsmCommonTypes())
5478                 + string(getComputeAsmInputOutputBuffer()) +
5479
5480                 "%id        = OpVariable %uvec3ptr Input\n"
5481                 "%zero      = OpConstant %i32 0\n"
5482
5483                 "%func      = OpFunction %void None %voidf\n"
5484                 "%5         = OpLabel\n"
5485                 "             OpReturn\n"
5486                 "             OpFunctionEnd\n"
5487
5488                 "%main      = OpFunction %void None %voidf\n"
5489                 "%entry     = OpLabel\n"
5490                 "%7         = OpFunctionCall %void %func\n"
5491
5492                 "%idval     = OpLoad %uvec3 %id\n"
5493                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5494
5495                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5496                 "%inval     = OpLoad %f32 %inloc\n"
5497                 "%neg       = OpFNegate %f32 %inval\n"
5498                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5499                 "             OpStore %outloc %neg\n"
5500
5501                 "             OpReturn\n"
5502                 "             OpFunctionEnd\n";
5503
5504         const StringTemplate shaderTemplate (
5505                 "OpCapability Shader\n"
5506                 "OpMemoryModel Logical GLSL450\n"
5507                 "OpEntryPoint GLCompute %main \"${ENTRY}\" %id\n"
5508                 "OpExecutionMode %main LocalSize 1 1 1\n"
5509                 "OpName %${ID} \"${NAME}\"\n" +
5510                 commonShaderFooter);
5511
5512         const std::string multipleNames =
5513                 commonShaderHeader +
5514                 "OpName %main \"to_be\"\n"
5515                 "OpName %id   \"or_not\"\n"
5516                 "OpName %main \"to_be\"\n"
5517                 "OpName %main \"makes_no\"\n"
5518                 "OpName %func \"difference\"\n"
5519                 "OpName %5    \"to_me\"\n" +
5520                 commonShaderFooter;
5521
5522         {
5523                 ComputeShaderSpec       spec;
5524
5525                 spec.assembly           = multipleNames;
5526                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5527                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5528                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5529
5530                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "main_has_multiple_names", "multiple_names", spec));
5531         }
5532
5533         const std::string everythingNamed =
5534                 commonShaderHeader +
5535                 "OpName %main   \"name1\"\n"
5536                 "OpName %id     \"name2\"\n"
5537                 "OpName %zero   \"name3\"\n"
5538                 "OpName %entry  \"name4\"\n"
5539                 "OpName %func   \"name5\"\n"
5540                 "OpName %5      \"name6\"\n"
5541                 "OpName %7      \"name7\"\n"
5542                 "OpName %idval  \"name8\"\n"
5543                 "OpName %inloc  \"name9\"\n"
5544                 "OpName %inval  \"name10\"\n"
5545                 "OpName %neg    \"name11\"\n"
5546                 "OpName %outloc \"name12\"\n"+
5547                 commonShaderFooter;
5548         {
5549                 ComputeShaderSpec       spec;
5550
5551                 spec.assembly           = everythingNamed;
5552                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5553                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5554                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5555
5556                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named", "everything_named", spec));
5557         }
5558
5559         const std::string everythingNamedTheSame =
5560                 commonShaderHeader +
5561                 "OpName %main   \"the_same\"\n"
5562                 "OpName %id     \"the_same\"\n"
5563                 "OpName %zero   \"the_same\"\n"
5564                 "OpName %entry  \"the_same\"\n"
5565                 "OpName %func   \"the_same\"\n"
5566                 "OpName %5      \"the_same\"\n"
5567                 "OpName %7      \"the_same\"\n"
5568                 "OpName %idval  \"the_same\"\n"
5569                 "OpName %inloc  \"the_same\"\n"
5570                 "OpName %inval  \"the_same\"\n"
5571                 "OpName %neg    \"the_same\"\n"
5572                 "OpName %outloc \"the_same\"\n"+
5573                 commonShaderFooter;
5574         {
5575                 ComputeShaderSpec       spec;
5576
5577                 spec.assembly           = everythingNamedTheSame;
5578                 spec.numWorkGroups      = IVec3(numElements, 1, 1);
5579                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5580                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5581
5582                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5583         }
5584
5585         // main_is_...
5586         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5587         {
5588                 map<string, string>     specializations;
5589                 ComputeShaderSpec       spec;
5590
5591                 specializations["ENTRY"]        = "main";
5592                 specializations["ID"]           = "main";
5593                 specializations["NAME"]         = abuseCases[ndx].param;
5594                 spec.assembly                           = shaderTemplate.specialize(specializations);
5595                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5596                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5597                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5598
5599                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("main") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5600         }
5601
5602         // x_is_....
5603         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5604         {
5605                 map<string, string>     specializations;
5606                 ComputeShaderSpec       spec;
5607
5608                 specializations["ENTRY"]        = "main";
5609                 specializations["ID"]           = "x";
5610                 specializations["NAME"]         = abuseCases[ndx].param;
5611                 spec.assembly                           = shaderTemplate.specialize(specializations);
5612                 spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5613                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5614                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5615
5616                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5617         }
5618
5619         cases.push_back(CaseParameter("_is_main", "main"));
5620         cases.push_back(CaseParameter("_is_not_main", "not_main"));
5621         testFunc.push_back("main");
5622         testFunc.push_back("func");
5623
5624         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5625         {
5626                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5627                 {
5628                         map<string, string>     specializations;
5629                         ComputeShaderSpec       spec;
5630
5631                         specializations["ENTRY"]        = "main";
5632                         specializations["ID"]           = testFunc[fNdx];
5633                         specializations["NAME"]         = cases[ndx].param;
5634                         spec.assembly                           = shaderTemplate.specialize(specializations);
5635                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5636                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5637                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5638
5639                         entryMainGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5640                 }
5641         }
5642
5643         cases.push_back(CaseParameter("_is_entry", "rdc"));
5644
5645         for(size_t fNdx = 0; fNdx < testFunc.size(); ++fNdx)
5646         {
5647                 for(size_t ndx = 0; ndx < cases.size(); ++ndx)
5648                 {
5649                         map<string, string>     specializations;
5650                         ComputeShaderSpec       spec;
5651
5652                         specializations["ENTRY"]        = "rdc";
5653                         specializations["ID"]           = testFunc[fNdx];
5654                         specializations["NAME"]         = cases[ndx].param;
5655                         spec.assembly                           = shaderTemplate.specialize(specializations);
5656                         spec.numWorkGroups                      = IVec3(numElements, 1, 1);
5657                         spec.entryPoint                         = "rdc";
5658                         spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5659                         spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5660
5661                         entryNotGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (testFunc[fNdx] + cases[ndx].name).c_str(), cases[ndx].name, spec));
5662                 }
5663         }
5664
5665         group->addChild(entryMainGroup.release());
5666         group->addChild(entryNotGroup.release());
5667         group->addChild(abuseGroup.release());
5668
5669         return group.release();
5670 }
5671
5672 tcu::TestCaseGroup* createOpMemberNameGroup (tcu::TestContext& testCtx)
5673 {
5674         de::MovePtr<tcu::TestCaseGroup> group(new tcu::TestCaseGroup(testCtx, "opmembername", "Tests OpMemberName cases"));
5675         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "abuse", "OpMemberName abuse tests"));
5676         vector<CaseParameter>                   abuseCases;
5677         vector<string>                                  testFunc;
5678         de::Random                                              rnd(deStringHash(group->getName()));
5679         const int                                               numElements = 128;
5680         vector<float>                                   inputFloats(numElements, 0);
5681         vector<float>                                   outputFloats(numElements, 0);
5682
5683         getOpNameAbuseCases(abuseCases);
5684
5685         fillRandomScalars(rnd, -100.0f, 100.0f, &inputFloats[0], numElements);
5686
5687         for (size_t ndx = 0; ndx < numElements; ++ndx)
5688                 outputFloats[ndx] = -inputFloats[ndx];
5689
5690         const string commonShaderHeader =
5691                 "OpCapability Shader\n"
5692                 "OpMemoryModel Logical GLSL450\n"
5693                 "OpEntryPoint GLCompute %main \"main\" %id\n"
5694                 "OpExecutionMode %main LocalSize 1 1 1\n";
5695
5696         const string commonShaderFooter =
5697                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5698
5699                 + string(getComputeAsmInputOutputBufferTraits())
5700                 + string(getComputeAsmCommonTypes())
5701                 + string(getComputeAsmInputOutputBuffer()) +
5702
5703                 "%u3str     = OpTypeStruct %u32 %u32 %u32\n"
5704
5705                 "%id        = OpVariable %uvec3ptr Input\n"
5706                 "%zero      = OpConstant %i32 0\n"
5707
5708                 "%main      = OpFunction %void None %voidf\n"
5709                 "%entry     = OpLabel\n"
5710
5711                 "%idval     = OpLoad %uvec3 %id\n"
5712                 "%x0        = OpCompositeExtract %u32 %idval 0\n"
5713
5714                 "%idstr     = OpCompositeConstruct %u3str %x0 %x0 %x0\n"
5715                 "%x         = OpCompositeExtract %u32 %idstr 0\n"
5716
5717                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5718                 "%inval     = OpLoad %f32 %inloc\n"
5719                 "%neg       = OpFNegate %f32 %inval\n"
5720                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5721                 "             OpStore %outloc %neg\n"
5722
5723                 "             OpReturn\n"
5724                 "             OpFunctionEnd\n";
5725
5726         const StringTemplate shaderTemplate(
5727                 commonShaderHeader +
5728                 "OpMemberName %u3str 0 \"${NAME}\"\n" +
5729                 commonShaderFooter);
5730
5731         const std::string multipleNames =
5732                 commonShaderHeader +
5733                 "OpMemberName %u3str 0 \"to_be\"\n"
5734                 "OpMemberName %u3str 1 \"or_not\"\n"
5735                 "OpMemberName %u3str 0 \"to_be\"\n"
5736                 "OpMemberName %u3str 2 \"makes_no\"\n"
5737                 "OpMemberName %u3str 0 \"difference\"\n"
5738                 "OpMemberName %u3str 0 \"to_me\"\n" +
5739                 commonShaderFooter;
5740         {
5741                 ComputeShaderSpec       spec;
5742
5743                 spec.assembly = multipleNames;
5744                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5745                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5746                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5747
5748                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "u3str_x_has_multiple_names", "multiple_names", spec));
5749         }
5750
5751         const std::string everythingNamedTheSame =
5752                 commonShaderHeader +
5753                 "OpMemberName %u3str 0 \"the_same\"\n"
5754                 "OpMemberName %u3str 1 \"the_same\"\n"
5755                 "OpMemberName %u3str 2 \"the_same\"\n" +
5756                 commonShaderFooter;
5757
5758         {
5759                 ComputeShaderSpec       spec;
5760
5761                 spec.assembly = everythingNamedTheSame;
5762                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5763                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5764                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5765
5766                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "everything_named_the_same", "everything_named_the_same", spec));
5767         }
5768
5769         // u3str_x_is_....
5770         for (size_t ndx = 0; ndx < abuseCases.size(); ++ndx)
5771         {
5772                 map<string, string>     specializations;
5773                 ComputeShaderSpec       spec;
5774
5775                 specializations["NAME"] = abuseCases[ndx].param;
5776                 spec.assembly = shaderTemplate.specialize(specializations);
5777                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5778                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5779                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5780
5781                 abuseGroup->addChild(new SpvAsmComputeShaderCase(testCtx, (std::string("u3str_x") + abuseCases[ndx].name).c_str(), abuseCases[ndx].name, spec));
5782         }
5783
5784         group->addChild(abuseGroup.release());
5785
5786         return group.release();
5787 }
5788
5789 // Assembly code used for testing function control is based on GLSL source code:
5790 //
5791 // #version 430
5792 //
5793 // layout(std140, set = 0, binding = 0) readonly buffer Input {
5794 //   float elements[];
5795 // } input_data;
5796 // layout(std140, set = 0, binding = 1) writeonly buffer Output {
5797 //   float elements[];
5798 // } output_data;
5799 //
5800 // float const10() { return 10.f; }
5801 //
5802 // void main() {
5803 //   uint x = gl_GlobalInvocationID.x;
5804 //   output_data.elements[x] = input_data.elements[x] + const10();
5805 // }
5806 tcu::TestCaseGroup* createFunctionControlGroup (tcu::TestContext& testCtx)
5807 {
5808         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "function_control", "Tests function control cases"));
5809         vector<CaseParameter>                   cases;
5810         de::Random                                              rnd                             (deStringHash(group->getName()));
5811         const int                                               numElements             = 100;
5812         vector<float>                                   inputFloats             (numElements, 0);
5813         vector<float>                                   outputFloats    (numElements, 0);
5814         const StringTemplate                    shaderTemplate  (
5815                 string(getComputeAsmShaderPreamble()) +
5816
5817                 "OpSource GLSL 430\n"
5818                 "OpName %main \"main\"\n"
5819                 "OpName %func_const10 \"const10(\"\n"
5820                 "OpName %id \"gl_GlobalInvocationID\"\n"
5821
5822                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5823
5824                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5825
5826                 "%f32f = OpTypeFunction %f32\n"
5827                 "%id = OpVariable %uvec3ptr Input\n"
5828                 "%zero = OpConstant %i32 0\n"
5829                 "%constf10 = OpConstant %f32 10.0\n"
5830
5831                 "%main         = OpFunction %void None %voidf\n"
5832                 "%entry        = OpLabel\n"
5833                 "%idval        = OpLoad %uvec3 %id\n"
5834                 "%x            = OpCompositeExtract %u32 %idval 0\n"
5835                 "%inloc        = OpAccessChain %f32ptr %indata %zero %x\n"
5836                 "%inval        = OpLoad %f32 %inloc\n"
5837                 "%ret_10       = OpFunctionCall %f32 %func_const10\n"
5838                 "%fadd         = OpFAdd %f32 %inval %ret_10\n"
5839                 "%outloc       = OpAccessChain %f32ptr %outdata %zero %x\n"
5840                 "                OpStore %outloc %fadd\n"
5841                 "                OpReturn\n"
5842                 "                OpFunctionEnd\n"
5843
5844                 "%func_const10 = OpFunction %f32 ${CONTROL} %f32f\n"
5845                 "%label        = OpLabel\n"
5846                 "                OpReturnValue %constf10\n"
5847                 "                OpFunctionEnd\n");
5848
5849         cases.push_back(CaseParameter("none",                                           "None"));
5850         cases.push_back(CaseParameter("inline",                                         "Inline"));
5851         cases.push_back(CaseParameter("dont_inline",                            "DontInline"));
5852         cases.push_back(CaseParameter("pure",                                           "Pure"));
5853         cases.push_back(CaseParameter("const",                                          "Const"));
5854         cases.push_back(CaseParameter("inline_pure",                            "Inline|Pure"));
5855         cases.push_back(CaseParameter("const_dont_inline",                      "Const|DontInline"));
5856         cases.push_back(CaseParameter("inline_dont_inline",                     "Inline|DontInline"));
5857         cases.push_back(CaseParameter("pure_inline_dont_inline",        "Pure|Inline|DontInline"));
5858
5859         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5860
5861         // CPU might not use the same rounding mode as the GPU. Use whole numbers to avoid rounding differences.
5862         floorAll(inputFloats);
5863
5864         for (size_t ndx = 0; ndx < numElements; ++ndx)
5865                 outputFloats[ndx] = inputFloats[ndx] + 10.f;
5866
5867         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5868         {
5869                 map<string, string>             specializations;
5870                 ComputeShaderSpec               spec;
5871
5872                 specializations["CONTROL"] = cases[caseNdx].param;
5873                 spec.assembly = shaderTemplate.specialize(specializations);
5874                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5875                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5876                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5877
5878                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5879         }
5880
5881         return group.release();
5882 }
5883
5884 tcu::TestCaseGroup* createMemoryAccessGroup (tcu::TestContext& testCtx)
5885 {
5886         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "memory_access", "Tests memory access cases"));
5887         vector<CaseParameter>                   cases;
5888         de::Random                                              rnd                             (deStringHash(group->getName()));
5889         const int                                               numElements             = 100;
5890         vector<float>                                   inputFloats             (numElements, 0);
5891         vector<float>                                   outputFloats    (numElements, 0);
5892         const StringTemplate                    shaderTemplate  (
5893                 string(getComputeAsmShaderPreamble()) +
5894
5895                 "OpSource GLSL 430\n"
5896                 "OpName %main           \"main\"\n"
5897                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5898
5899                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5900
5901                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
5902
5903                 "%f32ptr_f  = OpTypePointer Function %f32\n"
5904
5905                 "%id        = OpVariable %uvec3ptr Input\n"
5906                 "%zero      = OpConstant %i32 0\n"
5907                 "%four      = OpConstant %i32 4\n"
5908
5909                 "%main      = OpFunction %void None %voidf\n"
5910                 "%label     = OpLabel\n"
5911                 "%copy      = OpVariable %f32ptr_f Function\n"
5912                 "%idval     = OpLoad %uvec3 %id ${ACCESS}\n"
5913                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5914                 "%inloc     = OpAccessChain %f32ptr %indata  %zero %x\n"
5915                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
5916                 "             OpCopyMemory %copy %inloc ${ACCESS}\n"
5917                 "%val1      = OpLoad %f32 %copy\n"
5918                 "%val2      = OpLoad %f32 %inloc\n"
5919                 "%add       = OpFAdd %f32 %val1 %val2\n"
5920                 "             OpStore %outloc %add ${ACCESS}\n"
5921                 "             OpReturn\n"
5922                 "             OpFunctionEnd\n");
5923
5924         cases.push_back(CaseParameter("null",                                   ""));
5925         cases.push_back(CaseParameter("none",                                   "None"));
5926         cases.push_back(CaseParameter("volatile",                               "Volatile"));
5927         cases.push_back(CaseParameter("aligned",                                "Aligned 4"));
5928         cases.push_back(CaseParameter("nontemporal",                    "Nontemporal"));
5929         cases.push_back(CaseParameter("aligned_nontemporal",    "Aligned|Nontemporal 4"));
5930         cases.push_back(CaseParameter("aligned_volatile",               "Volatile|Aligned 4"));
5931
5932         fillRandomScalars(rnd, -100.f, 100.f, &inputFloats[0], numElements);
5933
5934         for (size_t ndx = 0; ndx < numElements; ++ndx)
5935                 outputFloats[ndx] = inputFloats[ndx] + inputFloats[ndx];
5936
5937         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
5938         {
5939                 map<string, string>             specializations;
5940                 ComputeShaderSpec               spec;
5941
5942                 specializations["ACCESS"] = cases[caseNdx].param;
5943                 spec.assembly = shaderTemplate.specialize(specializations);
5944                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputFloats)));
5945                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputFloats)));
5946                 spec.numWorkGroups = IVec3(numElements, 1, 1);
5947
5948                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
5949         }
5950
5951         return group.release();
5952 }
5953
5954 // Checks that we can get undefined values for various types, without exercising a computation with it.
5955 tcu::TestCaseGroup* createOpUndefGroup (tcu::TestContext& testCtx)
5956 {
5957         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opundef", "Tests the OpUndef instruction"));
5958         vector<CaseParameter>                   cases;
5959         de::Random                                              rnd                             (deStringHash(group->getName()));
5960         const int                                               numElements             = 100;
5961         vector<float>                                   positiveFloats  (numElements, 0);
5962         vector<float>                                   negativeFloats  (numElements, 0);
5963         const StringTemplate                    shaderTemplate  (
5964                 string(getComputeAsmShaderPreamble()) +
5965
5966                 "OpSource GLSL 430\n"
5967                 "OpName %main           \"main\"\n"
5968                 "OpName %id             \"gl_GlobalInvocationID\"\n"
5969
5970                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
5971
5972                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) +
5973                 "%uvec2     = OpTypeVector %u32 2\n"
5974                 "%fvec4     = OpTypeVector %f32 4\n"
5975                 "%fmat33    = OpTypeMatrix %fvec3 3\n"
5976                 "%image     = OpTypeImage %f32 2D 0 0 0 1 Unknown\n"
5977                 "%sampler   = OpTypeSampler\n"
5978                 "%simage    = OpTypeSampledImage %image\n"
5979                 "%const100  = OpConstant %u32 100\n"
5980                 "%uarr100   = OpTypeArray %i32 %const100\n"
5981                 "%struct    = OpTypeStruct %f32 %i32 %u32\n"
5982                 "%pointer   = OpTypePointer Function %i32\n"
5983                 + string(getComputeAsmInputOutputBuffer()) +
5984
5985                 "%id        = OpVariable %uvec3ptr Input\n"
5986                 "%zero      = OpConstant %i32 0\n"
5987
5988                 "%main      = OpFunction %void None %voidf\n"
5989                 "%label     = OpLabel\n"
5990
5991                 "%undef     = OpUndef ${TYPE}\n"
5992
5993                 "%idval     = OpLoad %uvec3 %id\n"
5994                 "%x         = OpCompositeExtract %u32 %idval 0\n"
5995
5996                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
5997                 "%inval     = OpLoad %f32 %inloc\n"
5998                 "%neg       = OpFNegate %f32 %inval\n"
5999                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
6000                 "             OpStore %outloc %neg\n"
6001                 "             OpReturn\n"
6002                 "             OpFunctionEnd\n");
6003
6004         cases.push_back(CaseParameter("bool",                   "%bool"));
6005         cases.push_back(CaseParameter("sint32",                 "%i32"));
6006         cases.push_back(CaseParameter("uint32",                 "%u32"));
6007         cases.push_back(CaseParameter("float32",                "%f32"));
6008         cases.push_back(CaseParameter("vec4float32",    "%fvec4"));
6009         cases.push_back(CaseParameter("vec2uint32",             "%uvec2"));
6010         cases.push_back(CaseParameter("matrix",                 "%fmat33"));
6011         cases.push_back(CaseParameter("image",                  "%image"));
6012         cases.push_back(CaseParameter("sampler",                "%sampler"));
6013         cases.push_back(CaseParameter("sampledimage",   "%simage"));
6014         cases.push_back(CaseParameter("array",                  "%uarr100"));
6015         cases.push_back(CaseParameter("runtimearray",   "%f32arr"));
6016         cases.push_back(CaseParameter("struct",                 "%struct"));
6017         cases.push_back(CaseParameter("pointer",                "%pointer"));
6018
6019         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
6020
6021         for (size_t ndx = 0; ndx < numElements; ++ndx)
6022                 negativeFloats[ndx] = -positiveFloats[ndx];
6023
6024         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
6025         {
6026                 map<string, string>             specializations;
6027                 ComputeShaderSpec               spec;
6028
6029                 specializations["TYPE"] = cases[caseNdx].param;
6030                 spec.assembly = shaderTemplate.specialize(specializations);
6031                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
6032                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
6033                 spec.numWorkGroups = IVec3(numElements, 1, 1);
6034
6035                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
6036         }
6037
6038                 return group.release();
6039 }
6040
6041 // Checks that a compute shader can generate a constant composite value of various types, without exercising a computation on it.
6042 tcu::TestCaseGroup* createFloat16OpConstantCompositeGroup (tcu::TestContext& testCtx)
6043 {
6044         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "Tests the OpConstantComposite instruction"));
6045         vector<CaseParameter>                   cases;
6046         de::Random                                              rnd                             (deStringHash(group->getName()));
6047         const int                                               numElements             = 100;
6048         vector<float>                                   positiveFloats  (numElements, 0);
6049         vector<float>                                   negativeFloats  (numElements, 0);
6050         const StringTemplate                    shaderTemplate  (
6051                 "OpCapability Shader\n"
6052                 "OpCapability Float16\n"
6053                 "OpMemoryModel Logical GLSL450\n"
6054                 "OpEntryPoint GLCompute %main \"main\" %id\n"
6055                 "OpExecutionMode %main LocalSize 1 1 1\n"
6056                 "OpSource GLSL 430\n"
6057                 "OpName %main           \"main\"\n"
6058                 "OpName %id             \"gl_GlobalInvocationID\"\n"
6059
6060                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
6061
6062                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
6063
6064                 "%id        = OpVariable %uvec3ptr Input\n"
6065                 "%zero      = OpConstant %i32 0\n"
6066                 "%f16       = OpTypeFloat 16\n"
6067                 "%c_f16_0   = OpConstant %f16 0.0\n"
6068                 "%c_f16_0_5 = OpConstant %f16 0.5\n"
6069                 "%c_f16_1   = OpConstant %f16 1.0\n"
6070                 "%v2f16     = OpTypeVector %f16 2\n"
6071                 "%v3f16     = OpTypeVector %f16 3\n"
6072                 "%v4f16     = OpTypeVector %f16 4\n"
6073
6074                 "${CONSTANT}\n"
6075
6076                 "%main      = OpFunction %void None %voidf\n"
6077                 "%label     = OpLabel\n"
6078                 "%idval     = OpLoad %uvec3 %id\n"
6079                 "%x         = OpCompositeExtract %u32 %idval 0\n"
6080                 "%inloc     = OpAccessChain %f32ptr %indata %zero %x\n"
6081                 "%inval     = OpLoad %f32 %inloc\n"
6082                 "%neg       = OpFNegate %f32 %inval\n"
6083                 "%outloc    = OpAccessChain %f32ptr %outdata %zero %x\n"
6084                 "             OpStore %outloc %neg\n"
6085                 "             OpReturn\n"
6086                 "             OpFunctionEnd\n");
6087
6088
6089         cases.push_back(CaseParameter("vector",                 "%const = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"));
6090         cases.push_back(CaseParameter("matrix",                 "%m3v3f16 = OpTypeMatrix %v3f16 3\n"
6091                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
6092                                                                                                         "%mat = OpConstantComposite %m3v3f16 %vec %vec %vec"));
6093         cases.push_back(CaseParameter("struct",                 "%m2v3f16 = OpTypeMatrix %v3f16 2\n"
6094                                                                                                         "%struct = OpTypeStruct %i32 %f16 %v3f16 %m2v3f16\n"
6095                                                                                                         "%vec = OpConstantComposite %v3f16 %c_f16_0 %c_f16_0_5 %c_f16_1\n"
6096                                                                                                         "%mat = OpConstantComposite %m2v3f16 %vec %vec\n"
6097                                                                                                         "%const = OpConstantComposite %struct %zero %c_f16_0_5 %vec %mat\n"));
6098         cases.push_back(CaseParameter("nested_struct",  "%st1 = OpTypeStruct %i32 %f16\n"
6099                                                                                                         "%st2 = OpTypeStruct %i32 %i32\n"
6100                                                                                                         "%struct = OpTypeStruct %st1 %st2\n"
6101                                                                                                         "%st1val = OpConstantComposite %st1 %zero %c_f16_0_5\n"
6102                                                                                                         "%st2val = OpConstantComposite %st2 %zero %zero\n"
6103                                                                                                         "%const = OpConstantComposite %struct %st1val %st2val"));
6104
6105         fillRandomScalars(rnd, 1.f, 100.f, &positiveFloats[0], numElements);
6106
6107         for (size_t ndx = 0; ndx < numElements; ++ndx)
6108                 negativeFloats[ndx] = -positiveFloats[ndx];
6109
6110         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
6111         {
6112                 map<string, string>             specializations;
6113                 ComputeShaderSpec               spec;
6114
6115                 specializations["CONSTANT"] = cases[caseNdx].param;
6116                 spec.assembly = shaderTemplate.specialize(specializations);
6117                 spec.inputs.push_back(BufferSp(new Float32Buffer(positiveFloats)));
6118                 spec.outputs.push_back(BufferSp(new Float32Buffer(negativeFloats)));
6119                 spec.numWorkGroups = IVec3(numElements, 1, 1);
6120
6121                 spec.extensions.push_back("VK_KHR_16bit_storage");
6122                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
6123
6124                 spec.requestedVulkanFeatures.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
6125                 spec.requestedVulkanFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
6126
6127                 group->addChild(new SpvAsmComputeShaderCase(testCtx, cases[caseNdx].name, cases[caseNdx].name, spec));
6128         }
6129
6130         return group.release();
6131 }
6132
6133 const vector<deFloat16> squarize(const vector<deFloat16>& inData, const deUint32 argNo)
6134 {
6135         const size_t            inDataLength    = inData.size();
6136         vector<deFloat16>       result;
6137
6138         result.reserve(inDataLength * inDataLength);
6139
6140         if (argNo == 0)
6141         {
6142                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6143                         result.insert(result.end(), inData.begin(), inData.end());
6144         }
6145
6146         if (argNo == 1)
6147         {
6148                 for (size_t numIdx = 0; numIdx < inDataLength; ++numIdx)
6149                 {
6150                         const vector<deFloat16> tmp(inDataLength, inData[numIdx]);
6151
6152                         result.insert(result.end(), tmp.begin(), tmp.end());
6153                 }
6154         }
6155
6156         return result;
6157 }
6158
6159 const vector<deFloat16> squarizeVector(const vector<deFloat16>& inData, const deUint32 argNo)
6160 {
6161         vector<deFloat16>       vec;
6162         vector<deFloat16>       result;
6163
6164         // Create vectors. vec will contain each possible pair from inData
6165         {
6166                 const size_t    inDataLength    = inData.size();
6167
6168                 DE_ASSERT(inDataLength <= 64);
6169
6170                 vec.reserve(2 * inDataLength * inDataLength);
6171
6172                 for (size_t numIdxX = 0; numIdxX < inDataLength; ++numIdxX)
6173                 for (size_t numIdxY = 0; numIdxY < inDataLength; ++numIdxY)
6174                 {
6175                         vec.push_back(inData[numIdxX]);
6176                         vec.push_back(inData[numIdxY]);
6177                 }
6178         }
6179
6180         // Create vector pairs. result will contain each possible pair from vec
6181         {
6182                 const size_t    coordsPerVector = 2;
6183                 const size_t    vectorsCount    = vec.size() / coordsPerVector;
6184
6185                 result.reserve(coordsPerVector * vectorsCount * vectorsCount);
6186
6187                 if (argNo == 0)
6188                 {
6189                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6190                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6191                         {
6192                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6193                                         result.push_back(vec[coordsPerVector * numIdxY + coordNdx]);
6194                         }
6195                 }
6196
6197                 if (argNo == 1)
6198                 {
6199                         for (size_t numIdxX = 0; numIdxX < vectorsCount; ++numIdxX)
6200                         for (size_t numIdxY = 0; numIdxY < vectorsCount; ++numIdxY)
6201                         {
6202                                 for (size_t coordNdx = 0; coordNdx < coordsPerVector; ++coordNdx)
6203                                         result.push_back(vec[coordsPerVector * numIdxX + coordNdx]);
6204                         }
6205                 }
6206         }
6207
6208         return result;
6209 }
6210
6211 struct fp16isNan                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isNaN(); } };
6212 struct fp16isInf                        { bool operator()(const tcu::Float16 in1, const tcu::Float16)           { return in1.isInf(); } };
6213 struct fp16isEqual                      { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() == in2.asFloat(); } };
6214 struct fp16isUnequal            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() != in2.asFloat(); } };
6215 struct fp16isLess                       { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <  in2.asFloat(); } };
6216 struct fp16isGreater            { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >  in2.asFloat(); } };
6217 struct fp16isLessOrEqual        { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() <= in2.asFloat(); } };
6218 struct fp16isGreaterOrEqual     { bool operator()(const tcu::Float16 in1, const tcu::Float16 in2)       { return in1.asFloat() >= in2.asFloat(); } };
6219
6220 template <class TestedLogicalFunction, bool onlyTestFunc, bool unationModeAnd, bool nanSupported>
6221 bool compareFP16Logical (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
6222 {
6223         if (inputs.size() != 2 || outputAllocs.size() != 1)
6224                 return false;
6225
6226         vector<deUint8> input1Bytes;
6227         vector<deUint8> input2Bytes;
6228
6229         inputs[0].getBytes(input1Bytes);
6230         inputs[1].getBytes(input2Bytes);
6231
6232         const deUint32                  denormModesCount                        = 2;
6233         const deFloat16                 float16one                                      = tcu::Float16(1.0f).bits();
6234         const deFloat16                 float16zero                                     = tcu::Float16(0.0f).bits();
6235         const tcu::Float16              zero                                            = tcu::Float16::zero(1);
6236         const deFloat16* const  outputAsFP16                            = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
6237         const deFloat16* const  input1AsFP16                            = reinterpret_cast<deFloat16* const>(&input1Bytes.front());
6238         const deFloat16* const  input2AsFP16                            = reinterpret_cast<deFloat16* const>(&input2Bytes.front());
6239         deUint32                                successfulRuns                          = denormModesCount;
6240         std::string                             results[denormModesCount];
6241         TestedLogicalFunction   testedLogicalFunction;
6242
6243         for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6244         {
6245                 const bool flushToZero = (denormMode == 1);
6246
6247                 for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deFloat16); ++idx)
6248                 {
6249                         const tcu::Float16      f1pre                   = tcu::Float16(input1AsFP16[idx]);
6250                         const tcu::Float16      f2pre                   = tcu::Float16(input2AsFP16[idx]);
6251                         const tcu::Float16      f1                              = (flushToZero && f1pre.isDenorm()) ? zero : f1pre;
6252                         const tcu::Float16      f2                              = (flushToZero && f2pre.isDenorm()) ? zero : f2pre;
6253                         deFloat16                       expectedOutput  = float16zero;
6254
6255                         if (onlyTestFunc)
6256                         {
6257                                 if (testedLogicalFunction(f1, f2))
6258                                         expectedOutput = float16one;
6259                         }
6260                         else
6261                         {
6262                                 const bool      f1nan   = f1.isNaN();
6263                                 const bool      f2nan   = f2.isNaN();
6264
6265                                 // Skip NaN floats if not supported by implementation
6266                                 if (!nanSupported && (f1nan || f2nan))
6267                                         continue;
6268
6269                                 if (unationModeAnd)
6270                                 {
6271                                         const bool      ordered         = !f1nan && !f2nan;
6272
6273                                         if (ordered && testedLogicalFunction(f1, f2))
6274                                                 expectedOutput = float16one;
6275                                 }
6276                                 else
6277                                 {
6278                                         const bool      unordered       = f1nan || f2nan;
6279
6280                                         if (unordered || testedLogicalFunction(f1, f2))
6281                                                 expectedOutput = float16one;
6282                                 }
6283                         }
6284
6285                         if (outputAsFP16[idx] != expectedOutput)
6286                         {
6287                                 std::ostringstream str;
6288
6289                                 str << "ERROR: Sub-case #" << idx
6290                                         << " flushToZero:" << flushToZero
6291                                         << std::hex
6292                                         << " failed, inputs: 0x" << f1.bits()
6293                                         << ";0x" << f2.bits()
6294                                         << " output: 0x" << outputAsFP16[idx]
6295                                         << " expected output: 0x" << expectedOutput;
6296
6297                                 results[denormMode] = str.str();
6298
6299                                 successfulRuns--;
6300
6301                                 break;
6302                         }
6303                 }
6304         }
6305
6306         if (successfulRuns == 0)
6307                 for (deUint32 denormMode = 0; denormMode < denormModesCount; denormMode++)
6308                         log << TestLog::Message << results[denormMode] << TestLog::EndMessage;
6309
6310         return successfulRuns > 0;
6311 }
6312
6313 } // anonymous
6314
6315 tcu::TestCaseGroup* createOpSourceTests (tcu::TestContext& testCtx)
6316 {
6317         struct NameCodePair { string name, code; };
6318         RGBA                                                    defaultColors[4];
6319         de::MovePtr<tcu::TestCaseGroup> opSourceTests                   (new tcu::TestCaseGroup(testCtx, "opsource", "OpSource instruction"));
6320         const std::string                               opsourceGLSLWithFile    = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile ";
6321         map<string, string>                             fragments                               = passthruFragments();
6322         const NameCodePair                              tests[]                                 =
6323         {
6324                 {"unknown", "OpSource Unknown 321"},
6325                 {"essl", "OpSource ESSL 310"},
6326                 {"glsl", "OpSource GLSL 450"},
6327                 {"opencl_cpp", "OpSource OpenCL_CPP 120"},
6328                 {"opencl_c", "OpSource OpenCL_C 120"},
6329                 {"multiple", "OpSource GLSL 450\nOpSource GLSL 450"},
6330                 {"file", opsourceGLSLWithFile},
6331                 {"source", opsourceGLSLWithFile + "\"void main(){}\""},
6332                 // Longest possible source string: SPIR-V limits instructions to 65535
6333                 // words, of which the first 4 are opsourceGLSLWithFile; the rest will
6334                 // contain 65530 UTF8 characters (one word each) plus one last word
6335                 // containing 3 ASCII characters and \0.
6336                 {"longsource", opsourceGLSLWithFile + '"' + makeLongUTF8String(65530) + "ccc" + '"'}
6337         };
6338
6339         getDefaultColors(defaultColors);
6340         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6341         {
6342                 fragments["debug"] = tests[testNdx].code;
6343                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6344         }
6345
6346         return opSourceTests.release();
6347 }
6348
6349 tcu::TestCaseGroup* createOpSourceContinuedTests (tcu::TestContext& testCtx)
6350 {
6351         struct NameCodePair { string name, code; };
6352         RGBA                                                            defaultColors[4];
6353         de::MovePtr<tcu::TestCaseGroup>         opSourceTests           (new tcu::TestCaseGroup(testCtx, "opsourcecontinued", "OpSourceContinued instruction"));
6354         map<string, string>                                     fragments                       = passthruFragments();
6355         const std::string                                       opsource                        = "%opsrcfile = OpString \"foo.vert\"\nOpSource GLSL 450 %opsrcfile \"void main(){}\"\n";
6356         const NameCodePair                                      tests[]                         =
6357         {
6358                 {"empty", opsource + "OpSourceContinued \"\""},
6359                 {"short", opsource + "OpSourceContinued \"abcde\""},
6360                 {"multiple", opsource + "OpSourceContinued \"abcde\"\nOpSourceContinued \"fghij\""},
6361                 // Longest possible source string: SPIR-V limits instructions to 65535
6362                 // words, of which the first one is OpSourceContinued/length; the rest
6363                 // will contain 65533 UTF8 characters (one word each) plus one last word
6364                 // containing 3 ASCII characters and \0.
6365                 {"long", opsource + "OpSourceContinued \"" + makeLongUTF8String(65533) + "ccc\""}
6366         };
6367
6368         getDefaultColors(defaultColors);
6369         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
6370         {
6371                 fragments["debug"] = tests[testNdx].code;
6372                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opSourceTests.get());
6373         }
6374
6375         return opSourceTests.release();
6376 }
6377 tcu::TestCaseGroup* createOpNoLineTests(tcu::TestContext& testCtx)
6378 {
6379         RGBA                                                             defaultColors[4];
6380         de::MovePtr<tcu::TestCaseGroup>          opLineTests             (new tcu::TestCaseGroup(testCtx, "opnoline", "OpNoLine instruction"));
6381         map<string, string>                                      fragments;
6382         getDefaultColors(defaultColors);
6383         fragments["debug"]                      =
6384                 "%name = OpString \"name\"\n";
6385
6386         fragments["pre_main"]   =
6387                 "OpNoLine\n"
6388                 "OpNoLine\n"
6389                 "OpLine %name 1 1\n"
6390                 "OpNoLine\n"
6391                 "OpLine %name 1 1\n"
6392                 "OpLine %name 1 1\n"
6393                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6394                 "OpNoLine\n"
6395                 "OpLine %name 1 1\n"
6396                 "OpNoLine\n"
6397                 "OpLine %name 1 1\n"
6398                 "OpLine %name 1 1\n"
6399                 "%second_param1 = OpFunctionParameter %v4f32\n"
6400                 "OpNoLine\n"
6401                 "OpNoLine\n"
6402                 "%label_secondfunction = OpLabel\n"
6403                 "OpNoLine\n"
6404                 "OpReturnValue %second_param1\n"
6405                 "OpFunctionEnd\n"
6406                 "OpNoLine\n"
6407                 "OpNoLine\n";
6408
6409         fragments["testfun"]            =
6410                 // A %test_code function that returns its argument unchanged.
6411                 "OpNoLine\n"
6412                 "OpNoLine\n"
6413                 "OpLine %name 1 1\n"
6414                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6415                 "OpNoLine\n"
6416                 "%param1 = OpFunctionParameter %v4f32\n"
6417                 "OpNoLine\n"
6418                 "OpNoLine\n"
6419                 "%label_testfun = OpLabel\n"
6420                 "OpNoLine\n"
6421                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6422                 "OpReturnValue %val1\n"
6423                 "OpFunctionEnd\n"
6424                 "OpLine %name 1 1\n"
6425                 "OpNoLine\n";
6426
6427         createTestsForAllStages("opnoline", defaultColors, defaultColors, fragments, opLineTests.get());
6428
6429         return opLineTests.release();
6430 }
6431
6432 tcu::TestCaseGroup* createOpModuleProcessedTests(tcu::TestContext& testCtx)
6433 {
6434         RGBA                                                            defaultColors[4];
6435         de::MovePtr<tcu::TestCaseGroup>         opModuleProcessedTests                  (new tcu::TestCaseGroup(testCtx, "opmoduleprocessed", "OpModuleProcessed instruction"));
6436         map<string, string>                                     fragments;
6437         std::vector<std::string>                        noExtensions;
6438         GraphicsResources                                       resources;
6439
6440         getDefaultColors(defaultColors);
6441         resources.verifyBinary = veryfiBinaryShader;
6442         resources.spirvVersion = SPIRV_VERSION_1_3;
6443
6444         fragments["moduleprocessed"]                                                    =
6445                 "OpModuleProcessed \"VULKAN CTS\"\n"
6446                 "OpModuleProcessed \"Negative values\"\n"
6447                 "OpModuleProcessed \"Date: 2017/09/21\"\n";
6448
6449         fragments["pre_main"]   =
6450                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6451                 "%second_param1 = OpFunctionParameter %v4f32\n"
6452                 "%label_secondfunction = OpLabel\n"
6453                 "OpReturnValue %second_param1\n"
6454                 "OpFunctionEnd\n";
6455
6456         fragments["testfun"]            =
6457                 // A %test_code function that returns its argument unchanged.
6458                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6459                 "%param1 = OpFunctionParameter %v4f32\n"
6460                 "%label_testfun = OpLabel\n"
6461                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6462                 "OpReturnValue %val1\n"
6463                 "OpFunctionEnd\n";
6464
6465         createTestsForAllStages ("opmoduleprocessed", defaultColors, defaultColors, fragments, resources, noExtensions, opModuleProcessedTests.get());
6466
6467         return opModuleProcessedTests.release();
6468 }
6469
6470
6471 tcu::TestCaseGroup* createOpLineTests(tcu::TestContext& testCtx)
6472 {
6473         RGBA                                                                                                    defaultColors[4];
6474         de::MovePtr<tcu::TestCaseGroup>                                                 opLineTests                     (new tcu::TestCaseGroup(testCtx, "opline", "OpLine instruction"));
6475         map<string, string>                                                                             fragments;
6476         std::vector<std::pair<std::string, std::string> >               problemStrings;
6477
6478         problemStrings.push_back(std::make_pair<std::string, std::string>("empty_name", ""));
6479         problemStrings.push_back(std::make_pair<std::string, std::string>("short_name", "short_name"));
6480         problemStrings.push_back(std::make_pair<std::string, std::string>("long_name", makeLongUTF8String(65530) + "ccc"));
6481         getDefaultColors(defaultColors);
6482
6483         fragments["debug"]                      =
6484                 "%other_name = OpString \"other_name\"\n";
6485
6486         fragments["pre_main"]   =
6487                 "OpLine %file_name 32 0\n"
6488                 "OpLine %file_name 32 32\n"
6489                 "OpLine %file_name 32 40\n"
6490                 "OpLine %other_name 32 40\n"
6491                 "OpLine %other_name 0 100\n"
6492                 "OpLine %other_name 0 4294967295\n"
6493                 "OpLine %other_name 4294967295 0\n"
6494                 "OpLine %other_name 32 40\n"
6495                 "OpLine %file_name 0 0\n"
6496                 "%second_function = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6497                 "OpLine %file_name 1 0\n"
6498                 "%second_param1 = OpFunctionParameter %v4f32\n"
6499                 "OpLine %file_name 1 3\n"
6500                 "OpLine %file_name 1 2\n"
6501                 "%label_secondfunction = OpLabel\n"
6502                 "OpLine %file_name 0 2\n"
6503                 "OpReturnValue %second_param1\n"
6504                 "OpFunctionEnd\n"
6505                 "OpLine %file_name 0 2\n"
6506                 "OpLine %file_name 0 2\n";
6507
6508         fragments["testfun"]            =
6509                 // A %test_code function that returns its argument unchanged.
6510                 "OpLine %file_name 1 0\n"
6511                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6512                 "OpLine %file_name 16 330\n"
6513                 "%param1 = OpFunctionParameter %v4f32\n"
6514                 "OpLine %file_name 14 442\n"
6515                 "%label_testfun = OpLabel\n"
6516                 "OpLine %file_name 11 1024\n"
6517                 "%val1 = OpFunctionCall %v4f32 %second_function %param1\n"
6518                 "OpLine %file_name 2 97\n"
6519                 "OpReturnValue %val1\n"
6520                 "OpFunctionEnd\n"
6521                 "OpLine %file_name 5 32\n";
6522
6523         for (size_t i = 0; i < problemStrings.size(); ++i)
6524         {
6525                 map<string, string> testFragments = fragments;
6526                 testFragments["debug"] += "%file_name = OpString \"" + problemStrings[i].second + "\"\n";
6527                 createTestsForAllStages(string("opline") + "_" + problemStrings[i].first, defaultColors, defaultColors, testFragments, opLineTests.get());
6528         }
6529
6530         return opLineTests.release();
6531 }
6532
6533 tcu::TestCaseGroup* createOpConstantNullTests(tcu::TestContext& testCtx)
6534 {
6535         de::MovePtr<tcu::TestCaseGroup> opConstantNullTests             (new tcu::TestCaseGroup(testCtx, "opconstantnull", "OpConstantNull instruction"));
6536         RGBA                                                    colors[4];
6537
6538
6539         const char                                              functionStart[] =
6540                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6541                 "%param1 = OpFunctionParameter %v4f32\n"
6542                 "%lbl    = OpLabel\n";
6543
6544         const char                                              functionEnd[]   =
6545                 "OpReturnValue %transformed_param\n"
6546                 "OpFunctionEnd\n";
6547
6548         struct NameConstantsCode
6549         {
6550                 string name;
6551                 string constants;
6552                 string code;
6553         };
6554
6555         NameConstantsCode tests[] =
6556         {
6557                 {
6558                         "vec4",
6559                         "%cnull = OpConstantNull %v4f32\n",
6560                         "%transformed_param = OpFAdd %v4f32 %param1 %cnull\n"
6561                 },
6562                 {
6563                         "float",
6564                         "%cnull = OpConstantNull %f32\n",
6565                         "%vp = OpVariable %fp_v4f32 Function\n"
6566                         "%v  = OpLoad %v4f32 %vp\n"
6567                         "%v0 = OpVectorInsertDynamic %v4f32 %v %cnull %c_i32_0\n"
6568                         "%v1 = OpVectorInsertDynamic %v4f32 %v0 %cnull %c_i32_1\n"
6569                         "%v2 = OpVectorInsertDynamic %v4f32 %v1 %cnull %c_i32_2\n"
6570                         "%v3 = OpVectorInsertDynamic %v4f32 %v2 %cnull %c_i32_3\n"
6571                         "%transformed_param = OpFAdd %v4f32 %param1 %v3\n"
6572                 },
6573                 {
6574                         "bool",
6575                         "%cnull             = OpConstantNull %bool\n",
6576                         "%v                 = OpVariable %fp_v4f32 Function\n"
6577                         "                     OpStore %v %param1\n"
6578                         "                     OpSelectionMerge %false_label None\n"
6579                         "                     OpBranchConditional %cnull %true_label %false_label\n"
6580                         "%true_label        = OpLabel\n"
6581                         "                     OpStore %v %c_v4f32_0_5_0_5_0_5_0_5\n"
6582                         "                     OpBranch %false_label\n"
6583                         "%false_label       = OpLabel\n"
6584                         "%transformed_param = OpLoad %v4f32 %v\n"
6585                 },
6586                 {
6587                         "i32",
6588                         "%cnull             = OpConstantNull %i32\n",
6589                         "%v                 = OpVariable %fp_v4f32 Function %c_v4f32_0_5_0_5_0_5_0_5\n"
6590                         "%b                 = OpIEqual %bool %cnull %c_i32_0\n"
6591                         "                     OpSelectionMerge %false_label None\n"
6592                         "                     OpBranchConditional %b %true_label %false_label\n"
6593                         "%true_label        = OpLabel\n"
6594                         "                     OpStore %v %param1\n"
6595                         "                     OpBranch %false_label\n"
6596                         "%false_label       = OpLabel\n"
6597                         "%transformed_param = OpLoad %v4f32 %v\n"
6598                 },
6599                 {
6600                         "struct",
6601                         "%stype             = OpTypeStruct %f32 %v4f32\n"
6602                         "%fp_stype          = OpTypePointer Function %stype\n"
6603                         "%cnull             = OpConstantNull %stype\n",
6604                         "%v                 = OpVariable %fp_stype Function %cnull\n"
6605                         "%f                 = OpAccessChain %fp_v4f32 %v %c_i32_1\n"
6606                         "%f_val             = OpLoad %v4f32 %f\n"
6607                         "%transformed_param = OpFAdd %v4f32 %param1 %f_val\n"
6608                 },
6609                 {
6610                         "array",
6611                         "%a4_v4f32          = OpTypeArray %v4f32 %c_u32_4\n"
6612                         "%fp_a4_v4f32       = OpTypePointer Function %a4_v4f32\n"
6613                         "%cnull             = OpConstantNull %a4_v4f32\n",
6614                         "%v                 = OpVariable %fp_a4_v4f32 Function %cnull\n"
6615                         "%f                 = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6616                         "%f1                = OpAccessChain %fp_v4f32 %v %c_u32_1\n"
6617                         "%f2                = OpAccessChain %fp_v4f32 %v %c_u32_2\n"
6618                         "%f3                = OpAccessChain %fp_v4f32 %v %c_u32_3\n"
6619                         "%f_val             = OpLoad %v4f32 %f\n"
6620                         "%f1_val            = OpLoad %v4f32 %f1\n"
6621                         "%f2_val            = OpLoad %v4f32 %f2\n"
6622                         "%f3_val            = OpLoad %v4f32 %f3\n"
6623                         "%t0                = OpFAdd %v4f32 %param1 %f_val\n"
6624                         "%t1                = OpFAdd %v4f32 %t0 %f1_val\n"
6625                         "%t2                = OpFAdd %v4f32 %t1 %f2_val\n"
6626                         "%transformed_param = OpFAdd %v4f32 %t2 %f3_val\n"
6627                 },
6628                 {
6629                         "matrix",
6630                         "%mat4x4_f32        = OpTypeMatrix %v4f32 4\n"
6631                         "%cnull             = OpConstantNull %mat4x4_f32\n",
6632                         // Our null matrix * any vector should result in a zero vector.
6633                         "%v                 = OpVectorTimesMatrix %v4f32 %param1 %cnull\n"
6634                         "%transformed_param = OpFAdd %v4f32 %param1 %v\n"
6635                 }
6636         };
6637
6638         getHalfColorsFullAlpha(colors);
6639
6640         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6641         {
6642                 map<string, string> fragments;
6643                 fragments["pre_main"] = tests[testNdx].constants;
6644                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6645                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, opConstantNullTests.get());
6646         }
6647         return opConstantNullTests.release();
6648 }
6649 tcu::TestCaseGroup* createOpConstantCompositeTests(tcu::TestContext& testCtx)
6650 {
6651         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstantcomposite", "OpConstantComposite instruction"));
6652         RGBA                                                    inputColors[4];
6653         RGBA                                                    outputColors[4];
6654
6655
6656         const char                                              functionStart[]  =
6657                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6658                 "%param1 = OpFunctionParameter %v4f32\n"
6659                 "%lbl    = OpLabel\n";
6660
6661         const char                                              functionEnd[]           =
6662                 "OpReturnValue %transformed_param\n"
6663                 "OpFunctionEnd\n";
6664
6665         struct NameConstantsCode
6666         {
6667                 string name;
6668                 string constants;
6669                 string code;
6670         };
6671
6672         NameConstantsCode tests[] =
6673         {
6674                 {
6675                         "vec4",
6676
6677                         "%cval              = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0\n",
6678                         "%transformed_param = OpFAdd %v4f32 %param1 %cval\n"
6679                 },
6680                 {
6681                         "struct",
6682
6683                         "%stype             = OpTypeStruct %v4f32 %f32\n"
6684                         "%fp_stype          = OpTypePointer Function %stype\n"
6685                         "%f32_n_1           = OpConstant %f32 -1.0\n"
6686                         "%f32_1_5           = OpConstant %f32 !0x3fc00000\n" // +1.5
6687                         "%cvec              = OpConstantComposite %v4f32 %f32_1_5 %f32_1_5 %f32_1_5 %c_f32_1\n"
6688                         "%cval              = OpConstantComposite %stype %cvec %f32_n_1\n",
6689
6690                         "%v                 = OpVariable %fp_stype Function %cval\n"
6691                         "%vec_ptr           = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
6692                         "%f32_ptr           = OpAccessChain %fp_f32 %v %c_u32_1\n"
6693                         "%vec_val           = OpLoad %v4f32 %vec_ptr\n"
6694                         "%f32_val           = OpLoad %f32 %f32_ptr\n"
6695                         "%tmp1              = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_1 %f32_val\n" // vec4(-1)
6696                         "%tmp2              = OpFAdd %v4f32 %tmp1 %param1\n" // param1 + vec4(-1)
6697                         "%transformed_param = OpFAdd %v4f32 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
6698                 },
6699                 {
6700                         // [1|0|0|0.5] [x] = x + 0.5
6701                         // [0|1|0|0.5] [y] = y + 0.5
6702                         // [0|0|1|0.5] [z] = z + 0.5
6703                         // [0|0|0|1  ] [1] = 1
6704                         "matrix",
6705
6706                         "%mat4x4_f32          = OpTypeMatrix %v4f32 4\n"
6707                         "%v4f32_1_0_0_0       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_0 %c_f32_0 %c_f32_0\n"
6708                         "%v4f32_0_1_0_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_1 %c_f32_0 %c_f32_0\n"
6709                         "%v4f32_0_0_1_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_1 %c_f32_0\n"
6710                         "%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"
6711                         "%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",
6712
6713                         "%transformed_param   = OpMatrixTimesVector %v4f32 %cval %param1\n"
6714                 },
6715                 {
6716                         "array",
6717
6718                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6719                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6720                         "%f32_n_1             = OpConstant %f32 -1.0\n"
6721                         "%f32_1_5             = OpConstant %f32 !0x3fc00000\n" // +1.5
6722                         "%carr                = OpConstantComposite %a4f32 %c_f32_0 %f32_n_1 %f32_1_5 %c_f32_0\n",
6723
6724                         "%v                   = OpVariable %fp_a4f32 Function %carr\n"
6725                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_0\n"
6726                         "%f1                  = OpAccessChain %fp_f32 %v %c_u32_1\n"
6727                         "%f2                  = OpAccessChain %fp_f32 %v %c_u32_2\n"
6728                         "%f3                  = OpAccessChain %fp_f32 %v %c_u32_3\n"
6729                         "%f_val               = OpLoad %f32 %f\n"
6730                         "%f1_val              = OpLoad %f32 %f1\n"
6731                         "%f2_val              = OpLoad %f32 %f2\n"
6732                         "%f3_val              = OpLoad %f32 %f3\n"
6733                         "%ftot1               = OpFAdd %f32 %f_val %f1_val\n"
6734                         "%ftot2               = OpFAdd %f32 %ftot1 %f2_val\n"
6735                         "%ftot3               = OpFAdd %f32 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
6736                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %ftot3\n"
6737                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6738                 },
6739                 {
6740                         //
6741                         // [
6742                         //   {
6743                         //      0.0,
6744                         //      [ 1.0, 1.0, 1.0, 1.0]
6745                         //   },
6746                         //   {
6747                         //      1.0,
6748                         //      [ 0.0, 0.5, 0.0, 0.0]
6749                         //   }, //     ^^^
6750                         //   {
6751                         //      0.0,
6752                         //      [ 1.0, 1.0, 1.0, 1.0]
6753                         //   }
6754                         // ]
6755                         "array_of_struct_of_array",
6756
6757                         "%c_v4f32_1_1_1_0     = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_0\n"
6758                         "%fp_a4f32            = OpTypePointer Function %a4f32\n"
6759                         "%stype               = OpTypeStruct %f32 %a4f32\n"
6760                         "%a3stype             = OpTypeArray %stype %c_u32_3\n"
6761                         "%fp_a3stype          = OpTypePointer Function %a3stype\n"
6762                         "%ca4f32_0            = OpConstantComposite %a4f32 %c_f32_0 %c_f32_0_5 %c_f32_0 %c_f32_0\n"
6763                         "%ca4f32_1            = OpConstantComposite %a4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
6764                         "%cstype1             = OpConstantComposite %stype %c_f32_0 %ca4f32_1\n"
6765                         "%cstype2             = OpConstantComposite %stype %c_f32_1 %ca4f32_0\n"
6766                         "%carr                = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
6767
6768                         "%v                   = OpVariable %fp_a3stype Function %carr\n"
6769                         "%f                   = OpAccessChain %fp_f32 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
6770                         "%f_l                 = OpLoad %f32 %f\n"
6771                         "%add_vec             = OpVectorTimesScalar %v4f32 %c_v4f32_1_1_1_0 %f_l\n"
6772                         "%transformed_param   = OpFAdd %v4f32 %param1 %add_vec\n"
6773                 }
6774         };
6775
6776         getHalfColorsFullAlpha(inputColors);
6777         outputColors[0] = RGBA(255, 255, 255, 255);
6778         outputColors[1] = RGBA(255, 127, 127, 255);
6779         outputColors[2] = RGBA(127, 255, 127, 255);
6780         outputColors[3] = RGBA(127, 127, 255, 255);
6781
6782         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
6783         {
6784                 map<string, string> fragments;
6785                 fragments["pre_main"] = tests[testNdx].constants;
6786                 fragments["testfun"] = string(functionStart) + tests[testNdx].code + functionEnd;
6787                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, opConstantCompositeTests.get());
6788         }
6789         return opConstantCompositeTests.release();
6790 }
6791
6792 tcu::TestCaseGroup* createSelectionBlockOrderTests(tcu::TestContext& testCtx)
6793 {
6794         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "selection_block_order", "Out-of-order blocks for selection"));
6795         RGBA                                                    inputColors[4];
6796         RGBA                                                    outputColors[4];
6797         map<string, string>                             fragments;
6798
6799         // vec4 test_code(vec4 param) {
6800         //   vec4 result = param;
6801         //   for (int i = 0; i < 4; ++i) {
6802         //     if (i == 0) result[i] = 0.;
6803         //     else        result[i] = 1. - result[i];
6804         //   }
6805         //   return result;
6806         // }
6807         const char                                              function[]                      =
6808                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6809                 "%param1    = OpFunctionParameter %v4f32\n"
6810                 "%lbl       = OpLabel\n"
6811                 "%iptr      = OpVariable %fp_i32 Function\n"
6812                 "%result    = OpVariable %fp_v4f32 Function\n"
6813                 "             OpStore %iptr %c_i32_0\n"
6814                 "             OpStore %result %param1\n"
6815                 "             OpBranch %loop\n"
6816
6817                 // Loop entry block.
6818                 "%loop      = OpLabel\n"
6819                 "%ival      = OpLoad %i32 %iptr\n"
6820                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6821                 "             OpLoopMerge %exit %if_entry None\n"
6822                 "             OpBranchConditional %lt_4 %if_entry %exit\n"
6823
6824                 // Merge block for loop.
6825                 "%exit      = OpLabel\n"
6826                 "%ret       = OpLoad %v4f32 %result\n"
6827                 "             OpReturnValue %ret\n"
6828
6829                 // If-statement entry block.
6830                 "%if_entry  = OpLabel\n"
6831                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
6832                 "%eq_0      = OpIEqual %bool %ival %c_i32_0\n"
6833                 "             OpSelectionMerge %if_exit None\n"
6834                 "             OpBranchConditional %eq_0 %if_true %if_false\n"
6835
6836                 // False branch for if-statement.
6837                 "%if_false  = OpLabel\n"
6838                 "%val       = OpLoad %f32 %loc\n"
6839                 "%sub       = OpFSub %f32 %c_f32_1 %val\n"
6840                 "             OpStore %loc %sub\n"
6841                 "             OpBranch %if_exit\n"
6842
6843                 // Merge block for if-statement.
6844                 "%if_exit   = OpLabel\n"
6845                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
6846                 "             OpStore %iptr %ival_next\n"
6847                 "             OpBranch %loop\n"
6848
6849                 // True branch for if-statement.
6850                 "%if_true   = OpLabel\n"
6851                 "             OpStore %loc %c_f32_0\n"
6852                 "             OpBranch %if_exit\n"
6853
6854                 "             OpFunctionEnd\n";
6855
6856         fragments["testfun"]    = function;
6857
6858         inputColors[0]                  = RGBA(127, 127, 127, 0);
6859         inputColors[1]                  = RGBA(127, 0,   0,   0);
6860         inputColors[2]                  = RGBA(0,   127, 0,   0);
6861         inputColors[3]                  = RGBA(0,   0,   127, 0);
6862
6863         outputColors[0]                 = RGBA(0, 128, 128, 255);
6864         outputColors[1]                 = RGBA(0, 255, 255, 255);
6865         outputColors[2]                 = RGBA(0, 128, 255, 255);
6866         outputColors[3]                 = RGBA(0, 255, 128, 255);
6867
6868         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6869
6870         return group.release();
6871 }
6872
6873 tcu::TestCaseGroup* createSwitchBlockOrderTests(tcu::TestContext& testCtx)
6874 {
6875         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "switch_block_order", "Out-of-order blocks for switch"));
6876         RGBA                                                    inputColors[4];
6877         RGBA                                                    outputColors[4];
6878         map<string, string>                             fragments;
6879
6880         const char                                              typesAndConstants[]     =
6881                 "%c_f32_p2  = OpConstant %f32 0.2\n"
6882                 "%c_f32_p4  = OpConstant %f32 0.4\n"
6883                 "%c_f32_p6  = OpConstant %f32 0.6\n"
6884                 "%c_f32_p8  = OpConstant %f32 0.8\n";
6885
6886         // vec4 test_code(vec4 param) {
6887         //   vec4 result = param;
6888         //   for (int i = 0; i < 4; ++i) {
6889         //     switch (i) {
6890         //       case 0: result[i] += .2; break;
6891         //       case 1: result[i] += .6; break;
6892         //       case 2: result[i] += .4; break;
6893         //       case 3: result[i] += .8; break;
6894         //       default: break; // unreachable
6895         //     }
6896         //   }
6897         //   return result;
6898         // }
6899         const char                                              function[]                      =
6900                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
6901                 "%param1    = OpFunctionParameter %v4f32\n"
6902                 "%lbl       = OpLabel\n"
6903                 "%iptr      = OpVariable %fp_i32 Function\n"
6904                 "%result    = OpVariable %fp_v4f32 Function\n"
6905                 "             OpStore %iptr %c_i32_0\n"
6906                 "             OpStore %result %param1\n"
6907                 "             OpBranch %loop\n"
6908
6909                 // Loop entry block.
6910                 "%loop      = OpLabel\n"
6911                 "%ival      = OpLoad %i32 %iptr\n"
6912                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
6913                 "             OpLoopMerge %exit %switch_exit None\n"
6914                 "             OpBranchConditional %lt_4 %switch_entry %exit\n"
6915
6916                 // Merge block for loop.
6917                 "%exit      = OpLabel\n"
6918                 "%ret       = OpLoad %v4f32 %result\n"
6919                 "             OpReturnValue %ret\n"
6920
6921                 // Switch-statement entry block.
6922                 "%switch_entry   = OpLabel\n"
6923                 "%loc            = OpAccessChain %fp_f32 %result %ival\n"
6924                 "%val            = OpLoad %f32 %loc\n"
6925                 "                  OpSelectionMerge %switch_exit None\n"
6926                 "                  OpSwitch %ival %switch_default 0 %case0 1 %case1 2 %case2 3 %case3\n"
6927
6928                 "%case2          = OpLabel\n"
6929                 "%addp4          = OpFAdd %f32 %val %c_f32_p4\n"
6930                 "                  OpStore %loc %addp4\n"
6931                 "                  OpBranch %switch_exit\n"
6932
6933                 "%switch_default = OpLabel\n"
6934                 "                  OpUnreachable\n"
6935
6936                 "%case3          = OpLabel\n"
6937                 "%addp8          = OpFAdd %f32 %val %c_f32_p8\n"
6938                 "                  OpStore %loc %addp8\n"
6939                 "                  OpBranch %switch_exit\n"
6940
6941                 "%case0          = OpLabel\n"
6942                 "%addp2          = OpFAdd %f32 %val %c_f32_p2\n"
6943                 "                  OpStore %loc %addp2\n"
6944                 "                  OpBranch %switch_exit\n"
6945
6946                 // Merge block for switch-statement.
6947                 "%switch_exit    = OpLabel\n"
6948                 "%ival_next      = OpIAdd %i32 %ival %c_i32_1\n"
6949                 "                  OpStore %iptr %ival_next\n"
6950                 "                  OpBranch %loop\n"
6951
6952                 "%case1          = OpLabel\n"
6953                 "%addp6          = OpFAdd %f32 %val %c_f32_p6\n"
6954                 "                  OpStore %loc %addp6\n"
6955                 "                  OpBranch %switch_exit\n"
6956
6957                 "                  OpFunctionEnd\n";
6958
6959         fragments["pre_main"]   = typesAndConstants;
6960         fragments["testfun"]    = function;
6961
6962         inputColors[0]                  = RGBA(127, 27,  127, 51);
6963         inputColors[1]                  = RGBA(127, 0,   0,   51);
6964         inputColors[2]                  = RGBA(0,   27,  0,   51);
6965         inputColors[3]                  = RGBA(0,   0,   127, 51);
6966
6967         outputColors[0]                 = RGBA(178, 180, 229, 255);
6968         outputColors[1]                 = RGBA(178, 153, 102, 255);
6969         outputColors[2]                 = RGBA(51,  180, 102, 255);
6970         outputColors[3]                 = RGBA(51,  153, 229, 255);
6971
6972         createTestsForAllStages("out_of_order", inputColors, outputColors, fragments, group.get());
6973
6974         return group.release();
6975 }
6976
6977 tcu::TestCaseGroup* createDecorationGroupTests(tcu::TestContext& testCtx)
6978 {
6979         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "decoration_group", "Decoration group tests"));
6980         RGBA                                                    inputColors[4];
6981         RGBA                                                    outputColors[4];
6982         map<string, string>                             fragments;
6983
6984         const char                                              decorations[]           =
6985                 "OpDecorate %array_group         ArrayStride 4\n"
6986                 "OpDecorate %struct_member_group Offset 0\n"
6987                 "%array_group         = OpDecorationGroup\n"
6988                 "%struct_member_group = OpDecorationGroup\n"
6989
6990                 "OpDecorate %group1 RelaxedPrecision\n"
6991                 "OpDecorate %group3 RelaxedPrecision\n"
6992                 "OpDecorate %group3 Invariant\n"
6993                 "OpDecorate %group3 Restrict\n"
6994                 "%group0 = OpDecorationGroup\n"
6995                 "%group1 = OpDecorationGroup\n"
6996                 "%group3 = OpDecorationGroup\n";
6997
6998         const char                                              typesAndConstants[]     =
6999                 "%a3f32     = OpTypeArray %f32 %c_u32_3\n"
7000                 "%struct1   = OpTypeStruct %a3f32\n"
7001                 "%struct2   = OpTypeStruct %a3f32\n"
7002                 "%fp_struct1 = OpTypePointer Function %struct1\n"
7003                 "%fp_struct2 = OpTypePointer Function %struct2\n"
7004                 "%c_f32_2    = OpConstant %f32 2.\n"
7005                 "%c_f32_n2   = OpConstant %f32 -2.\n"
7006
7007                 "%c_a3f32_1 = OpConstantComposite %a3f32 %c_f32_1 %c_f32_2 %c_f32_1\n"
7008                 "%c_a3f32_2 = OpConstantComposite %a3f32 %c_f32_n1 %c_f32_n2 %c_f32_n1\n"
7009                 "%c_struct1 = OpConstantComposite %struct1 %c_a3f32_1\n"
7010                 "%c_struct2 = OpConstantComposite %struct2 %c_a3f32_2\n";
7011
7012         const char                                              function[]                      =
7013                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7014                 "%param     = OpFunctionParameter %v4f32\n"
7015                 "%entry     = OpLabel\n"
7016                 "%result    = OpVariable %fp_v4f32 Function\n"
7017                 "%v_struct1 = OpVariable %fp_struct1 Function\n"
7018                 "%v_struct2 = OpVariable %fp_struct2 Function\n"
7019                 "             OpStore %result %param\n"
7020                 "             OpStore %v_struct1 %c_struct1\n"
7021                 "             OpStore %v_struct2 %c_struct2\n"
7022                 "%ptr1      = OpAccessChain %fp_f32 %v_struct1 %c_i32_0 %c_i32_2\n"
7023                 "%val1      = OpLoad %f32 %ptr1\n"
7024                 "%ptr2      = OpAccessChain %fp_f32 %v_struct2 %c_i32_0 %c_i32_2\n"
7025                 "%val2      = OpLoad %f32 %ptr2\n"
7026                 "%addvalues = OpFAdd %f32 %val1 %val2\n"
7027                 "%ptr       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7028                 "%val       = OpLoad %f32 %ptr\n"
7029                 "%addresult = OpFAdd %f32 %addvalues %val\n"
7030                 "             OpStore %ptr %addresult\n"
7031                 "%ret       = OpLoad %v4f32 %result\n"
7032                 "             OpReturnValue %ret\n"
7033                 "             OpFunctionEnd\n";
7034
7035         struct CaseNameDecoration
7036         {
7037                 string name;
7038                 string decoration;
7039         };
7040
7041         CaseNameDecoration tests[] =
7042         {
7043                 {
7044                         "same_decoration_group_on_multiple_types",
7045                         "OpGroupMemberDecorate %struct_member_group %struct1 0 %struct2 0\n"
7046                 },
7047                 {
7048                         "empty_decoration_group",
7049                         "OpGroupDecorate %group0      %a3f32\n"
7050                         "OpGroupDecorate %group0      %result\n"
7051                 },
7052                 {
7053                         "one_element_decoration_group",
7054                         "OpGroupDecorate %array_group %a3f32\n"
7055                 },
7056                 {
7057                         "multiple_elements_decoration_group",
7058                         "OpGroupDecorate %group3      %v_struct1\n"
7059                 },
7060                 {
7061                         "multiple_decoration_groups_on_same_variable",
7062                         "OpGroupDecorate %group0      %v_struct2\n"
7063                         "OpGroupDecorate %group1      %v_struct2\n"
7064                         "OpGroupDecorate %group3      %v_struct2\n"
7065                 },
7066                 {
7067                         "same_decoration_group_multiple_times",
7068                         "OpGroupDecorate %group1      %addvalues\n"
7069                         "OpGroupDecorate %group1      %addvalues\n"
7070                         "OpGroupDecorate %group1      %addvalues\n"
7071                 },
7072
7073         };
7074
7075         getHalfColorsFullAlpha(inputColors);
7076         getHalfColorsFullAlpha(outputColors);
7077
7078         for (size_t idx = 0; idx < (sizeof(tests) / sizeof(tests[0])); ++idx)
7079         {
7080                 fragments["decoration"] = decorations + tests[idx].decoration;
7081                 fragments["pre_main"]   = typesAndConstants;
7082                 fragments["testfun"]    = function;
7083
7084                 createTestsForAllStages(tests[idx].name, inputColors, outputColors, fragments, group.get());
7085         }
7086
7087         return group.release();
7088 }
7089
7090 struct SpecConstantTwoIntGraphicsCase
7091 {
7092         const char*             caseName;
7093         const char*             scDefinition0;
7094         const char*             scDefinition1;
7095         const char*             scResultType;
7096         const char*             scOperation;
7097         deInt32                 scActualValue0;
7098         deInt32                 scActualValue1;
7099         const char*             resultOperation;
7100         RGBA                    expectedColors[4];
7101         deInt32                 scActualValueLength;
7102
7103                                         SpecConstantTwoIntGraphicsCase (const char*             name,
7104                                                                                                         const char*             definition0,
7105                                                                                                         const char*             definition1,
7106                                                                                                         const char*             resultType,
7107                                                                                                         const char*             operation,
7108                                                                                                         const deInt32   value0,
7109                                                                                                         const deInt32   value1,
7110                                                                                                         const char*             resultOp,
7111                                                                                                         const RGBA              (&output)[4],
7112                                                                                                         const deInt32   valueLength = sizeof(deInt32))
7113                                                 : caseName                              (name)
7114                                                 , scDefinition0                 (definition0)
7115                                                 , scDefinition1                 (definition1)
7116                                                 , scResultType                  (resultType)
7117                                                 , scOperation                   (operation)
7118                                                 , scActualValue0                (value0)
7119                                                 , scActualValue1                (value1)
7120                                                 , resultOperation               (resultOp)
7121                                                 , scActualValueLength   (valueLength)
7122         {
7123                 expectedColors[0] = output[0];
7124                 expectedColors[1] = output[1];
7125                 expectedColors[2] = output[2];
7126                 expectedColors[3] = output[3];
7127         }
7128 };
7129
7130 tcu::TestCaseGroup* createSpecConstantTests (tcu::TestContext& testCtx)
7131 {
7132         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opspecconstantop", "Test the OpSpecConstantOp instruction"));
7133         vector<SpecConstantTwoIntGraphicsCase>  cases;
7134         RGBA                                                    inputColors[4];
7135         RGBA                                                    outputColors0[4];
7136         RGBA                                                    outputColors1[4];
7137         RGBA                                                    outputColors2[4];
7138
7139         const deInt32                                   m1AsFloat16                     = 0xbc00; // -1(fp16) == 1 01111 0000000000 == 1011 1100 0000 0000
7140
7141         const char      decorations1[]                  =
7142                 "OpDecorate %sc_0  SpecId 0\n"
7143                 "OpDecorate %sc_1  SpecId 1\n";
7144
7145         const char      typesAndConstants1[]    =
7146                 "${OPTYPE_DEFINITIONS:opt}"
7147                 "%sc_0      = OpSpecConstant${SC_DEF0}\n"
7148                 "%sc_1      = OpSpecConstant${SC_DEF1}\n"
7149                 "%sc_op     = OpSpecConstantOp ${SC_RESULT_TYPE} ${SC_OP}\n";
7150
7151         const char      function1[]                             =
7152                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7153                 "%param     = OpFunctionParameter %v4f32\n"
7154                 "%label     = OpLabel\n"
7155                 "%result    = OpVariable %fp_v4f32 Function\n"
7156                 "${TYPE_CONVERT:opt}"
7157                 "             OpStore %result %param\n"
7158                 "%gen       = ${GEN_RESULT}\n"
7159                 "%index     = OpIAdd %i32 %gen %c_i32_1\n"
7160                 "%loc       = OpAccessChain %fp_f32 %result %index\n"
7161                 "%val       = OpLoad %f32 %loc\n"
7162                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7163                 "             OpStore %loc %add\n"
7164                 "%ret       = OpLoad %v4f32 %result\n"
7165                 "             OpReturnValue %ret\n"
7166                 "             OpFunctionEnd\n";
7167
7168         inputColors[0] = RGBA(127, 127, 127, 255);
7169         inputColors[1] = RGBA(127, 0,   0,   255);
7170         inputColors[2] = RGBA(0,   127, 0,   255);
7171         inputColors[3] = RGBA(0,   0,   127, 255);
7172
7173         // Derived from inputColors[x] by adding 128 to inputColors[x][0].
7174         outputColors0[0] = RGBA(255, 127, 127, 255);
7175         outputColors0[1] = RGBA(255, 0,   0,   255);
7176         outputColors0[2] = RGBA(128, 127, 0,   255);
7177         outputColors0[3] = RGBA(128, 0,   127, 255);
7178
7179         // Derived from inputColors[x] by adding 128 to inputColors[x][1].
7180         outputColors1[0] = RGBA(127, 255, 127, 255);
7181         outputColors1[1] = RGBA(127, 128, 0,   255);
7182         outputColors1[2] = RGBA(0,   255, 0,   255);
7183         outputColors1[3] = RGBA(0,   128, 127, 255);
7184
7185         // Derived from inputColors[x] by adding 128 to inputColors[x][2].
7186         outputColors2[0] = RGBA(127, 127, 255, 255);
7187         outputColors2[1] = RGBA(127, 0,   128, 255);
7188         outputColors2[2] = RGBA(0,   127, 128, 255);
7189         outputColors2[3] = RGBA(0,   0,   255, 255);
7190
7191         const char addZeroToSc[]                = "OpIAdd %i32 %c_i32_0 %sc_op";
7192         const char addZeroToSc32[]              = "OpIAdd %i32 %c_i32_0 %sc_op32";
7193         const char selectTrueUsingSc[]  = "OpSelect %i32 %sc_op %c_i32_1 %c_i32_0";
7194         const char selectFalseUsingSc[] = "OpSelect %i32 %sc_op %c_i32_0 %c_i32_1";
7195
7196         cases.push_back(SpecConstantTwoIntGraphicsCase("iadd",                                  " %i32 0",              " %i32 0",              "%i32",         "IAdd                 %sc_0 %sc_1",                             19,             -20,    addZeroToSc,            outputColors0));
7197         cases.push_back(SpecConstantTwoIntGraphicsCase("isub",                                  " %i32 0",              " %i32 0",              "%i32",         "ISub                 %sc_0 %sc_1",                             19,             20,             addZeroToSc,            outputColors0));
7198         cases.push_back(SpecConstantTwoIntGraphicsCase("imul",                                  " %i32 0",              " %i32 0",              "%i32",         "IMul                 %sc_0 %sc_1",                             -1,             -1,             addZeroToSc,            outputColors2));
7199         cases.push_back(SpecConstantTwoIntGraphicsCase("sdiv",                                  " %i32 0",              " %i32 0",              "%i32",         "SDiv                 %sc_0 %sc_1",                             -126,   126,    addZeroToSc,            outputColors0));
7200         cases.push_back(SpecConstantTwoIntGraphicsCase("udiv",                                  " %i32 0",              " %i32 0",              "%i32",         "UDiv                 %sc_0 %sc_1",                             126,    126,    addZeroToSc,            outputColors2));
7201         cases.push_back(SpecConstantTwoIntGraphicsCase("srem",                                  " %i32 0",              " %i32 0",              "%i32",         "SRem                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7202         cases.push_back(SpecConstantTwoIntGraphicsCase("smod",                                  " %i32 0",              " %i32 0",              "%i32",         "SMod                 %sc_0 %sc_1",                             3,              2,              addZeroToSc,            outputColors2));
7203         cases.push_back(SpecConstantTwoIntGraphicsCase("umod",                                  " %i32 0",              " %i32 0",              "%i32",         "UMod                 %sc_0 %sc_1",                             1001,   500,    addZeroToSc,            outputColors2));
7204         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseand",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseAnd           %sc_0 %sc_1",                             0x33,   0x0d,   addZeroToSc,            outputColors2));
7205         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwiseor",                             " %i32 0",              " %i32 0",              "%i32",         "BitwiseOr            %sc_0 %sc_1",                             0,              1,              addZeroToSc,            outputColors2));
7206         cases.push_back(SpecConstantTwoIntGraphicsCase("bitwisexor",                    " %i32 0",              " %i32 0",              "%i32",         "BitwiseXor           %sc_0 %sc_1",                             0x2e,   0x2f,   addZeroToSc,            outputColors2));
7207         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightlogical",             " %i32 0",              " %i32 0",              "%i32",         "ShiftRightLogical    %sc_0 %sc_1",                             2,              1,              addZeroToSc,            outputColors2));
7208         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftrightarithmetic",  " %i32 0",              " %i32 0",              "%i32",         "ShiftRightArithmetic %sc_0 %sc_1",                             -4,             2,              addZeroToSc,            outputColors0));
7209         cases.push_back(SpecConstantTwoIntGraphicsCase("shiftleftlogical",              " %i32 0",              " %i32 0",              "%i32",         "ShiftLeftLogical     %sc_0 %sc_1",                             1,              0,              addZeroToSc,            outputColors2));
7210         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthan",                             " %i32 0",              " %i32 0",              "%bool",        "SLessThan            %sc_0 %sc_1",                             -20,    -10,    selectTrueUsingSc,      outputColors2));
7211         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthan",                             " %i32 0",              " %i32 0",              "%bool",        "ULessThan            %sc_0 %sc_1",                             10,             20,             selectTrueUsingSc,      outputColors2));
7212         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "SGreaterThan         %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7213         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthan",                  " %i32 0",              " %i32 0",              "%bool",        "UGreaterThan         %sc_0 %sc_1",                             10,             5,              selectTrueUsingSc,      outputColors2));
7214         cases.push_back(SpecConstantTwoIntGraphicsCase("slessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "SLessThanEqual       %sc_0 %sc_1",                             -10,    -10,    selectTrueUsingSc,      outputColors2));
7215         cases.push_back(SpecConstantTwoIntGraphicsCase("ulessthanequal",                " %i32 0",              " %i32 0",              "%bool",        "ULessThanEqual       %sc_0 %sc_1",                             50,             100,    selectTrueUsingSc,      outputColors2));
7216         cases.push_back(SpecConstantTwoIntGraphicsCase("sgreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "SGreaterThanEqual    %sc_0 %sc_1",                             -1000,  50,             selectFalseUsingSc,     outputColors2));
7217         cases.push_back(SpecConstantTwoIntGraphicsCase("ugreaterthanequal",             " %i32 0",              " %i32 0",              "%bool",        "UGreaterThanEqual    %sc_0 %sc_1",                             10,             10,             selectTrueUsingSc,      outputColors2));
7218         cases.push_back(SpecConstantTwoIntGraphicsCase("iequal",                                " %i32 0",              " %i32 0",              "%bool",        "IEqual               %sc_0 %sc_1",                             42,             24,             selectFalseUsingSc,     outputColors2));
7219         cases.push_back(SpecConstantTwoIntGraphicsCase("inotequal",                             " %i32 0",              " %i32 0",              "%bool",        "INotEqual            %sc_0 %sc_1",                             42,             24,             selectTrueUsingSc,      outputColors2));
7220         cases.push_back(SpecConstantTwoIntGraphicsCase("logicaland",                    "True %bool",   "True %bool",   "%bool",        "LogicalAnd           %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7221         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalor",                             "False %bool",  "False %bool",  "%bool",        "LogicalOr            %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7222         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalequal",                  "True %bool",   "True %bool",   "%bool",        "LogicalEqual         %sc_0 %sc_1",                             0,              1,              selectFalseUsingSc,     outputColors2));
7223         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnotequal",               "False %bool",  "False %bool",  "%bool",        "LogicalNotEqual      %sc_0 %sc_1",                             1,              0,              selectTrueUsingSc,      outputColors2));
7224         cases.push_back(SpecConstantTwoIntGraphicsCase("snegate",                               " %i32 0",              " %i32 0",              "%i32",         "SNegate              %sc_0",                                   -1,             0,              addZeroToSc,            outputColors2));
7225         cases.push_back(SpecConstantTwoIntGraphicsCase("not",                                   " %i32 0",              " %i32 0",              "%i32",         "Not                  %sc_0",                                   -2,             0,              addZeroToSc,            outputColors2));
7226         cases.push_back(SpecConstantTwoIntGraphicsCase("logicalnot",                    "False %bool",  "False %bool",  "%bool",        "LogicalNot           %sc_0",                                   1,              0,              selectFalseUsingSc,     outputColors2));
7227         cases.push_back(SpecConstantTwoIntGraphicsCase("select",                                "False %bool",  " %i32 0",              "%i32",         "Select               %sc_0 %sc_1 %c_i32_0",    1,              1,              addZeroToSc,            outputColors2));
7228         cases.push_back(SpecConstantTwoIntGraphicsCase("sconvert",                              " %i32 0",              " %i32 0",              "%i16",         "SConvert             %sc_0",                                   -1,             0,              addZeroToSc32,          outputColors0));
7229         // -1082130432 stored as 32-bit two's complement is the binary representation of -1 as IEEE-754 Float
7230         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert",                              " %f32 0",              " %f32 0",              "%f64",         "FConvert             %sc_0",                                   -1082130432, 0, addZeroToSc32,          outputColors0));
7231         cases.push_back(SpecConstantTwoIntGraphicsCase("fconvert16",                    " %f16 0",              " %f16 0",              "%f32",         "FConvert             %sc_0",                                   m1AsFloat16, 0, addZeroToSc32,          outputColors0, sizeof(deFloat16)));
7232         // \todo[2015-12-1 antiagainst] OpQuantizeToF16
7233
7234         for (size_t caseNdx = 0; caseNdx < cases.size(); ++caseNdx)
7235         {
7236                 map<string, string>                     specializations;
7237                 map<string, string>                     fragments;
7238                 SpecConstants                           specConstants;
7239                 PushConstants                           noPushConstants;
7240                 GraphicsResources                       noResources;
7241                 GraphicsInterfaces                      noInterfaces;
7242                 vector<string>                          extensions;
7243                 VulkanFeatures                          requiredFeatures;
7244
7245                 // Special SPIR-V code for SConvert-case
7246                 if (strcmp(cases[caseNdx].caseName, "sconvert") == 0)
7247                 {
7248                         requiredFeatures.coreFeatures.shaderInt16 = VK_TRUE;
7249                         fragments["capability"]                                 = "OpCapability Int16\n";                                       // Adds 16-bit integer capability
7250                         specializations["OPTYPE_DEFINITIONS"]   = "%i16 = OpTypeInt 16 1\n";                            // Adds 16-bit integer type
7251                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpSConvert %i32 %sc_op\n";        // Converts 16-bit integer to 32-bit integer
7252                 }
7253
7254                 // Special SPIR-V code for FConvert-case
7255                 if (strcmp(cases[caseNdx].caseName, "fconvert") == 0)
7256                 {
7257                         requiredFeatures.coreFeatures.shaderFloat64 = VK_TRUE;
7258                         fragments["capability"]                                 = "OpCapability Float64\n";                                     // Adds 64-bit float capability
7259                         specializations["OPTYPE_DEFINITIONS"]   = "%f64 = OpTypeFloat 64\n";                            // Adds 64-bit float type
7260                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 64-bit float to 32-bit integer
7261                 }
7262
7263                 // Special SPIR-V code for FConvert-case for 16-bit floats
7264                 if (strcmp(cases[caseNdx].caseName, "fconvert16") == 0)
7265                 {
7266                         extensions.push_back("VK_KHR_shader_float16_int8");
7267                         requiredFeatures.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
7268                         fragments["capability"]                                 = "OpCapability Float16\n";                                     // Adds 16-bit float capability
7269                         specializations["OPTYPE_DEFINITIONS"]   = "%f16 = OpTypeFloat 16\n";                            // Adds 16-bit float type
7270                         specializations["TYPE_CONVERT"]                 = "%sc_op32 = OpConvertFToS %i32 %sc_op\n";     // Converts 16-bit float to 32-bit integer
7271                 }
7272
7273                 specializations["SC_DEF0"]                      = cases[caseNdx].scDefinition0;
7274                 specializations["SC_DEF1"]                      = cases[caseNdx].scDefinition1;
7275                 specializations["SC_RESULT_TYPE"]       = cases[caseNdx].scResultType;
7276                 specializations["SC_OP"]                        = cases[caseNdx].scOperation;
7277                 specializations["GEN_RESULT"]           = cases[caseNdx].resultOperation;
7278
7279                 fragments["decoration"]                         = tcu::StringTemplate(decorations1).specialize(specializations);
7280                 fragments["pre_main"]                           = tcu::StringTemplate(typesAndConstants1).specialize(specializations);
7281                 fragments["testfun"]                            = tcu::StringTemplate(function1).specialize(specializations);
7282
7283                 specConstants.append(&cases[caseNdx].scActualValue0, cases[caseNdx].scActualValueLength);
7284                 specConstants.append(&cases[caseNdx].scActualValue1, cases[caseNdx].scActualValueLength);
7285
7286                 createTestsForAllStages(
7287                         cases[caseNdx].caseName, inputColors, cases[caseNdx].expectedColors, fragments, specConstants,
7288                         noPushConstants, noResources, noInterfaces, extensions, requiredFeatures, group.get());
7289         }
7290
7291         const char      decorations2[]                  =
7292                 "OpDecorate %sc_0  SpecId 0\n"
7293                 "OpDecorate %sc_1  SpecId 1\n"
7294                 "OpDecorate %sc_2  SpecId 2\n";
7295
7296         const char      typesAndConstants2[]    =
7297                 "%vec3_0      = OpConstantComposite %v3i32 %c_i32_0 %c_i32_0 %c_i32_0\n"
7298                 "%vec3_undef  = OpUndef %v3i32\n"
7299
7300                 "%sc_0        = OpSpecConstant %i32 0\n"
7301                 "%sc_1        = OpSpecConstant %i32 0\n"
7302                 "%sc_2        = OpSpecConstant %i32 0\n"
7303                 "%sc_vec3_0   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_0        %vec3_0      0\n"                                                 // (sc_0, 0,    0)
7304                 "%sc_vec3_1   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_1        %vec3_0      1\n"                                                 // (0,    sc_1, 0)
7305                 "%sc_vec3_2   = OpSpecConstantOp %v3i32 CompositeInsert  %sc_2        %vec3_0      2\n"                                                 // (0,    0,    sc_2)
7306                 "%sc_vec3_0_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0   %vec3_undef  0          0xFFFFFFFF 2\n"   // (sc_0, ???,  0)
7307                 "%sc_vec3_1_s = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_1   %vec3_undef  0xFFFFFFFF 1          0\n"   // (???,  sc_1, 0)
7308                 "%sc_vec3_2_s = OpSpecConstantOp %v3i32 VectorShuffle    %vec3_undef  %sc_vec3_2   5          0xFFFFFFFF 5\n"   // (sc_2, ???,  sc_2)
7309                 "%sc_vec3_01  = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_0_s %sc_vec3_1_s 1 0 4\n"                                             // (0,    sc_0, sc_1)
7310                 "%sc_vec3_012 = OpSpecConstantOp %v3i32 VectorShuffle    %sc_vec3_01  %sc_vec3_2_s 5 1 2\n"                                             // (sc_2, sc_0, sc_1)
7311                 "%sc_ext_0    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              0\n"                                                 // sc_2
7312                 "%sc_ext_1    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              1\n"                                                 // sc_0
7313                 "%sc_ext_2    = OpSpecConstantOp %i32   CompositeExtract %sc_vec3_012              2\n"                                                 // sc_1
7314                 "%sc_sub      = OpSpecConstantOp %i32   ISub             %sc_ext_0    %sc_ext_1\n"                                                              // (sc_2 - sc_0)
7315                 "%sc_final    = OpSpecConstantOp %i32   IMul             %sc_sub      %sc_ext_2\n";                                                             // (sc_2 - sc_0) * sc_1
7316
7317         const char      function2[]                             =
7318                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7319                 "%param     = OpFunctionParameter %v4f32\n"
7320                 "%label     = OpLabel\n"
7321                 "%result    = OpVariable %fp_v4f32 Function\n"
7322                 "             OpStore %result %param\n"
7323                 "%loc       = OpAccessChain %fp_f32 %result %sc_final\n"
7324                 "%val       = OpLoad %f32 %loc\n"
7325                 "%add       = OpFAdd %f32 %val %c_f32_0_5\n"
7326                 "             OpStore %loc %add\n"
7327                 "%ret       = OpLoad %v4f32 %result\n"
7328                 "             OpReturnValue %ret\n"
7329                 "             OpFunctionEnd\n";
7330
7331         map<string, string>     fragments;
7332         SpecConstants           specConstants;
7333
7334         fragments["decoration"] = decorations2;
7335         fragments["pre_main"]   = typesAndConstants2;
7336         fragments["testfun"]    = function2;
7337
7338         specConstants.append<deInt32>(56789);
7339         specConstants.append<deInt32>(-2);
7340         specConstants.append<deInt32>(56788);
7341
7342         createTestsForAllStages("vector_related", inputColors, outputColors2, fragments, specConstants, group.get());
7343
7344         return group.release();
7345 }
7346
7347 tcu::TestCaseGroup* createOpPhiTests(tcu::TestContext& testCtx)
7348 {
7349         de::MovePtr<tcu::TestCaseGroup> group                           (new tcu::TestCaseGroup(testCtx, "opphi", "Test the OpPhi instruction"));
7350         RGBA                                                    inputColors[4];
7351         RGBA                                                    outputColors1[4];
7352         RGBA                                                    outputColors2[4];
7353         RGBA                                                    outputColors3[4];
7354         RGBA                                                    outputColors4[4];
7355         map<string, string>                             fragments1;
7356         map<string, string>                             fragments2;
7357         map<string, string>                             fragments3;
7358         map<string, string>                             fragments4;
7359         std::vector<std::string>                extensions4;
7360         GraphicsResources                               resources4;
7361         VulkanFeatures                                  vulkanFeatures4;
7362
7363         const char      typesAndConstants1[]    =
7364                 "%c_f32_p2  = OpConstant %f32 0.2\n"
7365                 "%c_f32_p4  = OpConstant %f32 0.4\n"
7366                 "%c_f32_p5  = OpConstant %f32 0.5\n"
7367                 "%c_f32_p8  = OpConstant %f32 0.8\n";
7368
7369         // vec4 test_code(vec4 param) {
7370         //   vec4 result = param;
7371         //   for (int i = 0; i < 4; ++i) {
7372         //     float operand;
7373         //     switch (i) {
7374         //       case 0: operand = .2; break;
7375         //       case 1: operand = .5; break;
7376         //       case 2: operand = .4; break;
7377         //       case 3: operand = .0; break;
7378         //       default: break; // unreachable
7379         //     }
7380         //     result[i] += operand;
7381         //   }
7382         //   return result;
7383         // }
7384         const char      function1[]                             =
7385                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7386                 "%param1    = OpFunctionParameter %v4f32\n"
7387                 "%lbl       = OpLabel\n"
7388                 "%iptr      = OpVariable %fp_i32 Function\n"
7389                 "%result    = OpVariable %fp_v4f32 Function\n"
7390                 "             OpStore %iptr %c_i32_0\n"
7391                 "             OpStore %result %param1\n"
7392                 "             OpBranch %loop\n"
7393
7394                 "%loop      = OpLabel\n"
7395                 "%ival      = OpLoad %i32 %iptr\n"
7396                 "%lt_4      = OpSLessThan %bool %ival %c_i32_4\n"
7397                 "             OpLoopMerge %exit %phi None\n"
7398                 "             OpBranchConditional %lt_4 %entry %exit\n"
7399
7400                 "%entry     = OpLabel\n"
7401                 "%loc       = OpAccessChain %fp_f32 %result %ival\n"
7402                 "%val       = OpLoad %f32 %loc\n"
7403                 "             OpSelectionMerge %phi None\n"
7404                 "             OpSwitch %ival %default 0 %case0 1 %case1 2 %case2 3 %case3\n"
7405
7406                 "%case0     = OpLabel\n"
7407                 "             OpBranch %phi\n"
7408                 "%case1     = OpLabel\n"
7409                 "             OpBranch %phi\n"
7410                 "%case2     = OpLabel\n"
7411                 "             OpBranch %phi\n"
7412                 "%case3     = OpLabel\n"
7413                 "             OpBranch %phi\n"
7414
7415                 "%default   = OpLabel\n"
7416                 "             OpUnreachable\n"
7417
7418                 "%phi       = OpLabel\n"
7419                 "%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
7420                 "%add       = OpFAdd %f32 %val %operand\n"
7421                 "             OpStore %loc %add\n"
7422                 "%ival_next = OpIAdd %i32 %ival %c_i32_1\n"
7423                 "             OpStore %iptr %ival_next\n"
7424                 "             OpBranch %loop\n"
7425
7426                 "%exit      = OpLabel\n"
7427                 "%ret       = OpLoad %v4f32 %result\n"
7428                 "             OpReturnValue %ret\n"
7429
7430                 "             OpFunctionEnd\n";
7431
7432         fragments1["pre_main"]  = typesAndConstants1;
7433         fragments1["testfun"]   = function1;
7434
7435         getHalfColorsFullAlpha(inputColors);
7436
7437         outputColors1[0]                = RGBA(178, 255, 229, 255);
7438         outputColors1[1]                = RGBA(178, 127, 102, 255);
7439         outputColors1[2]                = RGBA(51,  255, 102, 255);
7440         outputColors1[3]                = RGBA(51,  127, 229, 255);
7441
7442         createTestsForAllStages("out_of_order", inputColors, outputColors1, fragments1, group.get());
7443
7444         const char      typesAndConstants2[]    =
7445                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7446
7447         // Add .4 to the second element of the given parameter.
7448         const char      function2[]                             =
7449                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7450                 "%param     = OpFunctionParameter %v4f32\n"
7451                 "%entry     = OpLabel\n"
7452                 "%result    = OpVariable %fp_v4f32 Function\n"
7453                 "             OpStore %result %param\n"
7454                 "%loc       = OpAccessChain %fp_f32 %result %c_i32_1\n"
7455                 "%val       = OpLoad %f32 %loc\n"
7456                 "             OpBranch %phi\n"
7457
7458                 "%phi        = OpLabel\n"
7459                 "%step       = OpPhi %i32 %c_i32_0  %entry %step_next  %phi\n"
7460                 "%accum      = OpPhi %f32 %val      %entry %accum_next %phi\n"
7461                 "%step_next  = OpIAdd %i32 %step  %c_i32_1\n"
7462                 "%accum_next = OpFAdd %f32 %accum %c_f32_p2\n"
7463                 "%still_loop = OpSLessThan %bool %step %c_i32_2\n"
7464                 "              OpLoopMerge %exit %phi None\n"
7465                 "              OpBranchConditional %still_loop %phi %exit\n"
7466
7467                 "%exit       = OpLabel\n"
7468                 "              OpStore %loc %accum\n"
7469                 "%ret        = OpLoad %v4f32 %result\n"
7470                 "              OpReturnValue %ret\n"
7471
7472                 "              OpFunctionEnd\n";
7473
7474         fragments2["pre_main"]  = typesAndConstants2;
7475         fragments2["testfun"]   = function2;
7476
7477         outputColors2[0]                        = RGBA(127, 229, 127, 255);
7478         outputColors2[1]                        = RGBA(127, 102, 0,   255);
7479         outputColors2[2]                        = RGBA(0,   229, 0,   255);
7480         outputColors2[3]                        = RGBA(0,   102, 127, 255);
7481
7482         createTestsForAllStages("induction", inputColors, outputColors2, fragments2, group.get());
7483
7484         const char      typesAndConstants3[]    =
7485                 "%true      = OpConstantTrue %bool\n"
7486                 "%false     = OpConstantFalse %bool\n"
7487                 "%c_f32_p2  = OpConstant %f32 0.2\n";
7488
7489         // Swap the second and the third element of the given parameter.
7490         const char      function3[]                             =
7491                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7492                 "%param     = OpFunctionParameter %v4f32\n"
7493                 "%entry     = OpLabel\n"
7494                 "%result    = OpVariable %fp_v4f32 Function\n"
7495                 "             OpStore %result %param\n"
7496                 "%a_loc     = OpAccessChain %fp_f32 %result %c_i32_1\n"
7497                 "%a_init    = OpLoad %f32 %a_loc\n"
7498                 "%b_loc     = OpAccessChain %fp_f32 %result %c_i32_2\n"
7499                 "%b_init    = OpLoad %f32 %b_loc\n"
7500                 "             OpBranch %phi\n"
7501
7502                 "%phi        = OpLabel\n"
7503                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7504                 "%a_next     = OpPhi %f32  %a_init %entry %b_next %phi\n"
7505                 "%b_next     = OpPhi %f32  %b_init %entry %a_next %phi\n"
7506                 "              OpLoopMerge %exit %phi None\n"
7507                 "              OpBranchConditional %still_loop %phi %exit\n"
7508
7509                 "%exit       = OpLabel\n"
7510                 "              OpStore %a_loc %a_next\n"
7511                 "              OpStore %b_loc %b_next\n"
7512                 "%ret        = OpLoad %v4f32 %result\n"
7513                 "              OpReturnValue %ret\n"
7514
7515                 "              OpFunctionEnd\n";
7516
7517         fragments3["pre_main"]  = typesAndConstants3;
7518         fragments3["testfun"]   = function3;
7519
7520         outputColors3[0]                        = RGBA(127, 127, 127, 255);
7521         outputColors3[1]                        = RGBA(127, 0,   0,   255);
7522         outputColors3[2]                        = RGBA(0,   0,   127, 255);
7523         outputColors3[3]                        = RGBA(0,   127, 0,   255);
7524
7525         createTestsForAllStages("swap", inputColors, outputColors3, fragments3, group.get());
7526
7527         const char      typesAndConstants4[]    =
7528                 "%f16        = OpTypeFloat 16\n"
7529                 "%v4f16      = OpTypeVector %f16 4\n"
7530                 "%fp_f16     = OpTypePointer Function %f16\n"
7531                 "%fp_v4f16   = OpTypePointer Function %v4f16\n"
7532                 "%true       = OpConstantTrue %bool\n"
7533                 "%false      = OpConstantFalse %bool\n"
7534                 "%c_f32_p2   = OpConstant %f32 0.2\n";
7535
7536         // Swap the second and the third element of the given parameter.
7537         const char      function4[]                             =
7538                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7539                 "%param      = OpFunctionParameter %v4f32\n"
7540                 "%entry      = OpLabel\n"
7541                 "%result     = OpVariable %fp_v4f16 Function\n"
7542                 "%param16    = OpFConvert %v4f16 %param\n"
7543                 "              OpStore %result %param16\n"
7544                 "%a_loc      = OpAccessChain %fp_f16 %result %c_i32_1\n"
7545                 "%a_init     = OpLoad %f16 %a_loc\n"
7546                 "%b_loc      = OpAccessChain %fp_f16 %result %c_i32_2\n"
7547                 "%b_init     = OpLoad %f16 %b_loc\n"
7548                 "              OpBranch %phi\n"
7549
7550                 "%phi        = OpLabel\n"
7551                 "%still_loop = OpPhi %bool %true   %entry %false  %phi\n"
7552                 "%a_next     = OpPhi %f16  %a_init %entry %b_next %phi\n"
7553                 "%b_next     = OpPhi %f16  %b_init %entry %a_next %phi\n"
7554                 "              OpLoopMerge %exit %phi None\n"
7555                 "              OpBranchConditional %still_loop %phi %exit\n"
7556
7557                 "%exit       = OpLabel\n"
7558                 "              OpStore %a_loc %a_next\n"
7559                 "              OpStore %b_loc %b_next\n"
7560                 "%ret16      = OpLoad %v4f16 %result\n"
7561                 "%ret        = OpFConvert %v4f32 %ret16\n"
7562                 "              OpReturnValue %ret\n"
7563
7564                 "              OpFunctionEnd\n";
7565
7566         fragments4["pre_main"]          = typesAndConstants4;
7567         fragments4["testfun"]           = function4;
7568         fragments4["capability"]        = "OpCapability StorageUniformBufferBlock16\n";
7569         fragments4["extension"]         = "OpExtension \"SPV_KHR_16bit_storage\"";
7570
7571         extensions4.push_back("VK_KHR_16bit_storage");
7572         extensions4.push_back("VK_KHR_shader_float16_int8");
7573
7574         vulkanFeatures4.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
7575         vulkanFeatures4.extFloat16Int8  = EXTFLOAT16INT8FEATURES_FLOAT16;
7576
7577         outputColors4[0]                        = RGBA(127, 127, 127, 255);
7578         outputColors4[1]                        = RGBA(127, 0,   0,   255);
7579         outputColors4[2]                        = RGBA(0,   0,   127, 255);
7580         outputColors4[3]                        = RGBA(0,   127, 0,   255);
7581
7582         createTestsForAllStages("swap16", inputColors, outputColors4, fragments4, resources4, extensions4, group.get(), vulkanFeatures4);
7583
7584         return group.release();
7585 }
7586
7587 tcu::TestCaseGroup* createNoContractionTests(tcu::TestContext& testCtx)
7588 {
7589         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "nocontraction", "Test the NoContraction decoration"));
7590         RGBA                                                    inputColors[4];
7591         RGBA                                                    outputColors[4];
7592
7593         // With NoContraction, (1 + 2^-23) * (1 - 2^-23) - 1 should be conducted as a multiplication and an addition separately.
7594         // For the multiplication, the result is 1 - 2^-46, which is out of the precision range for 32-bit float. (32-bit float
7595         // only have 23-bit fraction.) So it will be rounded to 1. Or 0x1.fffffc. Then the final result is 0 or -0x1p-24.
7596         // On the contrary, the result will be 2^-46, which is a normalized number perfectly representable as 32-bit float.
7597         const char                                              constantsAndTypes[]      =
7598                 "%c_vec4_0       = OpConstantComposite %v4f32 %c_f32_0 %c_f32_0 %c_f32_0 %c_f32_1\n"
7599                 "%c_vec4_1       = OpConstantComposite %v4f32 %c_f32_1 %c_f32_1 %c_f32_1 %c_f32_1\n"
7600                 "%c_f32_1pl2_23  = OpConstant %f32 0x1.000002p+0\n" // 1 + 2^-23
7601                 "%c_f32_1mi2_23  = OpConstant %f32 0x1.fffffcp-1\n" // 1 - 2^-23
7602                 "%c_f32_n1pn24   = OpConstant %f32 -0x1p-24\n";
7603
7604         const char                                              function[]       =
7605                 "%test_code      = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7606                 "%param          = OpFunctionParameter %v4f32\n"
7607                 "%label          = OpLabel\n"
7608                 "%var1           = OpVariable %fp_f32 Function %c_f32_1pl2_23\n"
7609                 "%var2           = OpVariable %fp_f32 Function\n"
7610                 "%red            = OpCompositeExtract %f32 %param 0\n"
7611                 "%plus_red       = OpFAdd %f32 %c_f32_1mi2_23 %red\n"
7612                 "                  OpStore %var2 %plus_red\n"
7613                 "%val1           = OpLoad %f32 %var1\n"
7614                 "%val2           = OpLoad %f32 %var2\n"
7615                 "%mul            = OpFMul %f32 %val1 %val2\n"
7616                 "%add            = OpFAdd %f32 %mul %c_f32_n1\n"
7617                 "%is0            = OpFOrdEqual %bool %add %c_f32_0\n"
7618                 "%isn1n24         = OpFOrdEqual %bool %add %c_f32_n1pn24\n"
7619                 "%success        = OpLogicalOr %bool %is0 %isn1n24\n"
7620                 "%v4success      = OpCompositeConstruct %v4bool %success %success %success %success\n"
7621                 "%ret            = OpSelect %v4f32 %v4success %c_vec4_0 %c_vec4_1\n"
7622                 "                  OpReturnValue %ret\n"
7623                 "                  OpFunctionEnd\n";
7624
7625         struct CaseNameDecoration
7626         {
7627                 string name;
7628                 string decoration;
7629         };
7630
7631
7632         CaseNameDecoration tests[] = {
7633                 {"multiplication",      "OpDecorate %mul NoContraction"},
7634                 {"addition",            "OpDecorate %add NoContraction"},
7635                 {"both",                        "OpDecorate %mul NoContraction\nOpDecorate %add NoContraction"},
7636         };
7637
7638         getHalfColorsFullAlpha(inputColors);
7639
7640         for (deUint8 idx = 0; idx < 4; ++idx)
7641         {
7642                 inputColors[idx].setRed(0);
7643                 outputColors[idx] = RGBA(0, 0, 0, 255);
7644         }
7645
7646         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(CaseNameDecoration); ++testNdx)
7647         {
7648                 map<string, string> fragments;
7649
7650                 fragments["decoration"] = tests[testNdx].decoration;
7651                 fragments["pre_main"] = constantsAndTypes;
7652                 fragments["testfun"] = function;
7653
7654                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, group.get());
7655         }
7656
7657         return group.release();
7658 }
7659
7660 tcu::TestCaseGroup* createMemoryAccessTests(tcu::TestContext& testCtx)
7661 {
7662         de::MovePtr<tcu::TestCaseGroup> memoryAccessTests (new tcu::TestCaseGroup(testCtx, "opmemoryaccess", "Memory Semantics"));
7663         RGBA                                                    colors[4];
7664
7665         const char                                              constantsAndTypes[]      =
7666                 "%c_a2f32_1         = OpConstantComposite %a2f32 %c_f32_1 %c_f32_1\n"
7667                 "%fp_a2f32          = OpTypePointer Function %a2f32\n"
7668                 "%stype             = OpTypeStruct  %v4f32 %a2f32 %f32\n"
7669                 "%fp_stype          = OpTypePointer Function %stype\n";
7670
7671         const char                                              function[]       =
7672                 "%test_code         = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7673                 "%param1            = OpFunctionParameter %v4f32\n"
7674                 "%lbl               = OpLabel\n"
7675                 "%v1                = OpVariable %fp_v4f32 Function\n"
7676                 "%v2                = OpVariable %fp_a2f32 Function\n"
7677                 "%v3                = OpVariable %fp_f32 Function\n"
7678                 "%v                 = OpVariable %fp_stype Function\n"
7679                 "%vv                = OpVariable %fp_stype Function\n"
7680                 "%vvv               = OpVariable %fp_f32 Function\n"
7681
7682                 "                     OpStore %v1 %c_v4f32_1_1_1_1\n"
7683                 "                     OpStore %v2 %c_a2f32_1\n"
7684                 "                     OpStore %v3 %c_f32_1\n"
7685
7686                 "%p_v4f32          = OpAccessChain %fp_v4f32 %v %c_u32_0\n"
7687                 "%p_a2f32          = OpAccessChain %fp_a2f32 %v %c_u32_1\n"
7688                 "%p_f32            = OpAccessChain %fp_f32 %v %c_u32_2\n"
7689                 "%v1_v             = OpLoad %v4f32 %v1 ${access_type}\n"
7690                 "%v2_v             = OpLoad %a2f32 %v2 ${access_type}\n"
7691                 "%v3_v             = OpLoad %f32 %v3 ${access_type}\n"
7692
7693                 "                    OpStore %p_v4f32 %v1_v ${access_type}\n"
7694                 "                    OpStore %p_a2f32 %v2_v ${access_type}\n"
7695                 "                    OpStore %p_f32 %v3_v ${access_type}\n"
7696
7697                 "                    OpCopyMemory %vv %v ${access_type}\n"
7698                 "                    OpCopyMemory %vvv %p_f32 ${access_type}\n"
7699
7700                 "%p_f32_2          = OpAccessChain %fp_f32 %vv %c_u32_2\n"
7701                 "%v_f32_2          = OpLoad %f32 %p_f32_2\n"
7702                 "%v_f32_3          = OpLoad %f32 %vvv\n"
7703
7704                 "%ret1             = OpVectorTimesScalar %v4f32 %param1 %v_f32_2\n"
7705                 "%ret2             = OpVectorTimesScalar %v4f32 %ret1 %v_f32_3\n"
7706                 "                    OpReturnValue %ret2\n"
7707                 "                    OpFunctionEnd\n";
7708
7709         struct NameMemoryAccess
7710         {
7711                 string name;
7712                 string accessType;
7713         };
7714
7715
7716         NameMemoryAccess tests[] =
7717         {
7718                 { "none", "" },
7719                 { "volatile", "Volatile" },
7720                 { "aligned",  "Aligned 1" },
7721                 { "volatile_aligned",  "Volatile|Aligned 1" },
7722                 { "nontemporal_aligned",  "Nontemporal|Aligned 1" },
7723                 { "volatile_nontemporal",  "Volatile|Nontemporal" },
7724                 { "volatile_nontermporal_aligned",  "Volatile|Nontemporal|Aligned 1" },
7725         };
7726
7727         getHalfColorsFullAlpha(colors);
7728
7729         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameMemoryAccess); ++testNdx)
7730         {
7731                 map<string, string> fragments;
7732                 map<string, string> memoryAccess;
7733                 memoryAccess["access_type"] = tests[testNdx].accessType;
7734
7735                 fragments["pre_main"] = constantsAndTypes;
7736                 fragments["testfun"] = tcu::StringTemplate(function).specialize(memoryAccess);
7737                 createTestsForAllStages(tests[testNdx].name, colors, colors, fragments, memoryAccessTests.get());
7738         }
7739         return memoryAccessTests.release();
7740 }
7741 tcu::TestCaseGroup* createOpUndefTests(tcu::TestContext& testCtx)
7742 {
7743         de::MovePtr<tcu::TestCaseGroup>         opUndefTests             (new tcu::TestCaseGroup(testCtx, "opundef", "Test OpUndef"));
7744         RGBA                                                            defaultColors[4];
7745         map<string, string>                                     fragments;
7746         getDefaultColors(defaultColors);
7747
7748         // First, simple cases that don't do anything with the OpUndef result.
7749         struct NameCodePair { string name, decl, type; };
7750         const NameCodePair tests[] =
7751         {
7752                 {"bool", "", "%bool"},
7753                 {"vec2uint32", "", "%v2u32"},
7754                 {"image", "%type = OpTypeImage %f32 2D 0 0 0 1 Unknown", "%type"},
7755                 {"sampler", "%type = OpTypeSampler", "%type"},
7756                 {"sampledimage", "%img = OpTypeImage %f32 2D 0 0 0 1 Unknown\n" "%type = OpTypeSampledImage %img", "%type"},
7757                 {"pointer", "", "%fp_i32"},
7758                 {"runtimearray", "%type = OpTypeRuntimeArray %f32", "%type"},
7759                 {"array", "%c_u32_100 = OpConstant %u32 100\n" "%type = OpTypeArray %i32 %c_u32_100", "%type"},
7760                 {"struct", "%type = OpTypeStruct %f32 %i32 %u32", "%type"}};
7761         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameCodePair); ++testNdx)
7762         {
7763                 fragments["undef_type"] = tests[testNdx].type;
7764                 fragments["testfun"] = StringTemplate(
7765                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7766                         "%param1 = OpFunctionParameter %v4f32\n"
7767                         "%label_testfun = OpLabel\n"
7768                         "%undef = OpUndef ${undef_type}\n"
7769                         "OpReturnValue %param1\n"
7770                         "OpFunctionEnd\n").specialize(fragments);
7771                 fragments["pre_main"] = tests[testNdx].decl;
7772                 createTestsForAllStages(tests[testNdx].name, defaultColors, defaultColors, fragments, opUndefTests.get());
7773         }
7774         fragments.clear();
7775
7776         fragments["testfun"] =
7777                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7778                 "%param1 = OpFunctionParameter %v4f32\n"
7779                 "%label_testfun = OpLabel\n"
7780                 "%undef = OpUndef %f32\n"
7781                 "%zero = OpFMul %f32 %undef %c_f32_0\n"
7782                 "%is_nan = OpIsNan %bool %zero\n" //OpUndef may result in NaN which may turn %zero into Nan.
7783                 "%actually_zero = OpSelect %f32 %is_nan %c_f32_0 %zero\n"
7784                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7785                 "%b = OpFAdd %f32 %a %actually_zero\n"
7786                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %b %c_i32_0\n"
7787                 "OpReturnValue %ret\n"
7788                 "OpFunctionEnd\n";
7789
7790         createTestsForAllStages("float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7791
7792         fragments["testfun"] =
7793                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7794                 "%param1 = OpFunctionParameter %v4f32\n"
7795                 "%label_testfun = OpLabel\n"
7796                 "%undef = OpUndef %i32\n"
7797                 "%zero = OpIMul %i32 %undef %c_i32_0\n"
7798                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7799                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7800                 "OpReturnValue %ret\n"
7801                 "OpFunctionEnd\n";
7802
7803         createTestsForAllStages("sint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7804
7805         fragments["testfun"] =
7806                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7807                 "%param1 = OpFunctionParameter %v4f32\n"
7808                 "%label_testfun = OpLabel\n"
7809                 "%undef = OpUndef %u32\n"
7810                 "%zero = OpIMul %u32 %undef %c_i32_0\n"
7811                 "%a = OpVectorExtractDynamic %f32 %param1 %zero\n"
7812                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %a %c_i32_0\n"
7813                 "OpReturnValue %ret\n"
7814                 "OpFunctionEnd\n";
7815
7816         createTestsForAllStages("uint32", defaultColors, defaultColors, fragments, opUndefTests.get());
7817
7818         fragments["testfun"] =
7819                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7820                 "%param1 = OpFunctionParameter %v4f32\n"
7821                 "%label_testfun = OpLabel\n"
7822                 "%undef = OpUndef %v4f32\n"
7823                 "%vzero = OpVectorTimesScalar %v4f32 %undef %c_f32_0\n"
7824                 "%zero_0 = OpVectorExtractDynamic %f32 %vzero %c_i32_0\n"
7825                 "%zero_1 = OpVectorExtractDynamic %f32 %vzero %c_i32_1\n"
7826                 "%zero_2 = OpVectorExtractDynamic %f32 %vzero %c_i32_2\n"
7827                 "%zero_3 = OpVectorExtractDynamic %f32 %vzero %c_i32_3\n"
7828                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7829                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7830                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7831                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7832                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7833                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7834                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7835                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7836                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7837                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7838                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7839                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7840                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7841                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7842                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7843                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7844                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7845                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7846                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7847                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7848                 "OpReturnValue %ret\n"
7849                 "OpFunctionEnd\n";
7850
7851         createTestsForAllStages("vec4float32", defaultColors, defaultColors, fragments, opUndefTests.get());
7852
7853         fragments["pre_main"] =
7854                 "%m2x2f32 = OpTypeMatrix %v2f32 2\n";
7855         fragments["testfun"] =
7856                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
7857                 "%param1 = OpFunctionParameter %v4f32\n"
7858                 "%label_testfun = OpLabel\n"
7859                 "%undef = OpUndef %m2x2f32\n"
7860                 "%mzero = OpMatrixTimesScalar %m2x2f32 %undef %c_f32_0\n"
7861                 "%zero_0 = OpCompositeExtract %f32 %mzero 0 0\n"
7862                 "%zero_1 = OpCompositeExtract %f32 %mzero 0 1\n"
7863                 "%zero_2 = OpCompositeExtract %f32 %mzero 1 0\n"
7864                 "%zero_3 = OpCompositeExtract %f32 %mzero 1 1\n"
7865                 "%is_nan_0 = OpIsNan %bool %zero_0\n"
7866                 "%is_nan_1 = OpIsNan %bool %zero_1\n"
7867                 "%is_nan_2 = OpIsNan %bool %zero_2\n"
7868                 "%is_nan_3 = OpIsNan %bool %zero_3\n"
7869                 "%actually_zero_0 = OpSelect %f32 %is_nan_0 %c_f32_0 %zero_0\n"
7870                 "%actually_zero_1 = OpSelect %f32 %is_nan_1 %c_f32_0 %zero_1\n"
7871                 "%actually_zero_2 = OpSelect %f32 %is_nan_2 %c_f32_0 %zero_2\n"
7872                 "%actually_zero_3 = OpSelect %f32 %is_nan_3 %c_f32_0 %zero_3\n"
7873                 "%param1_0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
7874                 "%param1_1 = OpVectorExtractDynamic %f32 %param1 %c_i32_1\n"
7875                 "%param1_2 = OpVectorExtractDynamic %f32 %param1 %c_i32_2\n"
7876                 "%param1_3 = OpVectorExtractDynamic %f32 %param1 %c_i32_3\n"
7877                 "%sum_0 = OpFAdd %f32 %param1_0 %actually_zero_0\n"
7878                 "%sum_1 = OpFAdd %f32 %param1_1 %actually_zero_1\n"
7879                 "%sum_2 = OpFAdd %f32 %param1_2 %actually_zero_2\n"
7880                 "%sum_3 = OpFAdd %f32 %param1_3 %actually_zero_3\n"
7881                 "%ret3 = OpVectorInsertDynamic %v4f32 %param1 %sum_3 %c_i32_3\n"
7882                 "%ret2 = OpVectorInsertDynamic %v4f32 %ret3 %sum_2 %c_i32_2\n"
7883                 "%ret1 = OpVectorInsertDynamic %v4f32 %ret2 %sum_1 %c_i32_1\n"
7884                 "%ret = OpVectorInsertDynamic %v4f32 %ret1 %sum_0 %c_i32_0\n"
7885                 "OpReturnValue %ret\n"
7886                 "OpFunctionEnd\n";
7887
7888         createTestsForAllStages("matrix", defaultColors, defaultColors, fragments, opUndefTests.get());
7889
7890         return opUndefTests.release();
7891 }
7892
7893 void createOpQuantizeSingleOptionTests(tcu::TestCaseGroup* testCtx)
7894 {
7895         const RGBA              inputColors[4]          =
7896         {
7897                 RGBA(0,         0,              0,              255),
7898                 RGBA(0,         0,              255,    255),
7899                 RGBA(0,         255,    0,              255),
7900                 RGBA(0,         255,    255,    255)
7901         };
7902
7903         const RGBA              expectedColors[4]       =
7904         {
7905                 RGBA(255,        0,              0,              255),
7906                 RGBA(255,        0,              0,              255),
7907                 RGBA(255,        0,              0,              255),
7908                 RGBA(255,        0,              0,              255)
7909         };
7910
7911         const struct SingleFP16Possibility
7912         {
7913                 const char* name;
7914                 const char* constant;  // Value to assign to %test_constant.
7915                 float           valueAsFloat;
7916                 const char* condition; // Must assign to %cond an expression that evaluates to true after %c = OpQuantizeToF16(%test_constant + 0).
7917         }                               tests[]                         =
7918         {
7919                 {
7920                         "negative",
7921                         "-0x1.3p1\n",
7922                         -constructNormalizedFloat(1, 0x300000),
7923                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7924                 }, // -19
7925                 {
7926                         "positive",
7927                         "0x1.0p7\n",
7928                         constructNormalizedFloat(7, 0x000000),
7929                         "%cond = OpFOrdEqual %bool %c %test_constant\n"
7930                 },  // +128
7931                 // SPIR-V requires that OpQuantizeToF16 flushes
7932                 // any numbers that would end up denormalized in F16 to zero.
7933                 {
7934                         "denorm",
7935                         "0x0.0006p-126\n",
7936                         std::ldexp(1.5f, -140),
7937                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7938                 },  // denorm
7939                 {
7940                         "negative_denorm",
7941                         "-0x0.0006p-126\n",
7942                         -std::ldexp(1.5f, -140),
7943                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7944                 }, // -denorm
7945                 {
7946                         "too_small",
7947                         "0x1.0p-16\n",
7948                         std::ldexp(1.0f, -16),
7949                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7950                 },     // too small positive
7951                 {
7952                         "negative_too_small",
7953                         "-0x1.0p-32\n",
7954                         -std::ldexp(1.0f, -32),
7955                         "%cond = OpFOrdEqual %bool %c %c_f32_0\n"
7956                 },      // too small negative
7957                 {
7958                         "negative_inf",
7959                         "-0x1.0p128\n",
7960                         -std::ldexp(1.0f, 128),
7961
7962                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7963                         "%inf = OpIsInf %bool %c\n"
7964                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7965                 },     // -inf to -inf
7966                 {
7967                         "inf",
7968                         "0x1.0p128\n",
7969                         std::ldexp(1.0f, 128),
7970
7971                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7972                         "%inf = OpIsInf %bool %c\n"
7973                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7974                 },     // +inf to +inf
7975                 {
7976                         "round_to_negative_inf",
7977                         "-0x1.0p32\n",
7978                         -std::ldexp(1.0f, 32),
7979
7980                         "%gz = OpFOrdLessThan %bool %c %c_f32_0\n"
7981                         "%inf = OpIsInf %bool %c\n"
7982                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7983                 },     // round to -inf
7984                 {
7985                         "round_to_inf",
7986                         "0x1.0p16\n",
7987                         std::ldexp(1.0f, 16),
7988
7989                         "%gz = OpFOrdGreaterThan %bool %c %c_f32_0\n"
7990                         "%inf = OpIsInf %bool %c\n"
7991                         "%cond = OpLogicalAnd %bool %gz %inf\n"
7992                 },     // round to +inf
7993                 {
7994                         "nan",
7995                         "0x1.1p128\n",
7996                         std::numeric_limits<float>::quiet_NaN(),
7997
7998                         // Test for any NaN value, as NaNs are not preserved
7999                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
8000                         "%cond = OpIsNan %bool %direct_quant\n"
8001                 }, // nan
8002                 {
8003                         "negative_nan",
8004                         "-0x1.0001p128\n",
8005                         std::numeric_limits<float>::quiet_NaN(),
8006
8007                         // Test for any NaN value, as NaNs are not preserved
8008                         "%direct_quant = OpQuantizeToF16 %f32 %test_constant\n"
8009                         "%cond = OpIsNan %bool %direct_quant\n"
8010                 } // -nan
8011         };
8012         const char*             constants                       =
8013                 "%test_constant = OpConstant %f32 ";  // The value will be test.constant.
8014
8015         StringTemplate  function                        (
8016                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8017                 "%param1        = OpFunctionParameter %v4f32\n"
8018                 "%label_testfun = OpLabel\n"
8019                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8020                 "%b             = OpFAdd %f32 %test_constant %a\n"
8021                 "%c             = OpQuantizeToF16 %f32 %b\n"
8022                 "${condition}\n"
8023                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8024                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
8025                 "                 OpReturnValue %retval\n"
8026                 "OpFunctionEnd\n"
8027         );
8028
8029         const char*             specDecorations         = "OpDecorate %test_constant SpecId 0\n";
8030         const char*             specConstants           =
8031                         "%test_constant = OpSpecConstant %f32 0.\n"
8032                         "%c             = OpSpecConstantOp %f32 QuantizeToF16 %test_constant\n";
8033
8034         StringTemplate  specConstantFunction(
8035                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8036                 "%param1        = OpFunctionParameter %v4f32\n"
8037                 "%label_testfun = OpLabel\n"
8038                 "${condition}\n"
8039                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8040                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1\n"
8041                 "                 OpReturnValue %retval\n"
8042                 "OpFunctionEnd\n"
8043         );
8044
8045         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
8046         {
8047                 map<string, string>                                                             codeSpecialization;
8048                 map<string, string>                                                             fragments;
8049                 codeSpecialization["condition"]                                 = tests[idx].condition;
8050                 fragments["testfun"]                                                    = function.specialize(codeSpecialization);
8051                 fragments["pre_main"]                                                   = string(constants) + tests[idx].constant + "\n";
8052                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
8053         }
8054
8055         for (size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx)
8056         {
8057                 map<string, string>                                                             codeSpecialization;
8058                 map<string, string>                                                             fragments;
8059                 SpecConstants                                                                   passConstants;
8060
8061                 codeSpecialization["condition"]                                 = tests[idx].condition;
8062                 fragments["testfun"]                                                    = specConstantFunction.specialize(codeSpecialization);
8063                 fragments["decoration"]                                                 = specDecorations;
8064                 fragments["pre_main"]                                                   = specConstants;
8065
8066                 passConstants.append<float>(tests[idx].valueAsFloat);
8067
8068                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
8069         }
8070 }
8071
8072 void createOpQuantizeTwoPossibilityTests(tcu::TestCaseGroup* testCtx)
8073 {
8074         RGBA inputColors[4] =  {
8075                 RGBA(0,         0,              0,              255),
8076                 RGBA(0,         0,              255,    255),
8077                 RGBA(0,         255,    0,              255),
8078                 RGBA(0,         255,    255,    255)
8079         };
8080
8081         RGBA expectedColors[4] =
8082         {
8083                 RGBA(255,        0,              0,              255),
8084                 RGBA(255,        0,              0,              255),
8085                 RGBA(255,        0,              0,              255),
8086                 RGBA(255,        0,              0,              255)
8087         };
8088
8089         struct DualFP16Possibility
8090         {
8091                 const char* name;
8092                 const char* input;
8093                 float           inputAsFloat;
8094                 const char* possibleOutput1;
8095                 const char* possibleOutput2;
8096         } tests[] = {
8097                 {
8098                         "positive_round_up_or_round_down",
8099                         "0x1.3003p8",
8100                         constructNormalizedFloat(8, 0x300300),
8101                         "0x1.304p8",
8102                         "0x1.3p8"
8103                 },
8104                 {
8105                         "negative_round_up_or_round_down",
8106                         "-0x1.6008p-7",
8107                         -constructNormalizedFloat(-7, 0x600800),
8108                         "-0x1.6p-7",
8109                         "-0x1.604p-7"
8110                 },
8111                 {
8112                         "carry_bit",
8113                         "0x1.01ep2",
8114                         constructNormalizedFloat(2, 0x01e000),
8115                         "0x1.01cp2",
8116                         "0x1.02p2"
8117                 },
8118                 {
8119                         "carry_to_exponent",
8120                         "0x1.ffep1",
8121                         constructNormalizedFloat(1, 0xffe000),
8122                         "0x1.ffcp1",
8123                         "0x1.0p2"
8124                 },
8125         };
8126         StringTemplate constants (
8127                 "%input_const = OpConstant %f32 ${input}\n"
8128                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8129                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8130                 );
8131
8132         StringTemplate specConstants (
8133                 "%input_const = OpSpecConstant %f32 0.\n"
8134                 "%possible_solution1 = OpConstant %f32 ${output1}\n"
8135                 "%possible_solution2 = OpConstant %f32 ${output2}\n"
8136         );
8137
8138         const char* specDecorations = "OpDecorate %input_const  SpecId 0\n";
8139
8140         const char* function  =
8141                 "%test_code     = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8142                 "%param1        = OpFunctionParameter %v4f32\n"
8143                 "%label_testfun = OpLabel\n"
8144                 "%a             = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8145                 // For the purposes of this test we assume that 0.f will always get
8146                 // faithfully passed through the pipeline stages.
8147                 "%b             = OpFAdd %f32 %input_const %a\n"
8148                 "%c             = OpQuantizeToF16 %f32 %b\n"
8149                 "%eq_1          = OpFOrdEqual %bool %c %possible_solution1\n"
8150                 "%eq_2          = OpFOrdEqual %bool %c %possible_solution2\n"
8151                 "%cond          = OpLogicalOr %bool %eq_1 %eq_2\n"
8152                 "%v4cond        = OpCompositeConstruct %v4bool %cond %cond %cond %cond\n"
8153                 "%retval        = OpSelect %v4f32 %v4cond %c_v4f32_1_0_0_1 %param1"
8154                 "                 OpReturnValue %retval\n"
8155                 "OpFunctionEnd\n";
8156
8157         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8158                 map<string, string>                                                                     fragments;
8159                 map<string, string>                                                                     constantSpecialization;
8160
8161                 constantSpecialization["input"]                                         = tests[idx].input;
8162                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8163                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8164                 fragments["testfun"]                                                            = function;
8165                 fragments["pre_main"]                                                           = constants.specialize(constantSpecialization);
8166                 createTestsForAllStages(tests[idx].name, inputColors, expectedColors, fragments, testCtx);
8167         }
8168
8169         for(size_t idx = 0; idx < (sizeof(tests)/sizeof(tests[0])); ++idx) {
8170                 map<string, string>                                                                     fragments;
8171                 map<string, string>                                                                     constantSpecialization;
8172                 SpecConstants                                                                           passConstants;
8173
8174                 constantSpecialization["output1"]                                       = tests[idx].possibleOutput1;
8175                 constantSpecialization["output2"]                                       = tests[idx].possibleOutput2;
8176                 fragments["testfun"]                                                            = function;
8177                 fragments["decoration"]                                                         = specDecorations;
8178                 fragments["pre_main"]                                                           = specConstants.specialize(constantSpecialization);
8179
8180                 passConstants.append<float>(tests[idx].inputAsFloat);
8181
8182                 createTestsForAllStages(string("spec_const_") + tests[idx].name, inputColors, expectedColors, fragments, passConstants, testCtx);
8183         }
8184 }
8185
8186 tcu::TestCaseGroup* createOpQuantizeTests(tcu::TestContext& testCtx)
8187 {
8188         de::MovePtr<tcu::TestCaseGroup> opQuantizeTests (new tcu::TestCaseGroup(testCtx, "opquantize", "Test OpQuantizeToF16"));
8189         createOpQuantizeSingleOptionTests(opQuantizeTests.get());
8190         createOpQuantizeTwoPossibilityTests(opQuantizeTests.get());
8191         return opQuantizeTests.release();
8192 }
8193
8194 struct ShaderPermutation
8195 {
8196         deUint8 vertexPermutation;
8197         deUint8 geometryPermutation;
8198         deUint8 tesscPermutation;
8199         deUint8 tessePermutation;
8200         deUint8 fragmentPermutation;
8201 };
8202
8203 ShaderPermutation getShaderPermutation(deUint8 inputValue)
8204 {
8205         ShaderPermutation       permutation =
8206         {
8207                 static_cast<deUint8>(inputValue & 0x10? 1u: 0u),
8208                 static_cast<deUint8>(inputValue & 0x08? 1u: 0u),
8209                 static_cast<deUint8>(inputValue & 0x04? 1u: 0u),
8210                 static_cast<deUint8>(inputValue & 0x02? 1u: 0u),
8211                 static_cast<deUint8>(inputValue & 0x01? 1u: 0u)
8212         };
8213         return permutation;
8214 }
8215
8216 tcu::TestCaseGroup* createModuleTests(tcu::TestContext& testCtx)
8217 {
8218         RGBA                                                            defaultColors[4];
8219         RGBA                                                            invertedColors[4];
8220         de::MovePtr<tcu::TestCaseGroup>         moduleTests                     (new tcu::TestCaseGroup(testCtx, "module", "Multiple entry points into shaders"));
8221
8222         getDefaultColors(defaultColors);
8223         getInvertedDefaultColors(invertedColors);
8224
8225         // Combined module tests
8226         {
8227                 // Shader stages: vertex and fragment
8228                 {
8229                         const ShaderElement combinedPipeline[]  =
8230                         {
8231                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8232                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8233                         };
8234
8235                         addFunctionCaseWithPrograms<InstanceContext>(
8236                                 moduleTests.get(), "same_module", "", createCombinedModule, runAndVerifyDefaultPipeline,
8237                                 createInstanceContext(combinedPipeline, map<string, string>()));
8238                 }
8239
8240                 // Shader stages: vertex, geometry and fragment
8241                 {
8242                         const ShaderElement combinedPipeline[]  =
8243                         {
8244                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8245                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8246                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8247                         };
8248
8249                         addFunctionCaseWithPrograms<InstanceContext>(
8250                                 moduleTests.get(), "same_module_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8251                                 createInstanceContext(combinedPipeline, map<string, string>()));
8252                 }
8253
8254                 // Shader stages: vertex, tessellation control, tessellation evaluation and fragment
8255                 {
8256                         const ShaderElement combinedPipeline[]  =
8257                         {
8258                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8259                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8260                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8261                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8262                         };
8263
8264                         addFunctionCaseWithPrograms<InstanceContext>(
8265                                 moduleTests.get(), "same_module_tessc_tesse", "", createCombinedModule, runAndVerifyDefaultPipeline,
8266                                 createInstanceContext(combinedPipeline, map<string, string>()));
8267                 }
8268
8269                 // Shader stages: vertex, tessellation control, tessellation evaluation, geometry and fragment
8270                 {
8271                         const ShaderElement combinedPipeline[]  =
8272                         {
8273                                 ShaderElement("module", "main", VK_SHADER_STAGE_VERTEX_BIT),
8274                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8275                                 ShaderElement("module", "main", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8276                                 ShaderElement("module", "main", VK_SHADER_STAGE_GEOMETRY_BIT),
8277                                 ShaderElement("module", "main", VK_SHADER_STAGE_FRAGMENT_BIT)
8278                         };
8279
8280                         addFunctionCaseWithPrograms<InstanceContext>(
8281                                 moduleTests.get(), "same_module_tessc_tesse_geom", "", createCombinedModule, runAndVerifyDefaultPipeline,
8282                                 createInstanceContext(combinedPipeline, map<string, string>()));
8283                 }
8284         }
8285
8286         const char* numbers[] =
8287         {
8288                 "1", "2"
8289         };
8290
8291         for (deInt8 idx = 0; idx < 32; ++idx)
8292         {
8293                 ShaderPermutation                       permutation             = getShaderPermutation(idx);
8294                 string                                          name                    = string("vert") + numbers[permutation.vertexPermutation] + "_geom" + numbers[permutation.geometryPermutation] + "_tessc" + numbers[permutation.tesscPermutation] + "_tesse" + numbers[permutation.tessePermutation] + "_frag" + numbers[permutation.fragmentPermutation];
8295                 const ShaderElement                     pipeline[]              =
8296                 {
8297                         ShaderElement("vert",   string("vert") +        numbers[permutation.vertexPermutation],         VK_SHADER_STAGE_VERTEX_BIT),
8298                         ShaderElement("geom",   string("geom") +        numbers[permutation.geometryPermutation],       VK_SHADER_STAGE_GEOMETRY_BIT),
8299                         ShaderElement("tessc",  string("tessc") +       numbers[permutation.tesscPermutation],          VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT),
8300                         ShaderElement("tesse",  string("tesse") +       numbers[permutation.tessePermutation],          VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT),
8301                         ShaderElement("frag",   string("frag") +        numbers[permutation.fragmentPermutation],       VK_SHADER_STAGE_FRAGMENT_BIT)
8302                 };
8303
8304                 // If there are an even number of swaps, then it should be no-op.
8305                 // If there are an odd number, the color should be flipped.
8306                 if ((permutation.vertexPermutation + permutation.geometryPermutation + permutation.tesscPermutation + permutation.tessePermutation + permutation.fragmentPermutation) % 2 == 0)
8307                 {
8308                         addFunctionCaseWithPrograms<InstanceContext>(
8309                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8310                                         createInstanceContext(pipeline, defaultColors, defaultColors, map<string, string>()));
8311                 }
8312                 else
8313                 {
8314                         addFunctionCaseWithPrograms<InstanceContext>(
8315                                         moduleTests.get(), name, "", createMultipleEntries, runAndVerifyDefaultPipeline,
8316                                         createInstanceContext(pipeline, defaultColors, invertedColors, map<string, string>()));
8317                 }
8318         }
8319         return moduleTests.release();
8320 }
8321
8322 std::string getUnusedVarTestNamePiece(const std::string& prefix, ShaderTask task)
8323 {
8324         switch (task)
8325         {
8326                 case SHADER_TASK_NONE:                  return "";
8327                 case SHADER_TASK_NORMAL:                return prefix + "_normal";
8328                 case SHADER_TASK_UNUSED_VAR:    return prefix + "_unused_var";
8329                 case SHADER_TASK_UNUSED_FUNC:   return prefix + "_unused_func";
8330                 default:                                                DE_ASSERT(DE_FALSE);
8331         }
8332         // unreachable
8333         return "";
8334 }
8335
8336 std::string getShaderTaskIndexName(ShaderTaskIndex index)
8337 {
8338         switch (index)
8339         {
8340         case SHADER_TASK_INDEX_VERTEX:                  return "vertex";
8341         case SHADER_TASK_INDEX_GEOMETRY:                return "geom";
8342         case SHADER_TASK_INDEX_TESS_CONTROL:    return "tessc";
8343         case SHADER_TASK_INDEX_TESS_EVAL:               return "tesse";
8344         case SHADER_TASK_INDEX_FRAGMENT:                return "frag";
8345         default:                                                                DE_ASSERT(DE_FALSE);
8346         }
8347         // unreachable
8348         return "";
8349 }
8350
8351 std::string getUnusedVarTestName(const ShaderTaskArray& shaderTasks, const VariableLocation& location)
8352 {
8353         std::string testName = location.toString();
8354
8355         for (size_t i = 0; i < DE_LENGTH_OF_ARRAY(shaderTasks); ++i)
8356         {
8357                 if (shaderTasks[i] != SHADER_TASK_NONE)
8358                 {
8359                         testName += "_" + getUnusedVarTestNamePiece(getShaderTaskIndexName((ShaderTaskIndex)i), shaderTasks[i]);
8360                 }
8361         }
8362
8363         return testName;
8364 }
8365
8366 tcu::TestCaseGroup* createUnusedVariableTests(tcu::TestContext& testCtx)
8367 {
8368         de::MovePtr<tcu::TestCaseGroup>         moduleTests                             (new tcu::TestCaseGroup(testCtx, "unused_variables", "Graphics shaders with unused variables"));
8369
8370         ShaderTaskArray                                         shaderCombinations[]    =
8371         {
8372                 // Vertex                                       Geometry                                        Tess. Control                           Tess. Evaluation                        Fragment
8373                 { SHADER_TASK_UNUSED_VAR,       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8374                 { SHADER_TASK_UNUSED_FUNC,      SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8375                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_VAR  },
8376                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_FUNC },
8377                 { SHADER_TASK_NORMAL,           SHADER_TASK_UNUSED_VAR,         SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8378                 { SHADER_TASK_NORMAL,           SHADER_TASK_UNUSED_FUNC,        SHADER_TASK_NONE,                       SHADER_TASK_NONE,                       SHADER_TASK_NORMAL      },
8379                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_VAR,         SHADER_TASK_NORMAL,                     SHADER_TASK_NORMAL      },
8380                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_UNUSED_FUNC,        SHADER_TASK_NORMAL,                     SHADER_TASK_NORMAL      },
8381                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NORMAL,                     SHADER_TASK_UNUSED_VAR,         SHADER_TASK_NORMAL      },
8382                 { SHADER_TASK_NORMAL,           SHADER_TASK_NONE,                       SHADER_TASK_NORMAL,                     SHADER_TASK_UNUSED_FUNC,        SHADER_TASK_NORMAL      }
8383         };
8384
8385         const VariableLocation                          testLocations[] =
8386         {
8387                 // Set          Binding
8388                 { 0,            5                       },
8389                 { 5,            5                       },
8390         };
8391
8392         for (size_t combNdx = 0; combNdx < DE_LENGTH_OF_ARRAY(shaderCombinations); ++combNdx)
8393         {
8394                 for (size_t locationNdx = 0; locationNdx < DE_LENGTH_OF_ARRAY(testLocations); ++locationNdx)
8395                 {
8396                         const ShaderTaskArray&  shaderTasks             = shaderCombinations[combNdx];
8397                         const VariableLocation& location                = testLocations[locationNdx];
8398                         std::string                             testName                = getUnusedVarTestName(shaderTasks, location);
8399
8400                         addFunctionCaseWithPrograms<UnusedVariableContext>(
8401                                 moduleTests.get(), testName, "", createUnusedVariableModules, runAndVerifyUnusedVariablePipeline,
8402                                 createUnusedVariableContext(shaderTasks, location));
8403                 }
8404         }
8405
8406         return moduleTests.release();
8407 }
8408
8409 tcu::TestCaseGroup* createLoopTests(tcu::TestContext& testCtx)
8410 {
8411         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "loop", "Looping control flow"));
8412         RGBA defaultColors[4];
8413         getDefaultColors(defaultColors);
8414         map<string, string> fragments;
8415         fragments["pre_main"] =
8416                 "%c_f32_5 = OpConstant %f32 5.\n";
8417
8418         // A loop with a single block. The Continue Target is the loop block
8419         // itself. In SPIR-V terms, the "loop construct" contains no blocks at all
8420         // -- the "continue construct" forms the entire loop.
8421         fragments["testfun"] =
8422                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8423                 "%param1 = OpFunctionParameter %v4f32\n"
8424
8425                 "%entry = OpLabel\n"
8426                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8427                 "OpBranch %loop\n"
8428
8429                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8430                 "%loop = OpLabel\n"
8431                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8432                 "%delta = OpPhi %f32 %c_f32_1 %entry %minus_delta %loop\n"
8433                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8434                 "%val = OpFAdd %f32 %val1 %delta\n"
8435                 "%minus_delta = OpFSub %f32 %c_f32_0 %delta\n"
8436                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8437                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8438                 "OpLoopMerge %exit %loop None\n"
8439                 "OpBranchConditional %again %loop %exit\n"
8440
8441                 "%exit = OpLabel\n"
8442                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8443                 "OpReturnValue %result\n"
8444
8445                 "OpFunctionEnd\n";
8446
8447         createTestsForAllStages("single_block", defaultColors, defaultColors, fragments, testGroup.get());
8448
8449         // Body comprised of multiple basic blocks.
8450         const StringTemplate multiBlock(
8451                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8452                 "%param1 = OpFunctionParameter %v4f32\n"
8453
8454                 "%entry = OpLabel\n"
8455                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8456                 "OpBranch %loop\n"
8457
8458                 ";adds and subtracts 1.0 to %val in alternate iterations\n"
8459                 "%loop = OpLabel\n"
8460                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %gather\n"
8461                 "%delta = OpPhi %f32 %c_f32_1 %entry %delta_next %gather\n"
8462                 "%val1 = OpPhi %f32 %val0 %entry %val %gather\n"
8463                 // There are several possibilities for the Continue Target below.  Each
8464                 // will be specialized into a separate test case.
8465                 "OpLoopMerge %exit ${continue_target} None\n"
8466                 "OpBranch %if\n"
8467
8468                 "%if = OpLabel\n"
8469                 ";delta_next = (delta > 0) ? -1 : 1;\n"
8470                 "%gt0 = OpFOrdGreaterThan %bool %delta %c_f32_0\n"
8471                 "OpSelectionMerge %gather DontFlatten\n"
8472                 "OpBranchConditional %gt0 %even %odd ;tells us if %count is even or odd\n"
8473
8474                 "%odd = OpLabel\n"
8475                 "OpBranch %gather\n"
8476
8477                 "%even = OpLabel\n"
8478                 "OpBranch %gather\n"
8479
8480                 "%gather = OpLabel\n"
8481                 "%delta_next = OpPhi %f32 %c_f32_n1 %even %c_f32_1 %odd\n"
8482                 "%val = OpFAdd %f32 %val1 %delta\n"
8483                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8484                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8485                 "OpBranchConditional %again %loop %exit\n"
8486
8487                 "%exit = OpLabel\n"
8488                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8489                 "OpReturnValue %result\n"
8490
8491                 "OpFunctionEnd\n");
8492
8493         map<string, string> continue_target;
8494
8495         // The Continue Target is the loop block itself.
8496         continue_target["continue_target"] = "%loop";
8497         fragments["testfun"] = multiBlock.specialize(continue_target);
8498         createTestsForAllStages("multi_block_continue_construct", defaultColors, defaultColors, fragments, testGroup.get());
8499
8500         // The Continue Target is at the end of the loop.
8501         continue_target["continue_target"] = "%gather";
8502         fragments["testfun"] = multiBlock.specialize(continue_target);
8503         createTestsForAllStages("multi_block_loop_construct", defaultColors, defaultColors, fragments, testGroup.get());
8504
8505         // A loop with continue statement.
8506         fragments["testfun"] =
8507                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8508                 "%param1 = OpFunctionParameter %v4f32\n"
8509
8510                 "%entry = OpLabel\n"
8511                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8512                 "OpBranch %loop\n"
8513
8514                 ";adds 4, 3, and 1 to %val0 (skips 2)\n"
8515                 "%loop = OpLabel\n"
8516                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8517                 "%val1 = OpPhi %f32 %val0 %entry %val %continue\n"
8518                 "OpLoopMerge %exit %continue None\n"
8519                 "OpBranch %if\n"
8520
8521                 "%if = OpLabel\n"
8522                 ";skip if %count==2\n"
8523                 "%eq2 = OpIEqual %bool %count %c_i32_2\n"
8524                 "OpSelectionMerge %continue DontFlatten\n"
8525                 "OpBranchConditional %eq2 %continue %body\n"
8526
8527                 "%body = OpLabel\n"
8528                 "%fcount = OpConvertSToF %f32 %count\n"
8529                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8530                 "OpBranch %continue\n"
8531
8532                 "%continue = OpLabel\n"
8533                 "%val = OpPhi %f32 %val2 %body %val1 %if\n"
8534                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8535                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8536                 "OpBranchConditional %again %loop %exit\n"
8537
8538                 "%exit = OpLabel\n"
8539                 "%same = OpFSub %f32 %val %c_f32_8\n"
8540                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8541                 "OpReturnValue %result\n"
8542                 "OpFunctionEnd\n";
8543         createTestsForAllStages("continue", defaultColors, defaultColors, fragments, testGroup.get());
8544
8545         // A loop with break.
8546         fragments["testfun"] =
8547                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8548                 "%param1 = OpFunctionParameter %v4f32\n"
8549
8550                 "%entry = OpLabel\n"
8551                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8552                 "%dot = OpDot %f32 %param1 %param1\n"
8553                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8554                 "%zero = OpConvertFToU %u32 %div\n"
8555                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8556                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8557                 "OpBranch %loop\n"
8558
8559                 ";adds 4 and 3 to %val0 (exits early)\n"
8560                 "%loop = OpLabel\n"
8561                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8562                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8563                 "OpLoopMerge %exit %continue None\n"
8564                 "OpBranch %if\n"
8565
8566                 "%if = OpLabel\n"
8567                 ";end loop if %count==%two\n"
8568                 "%above2 = OpSGreaterThan %bool %count %two\n"
8569                 "OpSelectionMerge %continue DontFlatten\n"
8570                 "OpBranchConditional %above2 %body %exit\n"
8571
8572                 "%body = OpLabel\n"
8573                 "%fcount = OpConvertSToF %f32 %count\n"
8574                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8575                 "OpBranch %continue\n"
8576
8577                 "%continue = OpLabel\n"
8578                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8579                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8580                 "OpBranchConditional %again %loop %exit\n"
8581
8582                 "%exit = OpLabel\n"
8583                 "%val_post = OpPhi %f32 %val2 %continue %val1 %if\n"
8584                 "%same = OpFSub %f32 %val_post %c_f32_7\n"
8585                 "%result = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8586                 "OpReturnValue %result\n"
8587                 "OpFunctionEnd\n";
8588         createTestsForAllStages("break", defaultColors, defaultColors, fragments, testGroup.get());
8589
8590         // A loop with return.
8591         fragments["testfun"] =
8592                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8593                 "%param1 = OpFunctionParameter %v4f32\n"
8594
8595                 "%entry = OpLabel\n"
8596                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8597                 "%dot = OpDot %f32 %param1 %param1\n"
8598                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8599                 "%zero = OpConvertFToU %u32 %div\n"
8600                 "%two = OpIAdd %i32 %zero %c_i32_2\n"
8601                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8602                 "OpBranch %loop\n"
8603
8604                 ";returns early without modifying %param1\n"
8605                 "%loop = OpLabel\n"
8606                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %continue\n"
8607                 "%val1 = OpPhi %f32 %val0 %entry %val2 %continue\n"
8608                 "OpLoopMerge %exit %continue None\n"
8609                 "OpBranch %if\n"
8610
8611                 "%if = OpLabel\n"
8612                 ";return if %count==%two\n"
8613                 "%above2 = OpSGreaterThan %bool %count %two\n"
8614                 "OpSelectionMerge %continue DontFlatten\n"
8615                 "OpBranchConditional %above2 %body %early_exit\n"
8616
8617                 "%early_exit = OpLabel\n"
8618                 "OpReturnValue %param1\n"
8619
8620                 "%body = OpLabel\n"
8621                 "%fcount = OpConvertSToF %f32 %count\n"
8622                 "%val2 = OpFAdd %f32 %val1 %fcount\n"
8623                 "OpBranch %continue\n"
8624
8625                 "%continue = OpLabel\n"
8626                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8627                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8628                 "OpBranchConditional %again %loop %exit\n"
8629
8630                 "%exit = OpLabel\n"
8631                 ";should never get here, so return an incorrect result\n"
8632                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val2 %c_i32_0\n"
8633                 "OpReturnValue %result\n"
8634                 "OpFunctionEnd\n";
8635         createTestsForAllStages("return", defaultColors, defaultColors, fragments, testGroup.get());
8636
8637         // Continue inside a switch block to break to enclosing loop's merge block.
8638         // Matches roughly the following GLSL code:
8639         // for (; keep_going; keep_going = false)
8640         // {
8641         //     switch (int(param1.x))
8642         //     {
8643         //         case 0: continue;
8644         //         case 1: continue;
8645         //         default: continue;
8646         //     }
8647         //     dead code: modify return value to invalid result.
8648         // }
8649         fragments["pre_main"] =
8650                 "%fp_bool = OpTypePointer Function %bool\n"
8651                 "%true = OpConstantTrue %bool\n"
8652                 "%false = OpConstantFalse %bool\n";
8653
8654         fragments["testfun"] =
8655                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8656                 "%param1 = OpFunctionParameter %v4f32\n"
8657
8658                 "%entry = OpLabel\n"
8659                 "%keep_going = OpVariable %fp_bool Function\n"
8660                 "%val_ptr = OpVariable %fp_f32 Function\n"
8661                 "%param1_x = OpCompositeExtract %f32 %param1 0\n"
8662                 "OpStore %keep_going %true\n"
8663                 "OpBranch %forloop_begin\n"
8664
8665                 "%forloop_begin = OpLabel\n"
8666                 "OpLoopMerge %forloop_merge %forloop_continue None\n"
8667                 "OpBranch %forloop\n"
8668
8669                 "%forloop = OpLabel\n"
8670                 "%for_condition = OpLoad %bool %keep_going\n"
8671                 "OpBranchConditional %for_condition %forloop_body %forloop_merge\n"
8672
8673                 "%forloop_body = OpLabel\n"
8674                 "OpStore %val_ptr %param1_x\n"
8675                 "%param1_x_int = OpConvertFToS %i32 %param1_x\n"
8676
8677                 "OpSelectionMerge %switch_merge None\n"
8678                 "OpSwitch %param1_x_int %default 0 %case_0 1 %case_1\n"
8679                 "%case_0 = OpLabel\n"
8680                 "OpBranch %forloop_continue\n"
8681                 "%case_1 = OpLabel\n"
8682                 "OpBranch %forloop_continue\n"
8683                 "%default = OpLabel\n"
8684                 "OpBranch %forloop_continue\n"
8685                 "%switch_merge = OpLabel\n"
8686                 ";should never get here, so change the return value to invalid result\n"
8687                 "OpStore %val_ptr %c_f32_1\n"
8688                 "OpBranch %forloop_continue\n"
8689
8690                 "%forloop_continue = OpLabel\n"
8691                 "OpStore %keep_going %false\n"
8692                 "OpBranch %forloop_begin\n"
8693                 "%forloop_merge = OpLabel\n"
8694
8695                 "%val = OpLoad %f32 %val_ptr\n"
8696                 "%result = OpVectorInsertDynamic %v4f32 %param1 %val %c_i32_0\n"
8697                 "OpReturnValue %result\n"
8698                 "OpFunctionEnd\n";
8699         createTestsForAllStages("switch_continue", defaultColors, defaultColors, fragments, testGroup.get());
8700
8701         return testGroup.release();
8702 }
8703
8704 // A collection of tests putting OpControlBarrier in places GLSL forbids but SPIR-V allows.
8705 tcu::TestCaseGroup* createBarrierTests(tcu::TestContext& testCtx)
8706 {
8707         de::MovePtr<tcu::TestCaseGroup> testGroup(new tcu::TestCaseGroup(testCtx, "barrier", "OpControlBarrier"));
8708         map<string, string> fragments;
8709
8710         // A barrier inside a function body.
8711         fragments["pre_main"] =
8712                 "%Workgroup = OpConstant %i32 2\n"
8713                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n";
8714         fragments["testfun"] =
8715                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8716                 "%param1 = OpFunctionParameter %v4f32\n"
8717                 "%label_testfun = OpLabel\n"
8718                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8719                 "OpReturnValue %param1\n"
8720                 "OpFunctionEnd\n";
8721         addTessCtrlTest(testGroup.get(), "in_function", fragments);
8722
8723         // Common setup code for the following tests.
8724         fragments["pre_main"] =
8725                 "%Workgroup = OpConstant %i32 2\n"
8726                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8727                 "%c_f32_5 = OpConstant %f32 5.\n";
8728         const string setupPercentZero =  // Begins %test_code function with code that sets %zero to 0u but cannot be optimized away.
8729                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8730                 "%param1 = OpFunctionParameter %v4f32\n"
8731                 "%entry = OpLabel\n"
8732                 ";param1 components are between 0 and 1, so dot product is 4 or less\n"
8733                 "%dot = OpDot %f32 %param1 %param1\n"
8734                 "%div = OpFDiv %f32 %dot %c_f32_5\n"
8735                 "%zero = OpConvertFToU %u32 %div\n";
8736
8737         // Barriers inside OpSwitch branches.
8738         fragments["testfun"] =
8739                 setupPercentZero +
8740                 "OpSelectionMerge %switch_exit None\n"
8741                 "OpSwitch %zero %switch_default 0 %case0 1 %case1 ;should always go to %case0\n"
8742
8743                 "%case1 = OpLabel\n"
8744                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8745                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8746                 "%wrong_branch_alert1 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8747                 "OpBranch %switch_exit\n"
8748
8749                 "%switch_default = OpLabel\n"
8750                 "%wrong_branch_alert2 = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8751                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8752                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8753                 "OpBranch %switch_exit\n"
8754
8755                 "%case0 = OpLabel\n"
8756                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8757                 "OpBranch %switch_exit\n"
8758
8759                 "%switch_exit = OpLabel\n"
8760                 "%ret = OpPhi %v4f32 %param1 %case0 %wrong_branch_alert1 %case1 %wrong_branch_alert2 %switch_default\n"
8761                 "OpReturnValue %ret\n"
8762                 "OpFunctionEnd\n";
8763         addTessCtrlTest(testGroup.get(), "in_switch", fragments);
8764
8765         // Barriers inside if-then-else.
8766         fragments["testfun"] =
8767                 setupPercentZero +
8768                 "%eq0 = OpIEqual %bool %zero %c_u32_0\n"
8769                 "OpSelectionMerge %exit DontFlatten\n"
8770                 "OpBranchConditional %eq0 %then %else\n"
8771
8772                 "%else = OpLabel\n"
8773                 ";This barrier should never be executed, but its presence makes test failure more likely when there's a bug.\n"
8774                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8775                 "%wrong_branch_alert = OpVectorInsertDynamic %v4f32 %param1 %c_f32_0_5 %c_i32_0\n"
8776                 "OpBranch %exit\n"
8777
8778                 "%then = OpLabel\n"
8779                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8780                 "OpBranch %exit\n"
8781                 "%exit = OpLabel\n"
8782                 "%ret = OpPhi %v4f32 %param1 %then %wrong_branch_alert %else\n"
8783                 "OpReturnValue %ret\n"
8784                 "OpFunctionEnd\n";
8785         addTessCtrlTest(testGroup.get(), "in_if", fragments);
8786
8787         // A barrier after control-flow reconvergence, tempting the compiler to attempt something like this:
8788         // http://lists.llvm.org/pipermail/llvm-dev/2009-October/026317.html.
8789         fragments["testfun"] =
8790                 setupPercentZero +
8791                 "%thread_id = OpLoad %i32 %BP_gl_InvocationID\n"
8792                 "%thread0 = OpIEqual %bool %thread_id %c_i32_0\n"
8793                 "OpSelectionMerge %exit DontFlatten\n"
8794                 "OpBranchConditional %thread0 %then %else\n"
8795
8796                 "%else = OpLabel\n"
8797                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8798                 "OpBranch %exit\n"
8799
8800                 "%then = OpLabel\n"
8801                 "%val1 = OpVectorExtractDynamic %f32 %param1 %zero\n"
8802                 "OpBranch %exit\n"
8803
8804                 "%exit = OpLabel\n"
8805                 "%val = OpPhi %f32 %val0 %else %val1 %then\n"
8806                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8807                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %val %zero\n"
8808                 "OpReturnValue %ret\n"
8809                 "OpFunctionEnd\n";
8810         addTessCtrlTest(testGroup.get(), "after_divergent_if", fragments);
8811
8812         // A barrier inside a loop.
8813         fragments["pre_main"] =
8814                 "%Workgroup = OpConstant %i32 2\n"
8815                 "%WorkgroupAcquireRelease = OpConstant %i32 0x108\n"
8816                 "%c_f32_10 = OpConstant %f32 10.\n";
8817         fragments["testfun"] =
8818                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8819                 "%param1 = OpFunctionParameter %v4f32\n"
8820                 "%entry = OpLabel\n"
8821                 "%val0 = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
8822                 "OpBranch %loop\n"
8823
8824                 ";adds 4, 3, 2, and 1 to %val0\n"
8825                 "%loop = OpLabel\n"
8826                 "%count = OpPhi %i32 %c_i32_4 %entry %count__ %loop\n"
8827                 "%val1 = OpPhi %f32 %val0 %entry %val %loop\n"
8828                 "OpControlBarrier %Workgroup %Workgroup %WorkgroupAcquireRelease\n"
8829                 "%fcount = OpConvertSToF %f32 %count\n"
8830                 "%val = OpFAdd %f32 %val1 %fcount\n"
8831                 "%count__ = OpISub %i32 %count %c_i32_1\n"
8832                 "%again = OpSGreaterThan %bool %count__ %c_i32_0\n"
8833                 "OpLoopMerge %exit %loop None\n"
8834                 "OpBranchConditional %again %loop %exit\n"
8835
8836                 "%exit = OpLabel\n"
8837                 "%same = OpFSub %f32 %val %c_f32_10\n"
8838                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %same %c_i32_0\n"
8839                 "OpReturnValue %ret\n"
8840                 "OpFunctionEnd\n";
8841         addTessCtrlTest(testGroup.get(), "in_loop", fragments);
8842
8843         return testGroup.release();
8844 }
8845
8846 // Test for the OpFRem instruction.
8847 tcu::TestCaseGroup* createFRemTests(tcu::TestContext& testCtx)
8848 {
8849         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "frem", "OpFRem"));
8850         map<string, string>                                     fragments;
8851         RGBA                                                            inputColors[4];
8852         RGBA                                                            outputColors[4];
8853
8854         fragments["pre_main"]                            =
8855                 "%c_f32_3 = OpConstant %f32 3.0\n"
8856                 "%c_f32_n3 = OpConstant %f32 -3.0\n"
8857                 "%c_f32_4 = OpConstant %f32 4.0\n"
8858                 "%c_f32_p75 = OpConstant %f32 0.75\n"
8859                 "%c_v4f32_p75_p75_p75_p75 = OpConstantComposite %v4f32 %c_f32_p75 %c_f32_p75 %c_f32_p75 %c_f32_p75 \n"
8860                 "%c_v4f32_4_4_4_4 = OpConstantComposite %v4f32 %c_f32_4 %c_f32_4 %c_f32_4 %c_f32_4\n"
8861                 "%c_v4f32_3_n3_3_n3 = OpConstantComposite %v4f32 %c_f32_3 %c_f32_n3 %c_f32_3 %c_f32_n3\n";
8862
8863         // The test does the following.
8864         // vec4 result = (param1 * 8.0) - 4.0;
8865         // return (frem(result.x,3) + 0.75, frem(result.y, -3) + 0.75, 0, 1)
8866         fragments["testfun"]                             =
8867                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8868                 "%param1 = OpFunctionParameter %v4f32\n"
8869                 "%label_testfun = OpLabel\n"
8870                 "%v_times_8 = OpVectorTimesScalar %v4f32 %param1 %c_f32_8\n"
8871                 "%minus_4 = OpFSub %v4f32 %v_times_8 %c_v4f32_4_4_4_4\n"
8872                 "%frem = OpFRem %v4f32 %minus_4 %c_v4f32_3_n3_3_n3\n"
8873                 "%added = OpFAdd %v4f32 %frem %c_v4f32_p75_p75_p75_p75\n"
8874                 "%xyz_1 = OpVectorInsertDynamic %v4f32 %added %c_f32_1 %c_i32_3\n"
8875                 "%xy_0_1 = OpVectorInsertDynamic %v4f32 %xyz_1 %c_f32_0 %c_i32_2\n"
8876                 "OpReturnValue %xy_0_1\n"
8877                 "OpFunctionEnd\n";
8878
8879
8880         inputColors[0]          = RGBA(16,      16,             0, 255);
8881         inputColors[1]          = RGBA(232, 232,        0, 255);
8882         inputColors[2]          = RGBA(232, 16,         0, 255);
8883         inputColors[3]          = RGBA(16,      232,    0, 255);
8884
8885         outputColors[0]         = RGBA(64,      64,             0, 255);
8886         outputColors[1]         = RGBA(255, 255,        0, 255);
8887         outputColors[2]         = RGBA(255, 64,         0, 255);
8888         outputColors[3]         = RGBA(64,      255,    0, 255);
8889
8890         createTestsForAllStages("frem", inputColors, outputColors, fragments, testGroup.get());
8891         return testGroup.release();
8892 }
8893
8894 // Test for the OpSRem instruction.
8895 tcu::TestCaseGroup* createOpSRemGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8896 {
8897         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "srem", "OpSRem"));
8898         map<string, string>                                     fragments;
8899
8900         fragments["pre_main"]                            =
8901                 "%c_f32_255 = OpConstant %f32 255.0\n"
8902                 "%c_i32_128 = OpConstant %i32 128\n"
8903                 "%c_i32_255 = OpConstant %i32 255\n"
8904                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8905                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8906                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8907
8908         // The test does the following.
8909         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8910         // ivec4 result = ivec4(srem(ints.x, ints.y), srem(ints.y, ints.z), srem(ints.z, ints.x), 255);
8911         // return float(result + 128) / 255.0;
8912         fragments["testfun"]                             =
8913                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8914                 "%param1 = OpFunctionParameter %v4f32\n"
8915                 "%label_testfun = OpLabel\n"
8916                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
8917                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
8918                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
8919                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
8920                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
8921                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
8922                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
8923                 "%x_out = OpSRem %i32 %x_in %y_in\n"
8924                 "%y_out = OpSRem %i32 %y_in %z_in\n"
8925                 "%z_out = OpSRem %i32 %z_in %x_in\n"
8926                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
8927                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
8928                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
8929                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
8930                 "OpReturnValue %float_out\n"
8931                 "OpFunctionEnd\n";
8932
8933         const struct CaseParams
8934         {
8935                 const char*             name;
8936                 const char*             failMessageTemplate;    // customized status message
8937                 qpTestResult    failResult;                             // override status on failure
8938                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
8939                 int                             results[4][3];                  // four (x, y, z) vectors of results
8940         } cases[] =
8941         {
8942                 {
8943                         "positive",
8944                         "${reason}",
8945                         QP_TEST_RESULT_FAIL,
8946                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                 // operands
8947                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                 // results
8948                 },
8949                 {
8950                         "all",
8951                         "Inconsistent results, but within specification: ${reason}",
8952                         negFailResult,                                                                                                                  // negative operands, not required by the spec
8953                         { { 5, 12, -17 }, { -5, -5, 7 }, { 75, 8, -81 }, { 25, -60, 100 } },    // operands
8954                         { { 5, 12,  -2 }, {  0, -5, 2 }, {  3, 8,  -6 }, { 25, -60,   0 } },    // results
8955                 },
8956         };
8957         // If either operand is negative the result is undefined. Some implementations may still return correct values.
8958
8959         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
8960         {
8961                 const CaseParams&       params                  = cases[caseNdx];
8962                 RGBA                            inputColors[4];
8963                 RGBA                            outputColors[4];
8964
8965                 for (int i = 0; i < 4; ++i)
8966                 {
8967                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
8968                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
8969                 }
8970
8971                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
8972         }
8973
8974         return testGroup.release();
8975 }
8976
8977 // Test for the OpSMod instruction.
8978 tcu::TestCaseGroup* createOpSModGraphicsTests(tcu::TestContext& testCtx, qpTestResult negFailResult)
8979 {
8980         de::MovePtr<tcu::TestCaseGroup>         testGroup(new tcu::TestCaseGroup(testCtx, "smod", "OpSMod"));
8981         map<string, string>                                     fragments;
8982
8983         fragments["pre_main"]                            =
8984                 "%c_f32_255 = OpConstant %f32 255.0\n"
8985                 "%c_i32_128 = OpConstant %i32 128\n"
8986                 "%c_i32_255 = OpConstant %i32 255\n"
8987                 "%c_v4f32_255 = OpConstantComposite %v4f32 %c_f32_255 %c_f32_255 %c_f32_255 %c_f32_255 \n"
8988                 "%c_v4f32_0_5 = OpConstantComposite %v4f32 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 %c_f32_0_5 \n"
8989                 "%c_v4i32_128 = OpConstantComposite %v4i32 %c_i32_128 %c_i32_128 %c_i32_128 %c_i32_128 \n";
8990
8991         // The test does the following.
8992         // ivec4 ints = int(param1 * 255.0 + 0.5) - 128;
8993         // ivec4 result = ivec4(smod(ints.x, ints.y), smod(ints.y, ints.z), smod(ints.z, ints.x), 255);
8994         // return float(result + 128) / 255.0;
8995         fragments["testfun"]                             =
8996                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
8997                 "%param1 = OpFunctionParameter %v4f32\n"
8998                 "%label_testfun = OpLabel\n"
8999                 "%div255 = OpFMul %v4f32 %param1 %c_v4f32_255\n"
9000                 "%add0_5 = OpFAdd %v4f32 %div255 %c_v4f32_0_5\n"
9001                 "%uints_in = OpConvertFToS %v4i32 %add0_5\n"
9002                 "%ints_in = OpISub %v4i32 %uints_in %c_v4i32_128\n"
9003                 "%x_in = OpCompositeExtract %i32 %ints_in 0\n"
9004                 "%y_in = OpCompositeExtract %i32 %ints_in 1\n"
9005                 "%z_in = OpCompositeExtract %i32 %ints_in 2\n"
9006                 "%x_out = OpSMod %i32 %x_in %y_in\n"
9007                 "%y_out = OpSMod %i32 %y_in %z_in\n"
9008                 "%z_out = OpSMod %i32 %z_in %x_in\n"
9009                 "%ints_out = OpCompositeConstruct %v4i32 %x_out %y_out %z_out %c_i32_255\n"
9010                 "%ints_offset = OpIAdd %v4i32 %ints_out %c_v4i32_128\n"
9011                 "%f_ints_offset = OpConvertSToF %v4f32 %ints_offset\n"
9012                 "%float_out = OpFDiv %v4f32 %f_ints_offset %c_v4f32_255\n"
9013                 "OpReturnValue %float_out\n"
9014                 "OpFunctionEnd\n";
9015
9016         const struct CaseParams
9017         {
9018                 const char*             name;
9019                 const char*             failMessageTemplate;    // customized status message
9020                 qpTestResult    failResult;                             // override status on failure
9021                 int                             operands[4][3];                 // four (x, y, z) vectors of operands
9022                 int                             results[4][3];                  // four (x, y, z) vectors of results
9023         } cases[] =
9024         {
9025                 {
9026                         "positive",
9027                         "${reason}",
9028                         QP_TEST_RESULT_FAIL,
9029                         { { 5, 12, 17 }, { 5, 5, 7 }, { 75, 8, 81 }, { 25, 60, 100 } },                         // operands
9030                         { { 5, 12,  2 }, { 0, 5, 2 }, {  3, 8,  6 }, { 25, 60,   0 } },                         // results
9031                 },
9032                 {
9033                         "all",
9034                         "Inconsistent results, but within specification: ${reason}",
9035                         negFailResult,                                                                                                                          // negative operands, not required by the spec
9036                         { { 5, 12, -17 }, { -5, -5,  7 }, { 75,   8, -81 }, {  25, -60, 100 } },        // operands
9037                         { { 5, -5,   3 }, {  0,  2, -3 }, {  3, -73,  69 }, { -35,  40,   0 } },        // results
9038                 },
9039         };
9040         // If either operand is negative the result is undefined. Some implementations may still return correct values.
9041
9042         for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); ++caseNdx)
9043         {
9044                 const CaseParams&       params                  = cases[caseNdx];
9045                 RGBA                            inputColors[4];
9046                 RGBA                            outputColors[4];
9047
9048                 for (int i = 0; i < 4; ++i)
9049                 {
9050                         inputColors [i] = RGBA(params.operands[i][0] + 128, params.operands[i][1] + 128, params.operands[i][2] + 128, 255);
9051                         outputColors[i] = RGBA(params.results [i][0] + 128, params.results [i][1] + 128, params.results [i][2] + 128, 255);
9052                 }
9053
9054                 createTestsForAllStages(params.name, inputColors, outputColors, fragments, testGroup.get(), params.failResult, params.failMessageTemplate);
9055         }
9056         return testGroup.release();
9057 }
9058
9059 enum ConversionDataType
9060 {
9061         DATA_TYPE_SIGNED_8,
9062         DATA_TYPE_SIGNED_16,
9063         DATA_TYPE_SIGNED_32,
9064         DATA_TYPE_SIGNED_64,
9065         DATA_TYPE_UNSIGNED_8,
9066         DATA_TYPE_UNSIGNED_16,
9067         DATA_TYPE_UNSIGNED_32,
9068         DATA_TYPE_UNSIGNED_64,
9069         DATA_TYPE_FLOAT_16,
9070         DATA_TYPE_FLOAT_32,
9071         DATA_TYPE_FLOAT_64,
9072         DATA_TYPE_VEC2_SIGNED_16,
9073         DATA_TYPE_VEC2_SIGNED_32
9074 };
9075
9076 const string getBitWidthStr (ConversionDataType type)
9077 {
9078         switch (type)
9079         {
9080                 case DATA_TYPE_SIGNED_8:
9081                 case DATA_TYPE_UNSIGNED_8:
9082                         return "8";
9083
9084                 case DATA_TYPE_SIGNED_16:
9085                 case DATA_TYPE_UNSIGNED_16:
9086                 case DATA_TYPE_FLOAT_16:
9087                         return "16";
9088
9089                 case DATA_TYPE_SIGNED_32:
9090                 case DATA_TYPE_UNSIGNED_32:
9091                 case DATA_TYPE_FLOAT_32:
9092                 case DATA_TYPE_VEC2_SIGNED_16:
9093                         return "32";
9094
9095                 case DATA_TYPE_SIGNED_64:
9096                 case DATA_TYPE_UNSIGNED_64:
9097                 case DATA_TYPE_FLOAT_64:
9098                 case DATA_TYPE_VEC2_SIGNED_32:
9099                         return "64";
9100
9101                 default:
9102                         DE_ASSERT(false);
9103         }
9104         return "";
9105 }
9106
9107 const string getByteWidthStr (ConversionDataType type)
9108 {
9109         switch (type)
9110         {
9111                 case DATA_TYPE_SIGNED_8:
9112                 case DATA_TYPE_UNSIGNED_8:
9113                         return "1";
9114
9115                 case DATA_TYPE_SIGNED_16:
9116                 case DATA_TYPE_UNSIGNED_16:
9117                 case DATA_TYPE_FLOAT_16:
9118                         return "2";
9119
9120                 case DATA_TYPE_SIGNED_32:
9121                 case DATA_TYPE_UNSIGNED_32:
9122                 case DATA_TYPE_FLOAT_32:
9123                 case DATA_TYPE_VEC2_SIGNED_16:
9124                         return "4";
9125
9126                 case DATA_TYPE_SIGNED_64:
9127                 case DATA_TYPE_UNSIGNED_64:
9128                 case DATA_TYPE_FLOAT_64:
9129                 case DATA_TYPE_VEC2_SIGNED_32:
9130                         return "8";
9131
9132                 default:
9133                         DE_ASSERT(false);
9134         }
9135         return "";
9136 }
9137
9138 bool isSigned (ConversionDataType type)
9139 {
9140         switch (type)
9141         {
9142                 case DATA_TYPE_SIGNED_8:
9143                 case DATA_TYPE_SIGNED_16:
9144                 case DATA_TYPE_SIGNED_32:
9145                 case DATA_TYPE_SIGNED_64:
9146                 case DATA_TYPE_FLOAT_16:
9147                 case DATA_TYPE_FLOAT_32:
9148                 case DATA_TYPE_FLOAT_64:
9149                 case DATA_TYPE_VEC2_SIGNED_16:
9150                 case DATA_TYPE_VEC2_SIGNED_32:
9151                         return true;
9152
9153                 case DATA_TYPE_UNSIGNED_8:
9154                 case DATA_TYPE_UNSIGNED_16:
9155                 case DATA_TYPE_UNSIGNED_32:
9156                 case DATA_TYPE_UNSIGNED_64:
9157                         return false;
9158
9159                 default:
9160                         DE_ASSERT(false);
9161         }
9162         return false;
9163 }
9164
9165 bool isInt (ConversionDataType type)
9166 {
9167         switch (type)
9168         {
9169                 case DATA_TYPE_SIGNED_8:
9170                 case DATA_TYPE_SIGNED_16:
9171                 case DATA_TYPE_SIGNED_32:
9172                 case DATA_TYPE_SIGNED_64:
9173                 case DATA_TYPE_UNSIGNED_8:
9174                 case DATA_TYPE_UNSIGNED_16:
9175                 case DATA_TYPE_UNSIGNED_32:
9176                 case DATA_TYPE_UNSIGNED_64:
9177                         return true;
9178
9179                 case DATA_TYPE_FLOAT_16:
9180                 case DATA_TYPE_FLOAT_32:
9181                 case DATA_TYPE_FLOAT_64:
9182                 case DATA_TYPE_VEC2_SIGNED_16:
9183                 case DATA_TYPE_VEC2_SIGNED_32:
9184                         return false;
9185
9186                 default:
9187                         DE_ASSERT(false);
9188         }
9189         return false;
9190 }
9191
9192 bool isFloat (ConversionDataType type)
9193 {
9194         switch (type)
9195         {
9196                 case DATA_TYPE_SIGNED_8:
9197                 case DATA_TYPE_SIGNED_16:
9198                 case DATA_TYPE_SIGNED_32:
9199                 case DATA_TYPE_SIGNED_64:
9200                 case DATA_TYPE_UNSIGNED_8:
9201                 case DATA_TYPE_UNSIGNED_16:
9202                 case DATA_TYPE_UNSIGNED_32:
9203                 case DATA_TYPE_UNSIGNED_64:
9204                 case DATA_TYPE_VEC2_SIGNED_16:
9205                 case DATA_TYPE_VEC2_SIGNED_32:
9206                         return false;
9207
9208                 case DATA_TYPE_FLOAT_16:
9209                 case DATA_TYPE_FLOAT_32:
9210                 case DATA_TYPE_FLOAT_64:
9211                         return true;
9212
9213                 default:
9214                         DE_ASSERT(false);
9215         }
9216         return false;
9217 }
9218
9219 const string getTypeName (ConversionDataType type)
9220 {
9221         string prefix = isSigned(type) ? "" : "u";
9222
9223         if              (isInt(type))                                           return prefix + "int"   + getBitWidthStr(type);
9224         else if (isFloat(type))                                         return prefix + "float" + getBitWidthStr(type);
9225         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9226         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "i32vec2";
9227         else                                                                            DE_ASSERT(false);
9228
9229         return "";
9230 }
9231
9232 const string getTestName (ConversionDataType from, ConversionDataType to, const char* suffix)
9233 {
9234         const string fullSuffix(suffix == DE_NULL ? "" : string("_") + string(suffix));
9235
9236         return getTypeName(from) + "_to_" + getTypeName(to) + fullSuffix;
9237 }
9238
9239 const string getAsmTypeName (ConversionDataType type)
9240 {
9241         string prefix;
9242
9243         if              (isInt(type))                                           prefix = isSigned(type) ? "i" : "u";
9244         else if (isFloat(type))                                         prefix = "f";
9245         else if (type == DATA_TYPE_VEC2_SIGNED_16)      return "i16vec2";
9246         else if (type == DATA_TYPE_VEC2_SIGNED_32)      return "v2i32";
9247         else                                                                            DE_ASSERT(false);
9248
9249         return prefix + getBitWidthStr(type);
9250 }
9251
9252 template<typename T>
9253 BufferSp getSpecializedBuffer (deInt64 number)
9254 {
9255         return BufferSp(new Buffer<T>(vector<T>(1, (T)number)));
9256 }
9257
9258 BufferSp getBuffer (ConversionDataType type, deInt64 number)
9259 {
9260         switch (type)
9261         {
9262                 case DATA_TYPE_SIGNED_8:                return getSpecializedBuffer<deInt8>(number);
9263                 case DATA_TYPE_SIGNED_16:               return getSpecializedBuffer<deInt16>(number);
9264                 case DATA_TYPE_SIGNED_32:               return getSpecializedBuffer<deInt32>(number);
9265                 case DATA_TYPE_SIGNED_64:               return getSpecializedBuffer<deInt64>(number);
9266                 case DATA_TYPE_UNSIGNED_8:              return getSpecializedBuffer<deUint8>(number);
9267                 case DATA_TYPE_UNSIGNED_16:             return getSpecializedBuffer<deUint16>(number);
9268                 case DATA_TYPE_UNSIGNED_32:             return getSpecializedBuffer<deUint32>(number);
9269                 case DATA_TYPE_UNSIGNED_64:             return getSpecializedBuffer<deUint64>(number);
9270                 case DATA_TYPE_FLOAT_16:                return getSpecializedBuffer<deUint16>(number);
9271                 case DATA_TYPE_FLOAT_32:                return getSpecializedBuffer<deUint32>(number);
9272                 case DATA_TYPE_FLOAT_64:                return getSpecializedBuffer<deUint64>(number);
9273                 case DATA_TYPE_VEC2_SIGNED_16:  return getSpecializedBuffer<deUint32>(number);
9274                 case DATA_TYPE_VEC2_SIGNED_32:  return getSpecializedBuffer<deUint64>(number);
9275
9276                 default:                                                TCU_THROW(InternalError, "Unimplemented type passed");
9277         }
9278 }
9279
9280 bool usesInt8 (ConversionDataType from, ConversionDataType to)
9281 {
9282         return (from == DATA_TYPE_SIGNED_8 || to == DATA_TYPE_SIGNED_8 ||
9283                         from == DATA_TYPE_UNSIGNED_8 || to == DATA_TYPE_UNSIGNED_8);
9284 }
9285
9286 bool usesInt16 (ConversionDataType from, ConversionDataType to)
9287 {
9288         return (from == DATA_TYPE_SIGNED_16 || to == DATA_TYPE_SIGNED_16 ||
9289                         from == DATA_TYPE_UNSIGNED_16 || to == DATA_TYPE_UNSIGNED_16 ||
9290                         from == DATA_TYPE_VEC2_SIGNED_16 || to == DATA_TYPE_VEC2_SIGNED_16);
9291 }
9292
9293 bool usesInt32 (ConversionDataType from, ConversionDataType to)
9294 {
9295         return (from == DATA_TYPE_SIGNED_32 || to == DATA_TYPE_SIGNED_32 ||
9296                         from == DATA_TYPE_UNSIGNED_32 || to == DATA_TYPE_UNSIGNED_32 ||
9297                         from == DATA_TYPE_VEC2_SIGNED_32|| to == DATA_TYPE_VEC2_SIGNED_32);
9298 }
9299
9300 bool usesInt64 (ConversionDataType from, ConversionDataType to)
9301 {
9302         return (from == DATA_TYPE_SIGNED_64 || to == DATA_TYPE_SIGNED_64 ||
9303                         from == DATA_TYPE_UNSIGNED_64 || to == DATA_TYPE_UNSIGNED_64);
9304 }
9305
9306 bool usesFloat16 (ConversionDataType from, ConversionDataType to)
9307 {
9308         return (from == DATA_TYPE_FLOAT_16 || to == DATA_TYPE_FLOAT_16);
9309 }
9310
9311 bool usesFloat32 (ConversionDataType from, ConversionDataType to)
9312 {
9313         return (from == DATA_TYPE_FLOAT_32 || to == DATA_TYPE_FLOAT_32);
9314 }
9315
9316 bool usesFloat64 (ConversionDataType from, ConversionDataType to)
9317 {
9318         return (from == DATA_TYPE_FLOAT_64 || to == DATA_TYPE_FLOAT_64);
9319 }
9320
9321 void getVulkanFeaturesAndExtensions (ConversionDataType from, ConversionDataType to, VulkanFeatures& vulkanFeatures, vector<string>& extensions)
9322 {
9323         if (usesInt16(from, to) && !usesInt32(from, to))
9324                 vulkanFeatures.coreFeatures.shaderInt16 = DE_TRUE;
9325
9326         if (usesInt64(from, to))
9327                 vulkanFeatures.coreFeatures.shaderInt64 = DE_TRUE;
9328
9329         if (usesFloat64(from, to))
9330                 vulkanFeatures.coreFeatures.shaderFloat64 = DE_TRUE;
9331
9332         if (usesInt16(from, to) || usesFloat16(from, to))
9333         {
9334                 extensions.push_back("VK_KHR_16bit_storage");
9335                 vulkanFeatures.ext16BitStorage |= EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
9336         }
9337
9338         if (usesFloat16(from, to) || usesInt8(from, to))
9339         {
9340                 extensions.push_back("VK_KHR_shader_float16_int8");
9341
9342                 if (usesFloat16(from, to))
9343                 {
9344                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
9345                 }
9346
9347                 if (usesInt8(from, to))
9348                 {
9349                         vulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
9350
9351                         extensions.push_back("VK_KHR_8bit_storage");
9352                         vulkanFeatures.ext8BitStorage |= EXT8BITSTORAGEFEATURES_STORAGE_BUFFER;
9353                 }
9354         }
9355 }
9356
9357 struct ConvertCase
9358 {
9359         ConvertCase (const string& instruction, ConversionDataType from, ConversionDataType to, deInt64 number, bool separateOutput = false, deInt64 outputNumber = 0, const char* suffix = DE_NULL)
9360         : m_fromType            (from)
9361         , m_toType                      (to)
9362         , m_name                        (getTestName(from, to, suffix))
9363         , m_inputBuffer         (getBuffer(from, number))
9364         {
9365                 string caps;
9366                 string decl;
9367                 string exts;
9368
9369                 m_asmTypes["inputType"]         = getAsmTypeName(from);
9370                 m_asmTypes["outputType"]        = getAsmTypeName(to);
9371
9372                 if (separateOutput)
9373                         m_outputBuffer = getBuffer(to, outputNumber);
9374                 else
9375                         m_outputBuffer = getBuffer(to, number);
9376
9377                 if (usesInt8(from, to))
9378                 {
9379                         bool requiresInt8Capability = true;
9380                         if (instruction == "OpUConvert" || instruction == "OpSConvert")
9381                         {
9382                                 // Conversions between 8 and 32 bit are provided by SPV_KHR_8bit_storage. The rest requires explicit Int8
9383                                 if (usesInt32(from, to))
9384                                         requiresInt8Capability = false;
9385                         }
9386
9387                         caps += "OpCapability StorageBuffer8BitAccess\n";
9388                         if (requiresInt8Capability)
9389                                 caps += "OpCapability Int8\n";
9390
9391                         decl += "%i8         = OpTypeInt 8 1\n"
9392                                         "%u8         = OpTypeInt 8 0\n";
9393                         exts += "OpExtension \"SPV_KHR_8bit_storage\"\n";
9394                 }
9395
9396                 if (usesInt16(from, to))
9397                 {
9398                         bool requiresInt16Capability = true;
9399
9400                         if (instruction == "OpUConvert" || instruction == "OpSConvert" || instruction == "OpFConvert")
9401                         {
9402                                 // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9403                                 if (usesInt32(from, to) || usesFloat32(from, to))
9404                                         requiresInt16Capability = false;
9405                         }
9406
9407                         decl += "%i16        = OpTypeInt 16 1\n"
9408                                         "%u16        = OpTypeInt 16 0\n"
9409                                         "%i16vec2    = OpTypeVector %i16 2\n";
9410
9411                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Int16
9412                         if (requiresInt16Capability)
9413                                 caps += "OpCapability Int16\n";
9414                 }
9415
9416                 if (usesFloat16(from, to))
9417                 {
9418                         decl += "%f16        = OpTypeFloat 16\n";
9419
9420                         // Conversions between 16 and 32 bit are provided by SPV_KHR_16bit_storage. The rest requires explicit Float16
9421                         if (!(usesInt32(from, to) || usesFloat32(from, to)))
9422                                 caps += "OpCapability Float16\n";
9423                 }
9424
9425                 if (usesInt16(from, to) || usesFloat16(from, to))
9426                 {
9427                         caps += "OpCapability StorageUniformBufferBlock16\n";
9428                         exts += "OpExtension \"SPV_KHR_16bit_storage\"\n";
9429                 }
9430
9431                 if (usesInt64(from, to))
9432                 {
9433                         caps += "OpCapability Int64\n";
9434                         decl += "%i64        = OpTypeInt 64 1\n"
9435                                         "%u64        = OpTypeInt 64 0\n";
9436                 }
9437
9438                 if (usesFloat64(from, to))
9439                 {
9440                         caps += "OpCapability Float64\n";
9441                         decl += "%f64        = OpTypeFloat 64\n";
9442                 }
9443
9444                 m_asmTypes["datatype_capabilities"]             = caps;
9445                 m_asmTypes["datatype_additional_decl"]  = decl;
9446                 m_asmTypes["datatype_extensions"]               = exts;
9447         }
9448
9449         ConversionDataType              m_fromType;
9450         ConversionDataType              m_toType;
9451         string                                  m_name;
9452         map<string, string>             m_asmTypes;
9453         BufferSp                                m_inputBuffer;
9454         BufferSp                                m_outputBuffer;
9455 };
9456
9457 const string getConvertCaseShaderStr (const string& instruction, const ConvertCase& convertCase)
9458 {
9459         map<string, string> params = convertCase.m_asmTypes;
9460
9461         params["instruction"]   = instruction;
9462         params["inDecorator"]   = getByteWidthStr(convertCase.m_fromType);
9463         params["outDecorator"]  = getByteWidthStr(convertCase.m_toType);
9464
9465         const StringTemplate shader (
9466                 "OpCapability Shader\n"
9467                 "${datatype_capabilities}"
9468                 "${datatype_extensions:opt}"
9469                 "OpMemoryModel Logical GLSL450\n"
9470                 "OpEntryPoint GLCompute %main \"main\"\n"
9471                 "OpExecutionMode %main LocalSize 1 1 1\n"
9472                 "OpSource GLSL 430\n"
9473                 "OpName %main           \"main\"\n"
9474                 // Decorators
9475                 "OpDecorate %indata DescriptorSet 0\n"
9476                 "OpDecorate %indata Binding 0\n"
9477                 "OpDecorate %outdata DescriptorSet 0\n"
9478                 "OpDecorate %outdata Binding 1\n"
9479                 "OpDecorate %in_buf BufferBlock\n"
9480                 "OpDecorate %out_buf BufferBlock\n"
9481                 "OpMemberDecorate %in_buf 0 Offset 0\n"
9482                 "OpMemberDecorate %out_buf 0 Offset 0\n"
9483                 // Base types
9484                 "%void       = OpTypeVoid\n"
9485                 "%voidf      = OpTypeFunction %void\n"
9486                 "%u32        = OpTypeInt 32 0\n"
9487                 "%i32        = OpTypeInt 32 1\n"
9488                 "%f32        = OpTypeFloat 32\n"
9489                 "%v2i32      = OpTypeVector %i32 2\n"
9490                 "${datatype_additional_decl}"
9491                 "%uvec3      = OpTypeVector %u32 3\n"
9492                 // Derived types
9493                 "%in_ptr     = OpTypePointer Uniform %${inputType}\n"
9494                 "%out_ptr    = OpTypePointer Uniform %${outputType}\n"
9495                 "%in_buf     = OpTypeStruct %${inputType}\n"
9496                 "%out_buf    = OpTypeStruct %${outputType}\n"
9497                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
9498                 "%out_bufptr = OpTypePointer Uniform %out_buf\n"
9499                 "%indata     = OpVariable %in_bufptr Uniform\n"
9500                 "%outdata    = OpVariable %out_bufptr Uniform\n"
9501                 // Constants
9502                 "%zero       = OpConstant %i32 0\n"
9503                 // Main function
9504                 "%main       = OpFunction %void None %voidf\n"
9505                 "%label      = OpLabel\n"
9506                 "%inloc      = OpAccessChain %in_ptr %indata %zero\n"
9507                 "%outloc     = OpAccessChain %out_ptr %outdata %zero\n"
9508                 "%inval      = OpLoad %${inputType} %inloc\n"
9509                 "%conv       = ${instruction} %${outputType} %inval\n"
9510                 "              OpStore %outloc %conv\n"
9511                 "              OpReturn\n"
9512                 "              OpFunctionEnd\n"
9513         );
9514
9515         return shader.specialize(params);
9516 }
9517
9518 void createConvertCases (vector<ConvertCase>& testCases, const string& instruction)
9519 {
9520         if (instruction == "OpUConvert")
9521         {
9522                 // Convert unsigned int to unsigned int
9523                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_16,          42));
9524                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_32,          73));
9525                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_UNSIGNED_64,          121));
9526
9527                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_8,           33));
9528                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_32,          60653));
9529                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_UNSIGNED_64,          17991));
9530
9531                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_64,          904256275));
9532                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_16,          6275));
9533                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_UNSIGNED_8,           17));
9534
9535                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_32,          701256243));
9536                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_16,          4741));
9537                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_UNSIGNED_8,           65));
9538         }
9539         else if (instruction == "OpSConvert")
9540         {
9541                 // Sign extension int->int
9542                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_16,            -30));
9543                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_32,            55));
9544                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_SIGNED_64,            -3));
9545                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_32,            14669));
9546                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_64,            -3341));
9547                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_64,            973610259));
9548
9549                 // Truncate for int->int
9550                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_SIGNED_8,                     81));
9551                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_8,                     -93));
9552                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_8,                     3182748172687672ll,                                     true,   56));
9553                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_SIGNED_16,            12382));
9554                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_32,            -972812359));
9555                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_SIGNED_16,            -1067742499291926803ll,                         true,   -4371));
9556
9557                 // Sign extension for int->uint
9558                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_16,          56));
9559                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_32,          -47,                                                            true,   4294967249u));
9560                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_UNSIGNED_64,          -5,                                                                     true,   18446744073709551611ull));
9561                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_32,          14669));
9562                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_64,          -3341,                                                          true,   18446744073709548275ull));
9563                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_64,          973610259));
9564
9565                 // Truncate for int->uint
9566                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_UNSIGNED_8,           -25711,                                                         true,   145));
9567                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_8,           103));
9568                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_8,           -1067742499291926803ll,                         true,   61165));
9569                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_UNSIGNED_16,          12382));
9570                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_32,          -972812359,                                                     true,   3322154937u));
9571                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_UNSIGNED_16,          -1067742499291926803ll,                         true,   61165));
9572
9573                 // Sign extension for uint->int
9574                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_16,            71));
9575                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_32,            201,                                                            true,   -55));
9576                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_SIGNED_64,            188,                                                            true,   -68));
9577                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_32,            14669));
9578                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_64,            62195,                                                          true,   -3341));
9579                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_64,            973610259));
9580
9581                 // Truncate for uint->int
9582                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_SIGNED_8,                     67));
9583                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_8,                     133,                                                            true,   -123));
9584                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_8,                     836927654193256494ull,                          true,   46));
9585                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_SIGNED_16,            12382));
9586                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_32,            18446744072736739257ull,                        true,   -972812359));
9587                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_SIGNED_16,            17379001574417624813ull,                        true,   -4371));
9588
9589                 // Convert i16vec2 to i32vec2 and vice versa
9590                 // Unsigned values are used here to represent negative signed values and to allow defined shifting behaviour.
9591                 // The actual signed value -32123 is used here as uint16 value 33413 and uint32 value 4294935173
9592                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_16,       DATA_TYPE_VEC2_SIGNED_32,       (33413u << 16)                  | 27593,        true,   (4294935173ull << 32)   | 27593));
9593                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_VEC2_SIGNED_32,       DATA_TYPE_VEC2_SIGNED_16,       (4294935173ull << 32)   | 27593,        true,   (33413u << 16)                  | 27593));
9594         }
9595         else if (instruction == "OpFConvert")
9596         {
9597                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9598                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_64,                     0x449a4000,                                                     true,   0x4093480000000000));
9599                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_32,                     0x4093480000000000,                                     true,   0x449a4000));
9600
9601                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_FLOAT_16,                     0x449a4000,                                                     true,   0x64D2));
9602                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_32,                     0x64D2,                                                         true,   0x449a4000));
9603
9604                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_FLOAT_64,                     0x64D2,                                                         true,   0x4093480000000000));
9605                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_FLOAT_16,                     0x4093480000000000,                                     true,   0x64D2));
9606         }
9607         else if (instruction == "OpConvertFToU")
9608         {
9609                 // Normal numbers from uint8 range
9610                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5020,                                                         true,   33,                                                                     "33"));
9611                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x42280000,                                                     true,   42,                                                                     "42"));
9612                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x4067800000000000ull,                          true,   188,                                                            "188"));
9613
9614                 // Maximum uint8 value
9615                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x5BF8,                                                         true,   255,                                                            "max"));
9616                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x437F0000,                                                     true,   255,                                                            "max"));
9617                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x406FE00000000000ull,                          true,   255,                                                            "max"));
9618
9619                 // +0
9620                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x0000,                                                         true,   0,                                                                      "p0"));
9621                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x00000000,                                                     true,   0,                                                                      "p0"));
9622                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9623
9624                 // -0
9625                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_8,           0x8000,                                                         true,   0,                                                                      "m0"));
9626                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_8,           0x80000000,                                                     true,   0,                                                                      "m0"));
9627                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_8,           0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9628
9629                 // All hexadecimal values below represent 1234.0 as 16/32/64-bit IEEE 754 float
9630                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x64D2,                                                         true,   1234,                                                           "1234"));
9631                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x64D2,                                                         true,   1234,                                                           "1234"));
9632                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x64D2,                                                         true,   1234,                                                           "1234"));
9633
9634                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9635                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x7BFF,                                                         true,   65504,                                                          "max"));
9636                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x7BFF,                                                         true,   65504,                                                          "max"));
9637                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x7BFF,                                                         true,   65504,                                                          "max"));
9638
9639                 // +0
9640                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x0000,                                                         true,   0,                                                                      "p0"));
9641                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x0000,                                                         true,   0,                                                                      "p0"));
9642                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x0000,                                                         true,   0,                                                                      "p0"));
9643
9644                 // -0
9645                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_16,          0x8000,                                                         true,   0,                                                                      "m0"));
9646                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_32,          0x8000,                                                         true,   0,                                                                      "m0"));
9647                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_UNSIGNED_64,          0x8000,                                                         true,   0,                                                                      "m0"));
9648
9649                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_16,          0x449a4000,                                                     true,   1234));
9650                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_32,          0x449a4000,                                                     true,   1234));
9651                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_UNSIGNED_64,          0x449a4000,                                                     true,   1234));
9652                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_16,          0x4093480000000000,                                     true,   1234));
9653                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_32,          0x4093480000000000,                                     true,   1234));
9654                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_UNSIGNED_64,          0x4093480000000000,                                     true,   1234));
9655         }
9656         else if (instruction == "OpConvertUToF")
9657         {
9658                 // Normal numbers from uint8 range
9659                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     116,                                                            true,   0x5740,                                                         "116"));
9660                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     232,                                                            true,   0x43680000,                                                     "232"));
9661                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     164,                                                            true,   0x4064800000000000ull,                          "164"));
9662
9663                 // Maximum uint8 value
9664                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_16,                     255,                                                            true,   0x5BF8,                                                         "max"));
9665                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_32,                     255,                                                            true,   0x437F0000,                                                     "max"));
9666                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_8,           DATA_TYPE_FLOAT_64,                     255,                                                            true,   0x406FE00000000000ull,                          "max"));
9667
9668                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9669                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9670                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9671                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     1234,                                                           true,   0x64D2,                                                         "1234"));
9672
9673                 // 0x7BFF = 0111 1011 1111 1111 = 0 11110 1111111111 = 65504
9674                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9675                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9676                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_16,                     65504,                                                          true,   0x7BFF,                                                         "max"));
9677
9678                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9679                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_16,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9680                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9681                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_32,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9682                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_32,                     1234,                                                           true,   0x449a4000));
9683                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_UNSIGNED_64,          DATA_TYPE_FLOAT_64,                     1234,                                                           true,   0x4093480000000000));
9684         }
9685         else if (instruction == "OpConvertFToS")
9686         {
9687                 // Normal numbers from int8 range
9688                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xC980,                                                         true,   -11,                                                            "m11"));
9689                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC2140000,                                                     true,   -37,                                                            "m37"));
9690                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC050800000000000ull,                          true,   -66,                                                            "m66"));
9691
9692                 // Minimum int8 value
9693                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0xD800,                                                         true,   -128,                                                           "min"));
9694                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0xC3000000,                                                     true,   -128,                                                           "min"));
9695                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0xC060000000000000ull,                          true,   -128,                                                           "min"));
9696
9697                 // Maximum int8 value
9698                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x57F0,                                                         true,   127,                                                            "max"));
9699                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x42FE0000,                                                     true,   127,                                                            "max"));
9700                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x405FC00000000000ull,                          true,   127,                                                            "max"));
9701
9702                 // +0
9703                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x0000,                                                         true,   0,                                                                      "p0"));
9704                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x00000000,                                                     true,   0,                                                                      "p0"));
9705                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x0000000000000000ull,                          true,   0,                                                                      "p0"));
9706
9707                 // -0
9708                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_8,                     0x8000,                                                         true,   0,                                                                      "m0"));
9709                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_8,                     0x80000000,                                                     true,   0,                                                                      "m0"));
9710                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_8,                     0x8000000000000000ull,                          true,   0,                                                                      "m0"));
9711
9712                 // All hexadecimal values below represent -1234.0 as 32/64-bit IEEE 754 float
9713                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9714                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9715                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xE4D2,                                                         true,   -1234,                                                          "m1234"));
9716
9717                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9718                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0xF800,                                                         true,   -32768,                                                         "min"));
9719                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0xF800,                                                         true,   -32768,                                                         "min"));
9720                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0xF800,                                                         true,   -32768,                                                         "min"));
9721
9722                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9723                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x77FF,                                                         true,   32752,                                                          "max"));
9724                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x77FF,                                                         true,   32752,                                                          "max"));
9725                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x77FF,                                                         true,   32752,                                                          "max"));
9726
9727                 // +0
9728                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x0000,                                                         true,   0,                                                                      "p0"));
9729                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x0000,                                                         true,   0,                                                                      "p0"));
9730                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x0000,                                                         true,   0,                                                                      "p0"));
9731
9732                 // -0
9733                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_16,            0x8000,                                                         true,   0,                                                                      "m0"));
9734                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_32,            0x8000,                                                         true,   0,                                                                      "m0"));
9735                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_16,                     DATA_TYPE_SIGNED_64,            0x8000,                                                         true,   0,                                                                      "m0"));
9736
9737                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc49a4000,                                                     true,   -1234));
9738                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_32,            0xc49a4000,                                                     true,   -1234));
9739                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_64,            0xc49a4000,                                                     true,   -1234));
9740                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_16,            0xc093480000000000,                                     true,   -1234));
9741                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_32,            0xc093480000000000,                                     true,   -1234));
9742                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_64,                     DATA_TYPE_SIGNED_64,            0xc093480000000000,                                     true,   -1234));
9743                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0x453b9000,                                                     true,    3001,                                                          "p3001"));
9744                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_FLOAT_32,                     DATA_TYPE_SIGNED_16,            0xc53b9000,                                                     true,   -3001,                                                          "m3001"));
9745         }
9746         else if (instruction == "OpConvertSToF")
9747         {
9748                 // Normal numbers from int8 range
9749                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -12,                                                            true,   0xCA00,                                                         "m21"));
9750                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -21,                                                            true,   0xC1A80000,                                                     "m21"));
9751                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -99,                                                            true,   0xC058C00000000000ull,                          "m99"));
9752
9753                 // Minimum int8 value
9754                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     -128,                                                           true,   0xD800,                                                         "min"));
9755                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     -128,                                                           true,   0xC3000000,                                                     "min"));
9756                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     -128,                                                           true,   0xC060000000000000ull,                          "min"));
9757
9758                 // Maximum int8 value
9759                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_16,                     127,                                                            true,   0x57F0,                                                         "max"));
9760                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_32,                     127,                                                            true,   0x42FE0000,                                                     "max"));
9761                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_8,                     DATA_TYPE_FLOAT_64,                     127,                                                            true,   0x405FC00000000000ull,                          "max"));
9762
9763                 // All hexadecimal values below represent 1234.0 as 32/64-bit IEEE 754 float
9764                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9765                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9766                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -1234,                                                          true,   0xE4D2,                                                         "m1234"));
9767
9768                 // 0xF800 = 1111 1000 0000 0000 = 1 11110 0000000000 = -32768
9769                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9770                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9771                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     -32768,                                                         true,   0xF800,                                                         "min"));
9772
9773                 // 0x77FF = 0111 0111 1111 1111 = 0 11101 1111111111 = 32752
9774                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9775                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9776                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_16,                     32752,                                                          true,   0x77FF,                                                         "max"));
9777
9778                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9779                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_16,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9780                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9781                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_32,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9782                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_32,                     -1234,                                                          true,   0xc49a4000));
9783                 testCases.push_back(ConvertCase(instruction,    DATA_TYPE_SIGNED_64,            DATA_TYPE_FLOAT_64,                     -1234,                                                          true,   0xc093480000000000));
9784         }
9785         else
9786                 DE_FATAL("Unknown instruction");
9787 }
9788
9789 const map<string, string> getConvertCaseFragments (string instruction, const ConvertCase& convertCase)
9790 {
9791         map<string, string> params = convertCase.m_asmTypes;
9792         map<string, string> fragments;
9793
9794         params["instruction"] = instruction;
9795         params["inDecorator"] = getByteWidthStr(convertCase.m_fromType);
9796
9797         const StringTemplate decoration (
9798                 "      OpDecorate %SSBOi DescriptorSet 0\n"
9799                 "      OpDecorate %SSBOo DescriptorSet 0\n"
9800                 "      OpDecorate %SSBOi Binding 0\n"
9801                 "      OpDecorate %SSBOo Binding 1\n"
9802                 "      OpDecorate %s_SSBOi Block\n"
9803                 "      OpDecorate %s_SSBOo Block\n"
9804                 "OpMemberDecorate %s_SSBOi 0 Offset 0\n"
9805                 "OpMemberDecorate %s_SSBOo 0 Offset 0\n");
9806
9807         const StringTemplate pre_main (
9808                 "${datatype_additional_decl:opt}"
9809                 "    %ptr_in = OpTypePointer StorageBuffer %${inputType}\n"
9810                 "   %ptr_out = OpTypePointer StorageBuffer %${outputType}\n"
9811                 "   %s_SSBOi = OpTypeStruct %${inputType}\n"
9812                 "   %s_SSBOo = OpTypeStruct %${outputType}\n"
9813                 " %ptr_SSBOi = OpTypePointer StorageBuffer %s_SSBOi\n"
9814                 " %ptr_SSBOo = OpTypePointer StorageBuffer %s_SSBOo\n"
9815                 "     %SSBOi = OpVariable %ptr_SSBOi StorageBuffer\n"
9816                 "     %SSBOo = OpVariable %ptr_SSBOo StorageBuffer\n");
9817
9818         const StringTemplate testfun (
9819                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9820                 "%param     = OpFunctionParameter %v4f32\n"
9821                 "%label     = OpLabel\n"
9822                 "%iLoc      = OpAccessChain %ptr_in %SSBOi %c_u32_0\n"
9823                 "%oLoc      = OpAccessChain %ptr_out %SSBOo %c_u32_0\n"
9824                 "%valIn     = OpLoad %${inputType} %iLoc\n"
9825                 "%valOut    = ${instruction} %${outputType} %valIn\n"
9826                 "             OpStore %oLoc %valOut\n"
9827                 "             OpReturnValue %param\n"
9828                 "             OpFunctionEnd\n");
9829
9830         params["datatype_extensions"] =
9831                 params["datatype_extensions"] +
9832                 "OpExtension \"SPV_KHR_storage_buffer_storage_class\"\n";
9833
9834         fragments["capability"] = params["datatype_capabilities"];
9835         fragments["extension"]  = params["datatype_extensions"];
9836         fragments["decoration"] = decoration.specialize(params);
9837         fragments["pre_main"]   = pre_main.specialize(params);
9838         fragments["testfun"]    = testfun.specialize(params);
9839
9840         return fragments;
9841 }
9842
9843 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in compute shaders
9844 tcu::TestCaseGroup* createConvertComputeTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9845 {
9846         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9847         vector<ConvertCase>                                     testCases;
9848         createConvertCases(testCases, instruction);
9849
9850         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9851         {
9852                 ComputeShaderSpec spec;
9853                 spec.assembly                   = getConvertCaseShaderStr(instruction, *test);
9854                 spec.numWorkGroups              = IVec3(1, 1, 1);
9855                 spec.inputs.push_back   (test->m_inputBuffer);
9856                 spec.outputs.push_back  (test->m_outputBuffer);
9857
9858                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, spec.requestedVulkanFeatures, spec.extensions);
9859
9860                 group->addChild(new SpvAsmComputeShaderCase(testCtx, test->m_name.c_str(), "", spec));
9861         }
9862         return group.release();
9863 }
9864
9865 // Test for OpSConvert, OpUConvert, OpFConvert and OpConvert* in graphics shaders
9866 tcu::TestCaseGroup* createConvertGraphicsTests (tcu::TestContext& testCtx, const string& instruction, const string& name)
9867 {
9868         de::MovePtr<tcu::TestCaseGroup>         group(new tcu::TestCaseGroup(testCtx, name.c_str(), instruction.c_str()));
9869         vector<ConvertCase>                                     testCases;
9870         createConvertCases(testCases, instruction);
9871
9872         for (vector<ConvertCase>::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
9873         {
9874                 map<string, string>     fragments               = getConvertCaseFragments(instruction, *test);
9875                 VulkanFeatures          vulkanFeatures;
9876                 GraphicsResources       resources;
9877                 vector<string>          extensions;
9878                 SpecConstants           noSpecConstants;
9879                 PushConstants           noPushConstants;
9880                 GraphicsInterfaces      noInterfaces;
9881                 tcu::RGBA                       defaultColors[4];
9882
9883                 getDefaultColors                        (defaultColors);
9884                 resources.inputs.push_back      (Resource(test->m_inputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9885                 resources.outputs.push_back     (Resource(test->m_outputBuffer, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
9886                 extensions.push_back            ("VK_KHR_storage_buffer_storage_class");
9887
9888                 getVulkanFeaturesAndExtensions(test->m_fromType, test->m_toType, vulkanFeatures, extensions);
9889
9890                 vulkanFeatures.coreFeatures.vertexPipelineStoresAndAtomics      = true;
9891                 vulkanFeatures.coreFeatures.fragmentStoresAndAtomics            = true;
9892
9893                 createTestsForAllStages(
9894                         test->m_name, defaultColors, defaultColors, fragments, noSpecConstants,
9895                         noPushConstants, resources, noInterfaces, extensions, vulkanFeatures, group.get());
9896         }
9897         return group.release();
9898 }
9899
9900 // Constant-Creation Instructions: OpConstant, OpConstantComposite
9901 tcu::TestCaseGroup* createOpConstantFloat16Tests(tcu::TestContext& testCtx)
9902 {
9903         de::MovePtr<tcu::TestCaseGroup> opConstantCompositeTests                (new tcu::TestCaseGroup(testCtx, "opconstant", "OpConstant and OpConstantComposite instruction"));
9904         RGBA                                                    inputColors[4];
9905         RGBA                                                    outputColors[4];
9906         vector<string>                                  extensions;
9907         GraphicsResources                               resources;
9908         VulkanFeatures                                  features;
9909
9910         const char                                              functionStart[]  =
9911                 "%test_code             = OpFunction %v4f32 None %v4f32_v4f32_function\n"
9912                 "%param1                = OpFunctionParameter %v4f32\n"
9913                 "%lbl                   = OpLabel\n";
9914
9915         const char                                              functionEnd[]           =
9916                 "%transformed_param_32  = OpFConvert %v4f32 %transformed_param\n"
9917                 "                         OpReturnValue %transformed_param_32\n"
9918                 "                         OpFunctionEnd\n";
9919
9920         struct NameConstantsCode
9921         {
9922                 string name;
9923                 string constants;
9924                 string code;
9925         };
9926
9927 #define FLOAT_16_COMMON_TYPES_AND_CONSTS \
9928                         "%f16                  = OpTypeFloat 16\n"                                                 \
9929                         "%c_f16_0              = OpConstant %f16 0.0\n"                                            \
9930                         "%c_f16_0_5            = OpConstant %f16 0.5\n"                                            \
9931                         "%c_f16_1              = OpConstant %f16 1.0\n"                                            \
9932                         "%v4f16                = OpTypeVector %f16 4\n"                                            \
9933                         "%fp_f16               = OpTypePointer Function %f16\n"                                    \
9934                         "%fp_v4f16             = OpTypePointer Function %v4f16\n"                                  \
9935                         "%c_v4f16_1_1_1_1      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n" \
9936                         "%a4f16                = OpTypeArray %f16 %c_u32_4\n"                                      \
9937
9938         NameConstantsCode                               tests[] =
9939         {
9940                 {
9941                         "vec4",
9942
9943                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9944                         "%cval                 = OpConstantComposite %v4f16 %c_f16_0_5 %c_f16_0_5 %c_f16_0_5 %c_f16_0\n",
9945                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9946                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %cval\n"
9947                 },
9948                 {
9949                         "struct",
9950
9951                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9952                         "%stype                = OpTypeStruct %v4f16 %f16\n"
9953                         "%fp_stype             = OpTypePointer Function %stype\n"
9954                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9955                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9956                         "%cvec                 = OpConstantComposite %v4f16 %f16_1_5 %f16_1_5 %f16_1_5 %c_f16_1\n"
9957                         "%cval                 = OpConstantComposite %stype %cvec %f16_n_1\n",
9958
9959                         "%v                    = OpVariable %fp_stype Function %cval\n"
9960                         "%vec_ptr              = OpAccessChain %fp_v4f16 %v %c_u32_0\n"
9961                         "%f16_ptr              = OpAccessChain %fp_f16 %v %c_u32_1\n"
9962                         "%vec_val              = OpLoad %v4f16 %vec_ptr\n"
9963                         "%f16_val              = OpLoad %f16 %f16_ptr\n"
9964                         "%tmp1                 = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_1 %f16_val\n" // vec4(-1)
9965                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9966                         "%tmp2                 = OpFAdd %v4f16 %tmp1 %param1_16\n" // param1 + vec4(-1)
9967                         "%transformed_param    = OpFAdd %v4f16 %tmp2 %vec_val\n" // param1 + vec4(-1) + vec4(1.5, 1.5, 1.5, 1.0)
9968                 },
9969                 {
9970                         // [1|0|0|0.5] [x] = x + 0.5
9971                         // [0|1|0|0.5] [y] = y + 0.5
9972                         // [0|0|1|0.5] [z] = z + 0.5
9973                         // [0|0|0|1  ] [1] = 1
9974                         "matrix",
9975
9976                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9977                         "%mat4x4_f16           = OpTypeMatrix %v4f16 4\n"
9978                         "%v4f16_1_0_0_0        = OpConstantComposite %v4f16 %c_f16_1 %c_f16_0 %c_f16_0 %c_f16_0\n"
9979                         "%v4f16_0_1_0_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_1 %c_f16_0 %c_f16_0\n"
9980                         "%v4f16_0_0_1_0        = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_1 %c_f16_0\n"
9981                         "%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"
9982                         "%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",
9983
9984                         "%param1_16            = OpFConvert %v4f16 %param1\n"
9985                         "%transformed_param    = OpMatrixTimesVector %v4f16 %cval %param1_16\n"
9986                 },
9987                 {
9988                         "array",
9989
9990                         FLOAT_16_COMMON_TYPES_AND_CONSTS
9991                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
9992                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
9993                         "%f16_n_1              = OpConstant %f16 -1.0\n"
9994                         "%f16_1_5              = OpConstant %f16 !0x3e00\n" // +1.5
9995                         "%carr                 = OpConstantComposite %a4f16 %c_f16_0 %f16_n_1 %f16_1_5 %c_f16_0\n",
9996
9997                         "%v                    = OpVariable %fp_a4f16 Function %carr\n"
9998                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_0\n"
9999                         "%f1                   = OpAccessChain %fp_f16 %v %c_u32_1\n"
10000                         "%f2                   = OpAccessChain %fp_f16 %v %c_u32_2\n"
10001                         "%f3                   = OpAccessChain %fp_f16 %v %c_u32_3\n"
10002                         "%f_val                = OpLoad %f16 %f\n"
10003                         "%f1_val               = OpLoad %f16 %f1\n"
10004                         "%f2_val               = OpLoad %f16 %f2\n"
10005                         "%f3_val               = OpLoad %f16 %f3\n"
10006                         "%ftot1                = OpFAdd %f16 %f_val %f1_val\n"
10007                         "%ftot2                = OpFAdd %f16 %ftot1 %f2_val\n"
10008                         "%ftot3                = OpFAdd %f16 %ftot2 %f3_val\n"  // 0 - 1 + 1.5 + 0
10009                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %ftot3\n"
10010                         "%param1_16            = OpFConvert %v4f16 %param1\n"
10011                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
10012                 },
10013                 {
10014                         //
10015                         // [
10016                         //   {
10017                         //      0.0,
10018                         //      [ 1.0, 1.0, 1.0, 1.0]
10019                         //   },
10020                         //   {
10021                         //      1.0,
10022                         //      [ 0.0, 0.5, 0.0, 0.0]
10023                         //   }, //     ^^^
10024                         //   {
10025                         //      0.0,
10026                         //      [ 1.0, 1.0, 1.0, 1.0]
10027                         //   }
10028                         // ]
10029                         "array_of_struct_of_array",
10030
10031                         FLOAT_16_COMMON_TYPES_AND_CONSTS
10032                         "%c_v4f16_1_1_1_0      = OpConstantComposite %v4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_0\n"
10033                         "%fp_a4f16             = OpTypePointer Function %a4f16\n"
10034                         "%stype                = OpTypeStruct %f16 %a4f16\n"
10035                         "%a3stype              = OpTypeArray %stype %c_u32_3\n"
10036                         "%fp_a3stype           = OpTypePointer Function %a3stype\n"
10037                         "%ca4f16_0             = OpConstantComposite %a4f16 %c_f16_0 %c_f16_0_5 %c_f16_0 %c_f16_0\n"
10038                         "%ca4f16_1             = OpConstantComposite %a4f16 %c_f16_1 %c_f16_1 %c_f16_1 %c_f16_1\n"
10039                         "%cstype1              = OpConstantComposite %stype %c_f16_0 %ca4f16_1\n"
10040                         "%cstype2              = OpConstantComposite %stype %c_f16_1 %ca4f16_0\n"
10041                         "%carr                 = OpConstantComposite %a3stype %cstype1 %cstype2 %cstype1",
10042
10043                         "%v                    = OpVariable %fp_a3stype Function %carr\n"
10044                         "%f                    = OpAccessChain %fp_f16 %v %c_u32_1 %c_u32_1 %c_u32_1\n"
10045                         "%f_l                  = OpLoad %f16 %f\n"
10046                         "%add_vec              = OpVectorTimesScalar %v4f16 %c_v4f16_1_1_1_0 %f_l\n"
10047                         "%param1_16            = OpFConvert %v4f16 %param1\n"
10048                         "%transformed_param    = OpFAdd %v4f16 %param1_16 %add_vec\n"
10049                 }
10050         };
10051
10052         getHalfColorsFullAlpha(inputColors);
10053         outputColors[0] = RGBA(255, 255, 255, 255);
10054         outputColors[1] = RGBA(255, 127, 127, 255);
10055         outputColors[2] = RGBA(127, 255, 127, 255);
10056         outputColors[3] = RGBA(127, 127, 255, 255);
10057
10058         extensions.push_back("VK_KHR_16bit_storage");
10059         extensions.push_back("VK_KHR_shader_float16_int8");
10060         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10061
10062         for (size_t testNdx = 0; testNdx < sizeof(tests) / sizeof(NameConstantsCode); ++testNdx)
10063         {
10064                 map<string, string> fragments;
10065
10066                 fragments["extension"]  = "OpExtension \"SPV_KHR_16bit_storage\"";
10067                 fragments["capability"] = "OpCapability Float16\n";
10068                 fragments["pre_main"]   = tests[testNdx].constants;
10069                 fragments["testfun"]    = string(functionStart) + tests[testNdx].code + functionEnd;
10070
10071                 createTestsForAllStages(tests[testNdx].name, inputColors, outputColors, fragments, resources, extensions, opConstantCompositeTests.get(), features);
10072         }
10073         return opConstantCompositeTests.release();
10074 }
10075
10076 template<typename T>
10077 void finalizeTestsCreation (T&                                                  specResource,
10078                                                         const map<string, string>&      fragments,
10079                                                         tcu::TestContext&                       testCtx,
10080                                                         tcu::TestCaseGroup&                     testGroup,
10081                                                         const std::string&                      testName,
10082                                                         const VulkanFeatures&           vulkanFeatures,
10083                                                         const vector<string>&           extensions,
10084                                                         const IVec3&                            numWorkGroups);
10085
10086 template<>
10087 void finalizeTestsCreation (GraphicsResources&                  specResource,
10088                                                         const map<string, string>&      fragments,
10089                                                         tcu::TestContext&                       ,
10090                                                         tcu::TestCaseGroup&                     testGroup,
10091                                                         const std::string&                      testName,
10092                                                         const VulkanFeatures&           vulkanFeatures,
10093                                                         const vector<string>&           extensions,
10094                                                         const IVec3&                            )
10095 {
10096         RGBA defaultColors[4];
10097         getDefaultColors(defaultColors);
10098
10099         createTestsForAllStages(testName, defaultColors, defaultColors, fragments, specResource, extensions, &testGroup, vulkanFeatures);
10100 }
10101
10102 template<>
10103 void finalizeTestsCreation (ComputeShaderSpec&                  specResource,
10104                                                         const map<string, string>&      fragments,
10105                                                         tcu::TestContext&                       testCtx,
10106                                                         tcu::TestCaseGroup&                     testGroup,
10107                                                         const std::string&                      testName,
10108                                                         const VulkanFeatures&           vulkanFeatures,
10109                                                         const vector<string>&           extensions,
10110                                                         const IVec3&                            numWorkGroups)
10111 {
10112         specResource.numWorkGroups = numWorkGroups;
10113         specResource.requestedVulkanFeatures = vulkanFeatures;
10114         specResource.extensions = extensions;
10115
10116         specResource.assembly = makeComputeShaderAssembly(fragments);
10117
10118         testGroup.addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", specResource));
10119 }
10120
10121 template<class SpecResource>
10122 tcu::TestCaseGroup* createFloat16LogicalSet (tcu::TestContext& testCtx, const bool nanSupported)
10123 {
10124         const string                                            nan                                     = nanSupported ? "_nan" : "";
10125         const string                                            groupName                       = "logical" + nan;
10126         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, groupName.c_str(), "Float 16 logical tests"));
10127
10128         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10129         const string                                            spvCapabilities         = string("OpCapability StorageUniformBufferBlock16\n") + (nanSupported ? "OpCapability SignedZeroInfNanPreserve\n" : "");
10130         const string                                            spvExtensions           = string("OpExtension \"SPV_KHR_16bit_storage\"\n") + (nanSupported ? "OpExtension \"SPV_KHR_float_controls\"\n" : "");
10131         const string                                            spvExecutionMode        = nanSupported ? "OpExecutionMode %BP_main SignedZeroInfNanPreserve 16\n" : "";
10132         const deUint32                                          numDataPoints           = 16;
10133         const vector<deFloat16>                         float16Data                     = getFloat16s(rnd, numDataPoints);
10134         const vector<deFloat16>                         float16Data1            = squarize(float16Data, 0);
10135         const vector<deFloat16>                         float16Data2            = squarize(float16Data, 1);
10136         const vector<deFloat16>                         float16DataVec1         = squarizeVector(float16Data, 0);
10137         const vector<deFloat16>                         float16DataVec2         = squarizeVector(float16Data, 1);
10138         const vector<deFloat16>                         float16OutDummy         (float16Data1.size(), 0);
10139         const vector<deFloat16>                         float16OutVecDummy      (float16DataVec1.size(), 0);
10140
10141         struct TestOp
10142         {
10143                 const char*             opCode;
10144                 VerifyIOFunc    verifyFuncNan;
10145                 VerifyIOFunc    verifyFuncNonNan;
10146                 const deUint32  argCount;
10147         };
10148
10149         const TestOp    testOps[]       =
10150         {
10151                 { "OpIsNan"                                             ,       compareFP16Logical<fp16isNan,                           true,  false, true>,    compareFP16Logical<fp16isNan,                           true,  false, false>,   1       },
10152                 { "OpIsInf"                                             ,       compareFP16Logical<fp16isInf,                           true,  false, true>,    compareFP16Logical<fp16isInf,                           true,  false, false>,   1       },
10153                 { "OpFOrdEqual"                                 ,       compareFP16Logical<fp16isEqual,                         false, true,  true>,    compareFP16Logical<fp16isEqual,                         false, true,  false>,   2       },
10154                 { "OpFUnordEqual"                               ,       compareFP16Logical<fp16isEqual,                         false, false, true>,    compareFP16Logical<fp16isEqual,                         false, false, false>,   2       },
10155                 { "OpFOrdNotEqual"                              ,       compareFP16Logical<fp16isUnequal,                       false, true,  true>,    compareFP16Logical<fp16isUnequal,                       false, true,  false>,   2       },
10156                 { "OpFUnordNotEqual"                    ,       compareFP16Logical<fp16isUnequal,                       false, false, true>,    compareFP16Logical<fp16isUnequal,                       false, false, false>,   2       },
10157                 { "OpFOrdLessThan"                              ,       compareFP16Logical<fp16isLess,                          false, true,  true>,    compareFP16Logical<fp16isLess,                          false, true,  false>,   2       },
10158                 { "OpFUnordLessThan"                    ,       compareFP16Logical<fp16isLess,                          false, false, true>,    compareFP16Logical<fp16isLess,                          false, false, false>,   2       },
10159                 { "OpFOrdGreaterThan"                   ,       compareFP16Logical<fp16isGreater,                       false, true,  true>,    compareFP16Logical<fp16isGreater,                       false, true,  false>,   2       },
10160                 { "OpFUnordGreaterThan"                 ,       compareFP16Logical<fp16isGreater,                       false, false, true>,    compareFP16Logical<fp16isGreater,                       false, false, false>,   2       },
10161                 { "OpFOrdLessThanEqual"                 ,       compareFP16Logical<fp16isLessOrEqual,           false, true,  true>,    compareFP16Logical<fp16isLessOrEqual,           false, true,  false>,   2       },
10162                 { "OpFUnordLessThanEqual"               ,       compareFP16Logical<fp16isLessOrEqual,           false, false, true>,    compareFP16Logical<fp16isLessOrEqual,           false, false, false>,   2       },
10163                 { "OpFOrdGreaterThanEqual"              ,       compareFP16Logical<fp16isGreaterOrEqual,        false, true,  true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, true,  false>,   2       },
10164                 { "OpFUnordGreaterThanEqual"    ,       compareFP16Logical<fp16isGreaterOrEqual,        false, false, true>,    compareFP16Logical<fp16isGreaterOrEqual,        false, false, false>,   2       },
10165         };
10166
10167         { // scalar cases
10168                 const StringTemplate preMain
10169                 (
10170                         "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10171                         "      %f16 = OpTypeFloat 16\n"
10172                         "  %c_f16_0 = OpConstant %f16 0.0\n"
10173                         "  %c_f16_1 = OpConstant %f16 1.0\n"
10174                         "   %up_f16 = OpTypePointer Uniform %f16\n"
10175                         "   %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
10176                         "   %SSBO16 = OpTypeStruct %ra_f16\n"
10177                         "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10178                         "%ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
10179                         "%ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
10180                         " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10181                 );
10182
10183                 const StringTemplate decoration
10184                 (
10185                         "OpDecorate %ra_f16 ArrayStride 2\n"
10186                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
10187                         "OpDecorate %SSBO16 BufferBlock\n"
10188                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
10189                         "OpDecorate %ssbo_src0 Binding 0\n"
10190                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
10191                         "OpDecorate %ssbo_src1 Binding 1\n"
10192                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
10193                         "OpDecorate %ssbo_dst Binding 2\n"
10194                 );
10195
10196                 const StringTemplate testFun
10197                 (
10198                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10199                         "    %param = OpFunctionParameter %v4f32\n"
10200
10201                         "    %entry = OpLabel\n"
10202                         "        %i = OpVariable %fp_i32 Function\n"
10203                         "             OpStore %i %c_i32_0\n"
10204                         "             OpBranch %loop\n"
10205
10206                         "     %loop = OpLabel\n"
10207                         "    %i_cmp = OpLoad %i32 %i\n"
10208                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10209                         "             OpLoopMerge %merge %next None\n"
10210                         "             OpBranchConditional %lt %write %merge\n"
10211
10212                         "    %write = OpLabel\n"
10213                         "      %ndx = OpLoad %i32 %i\n"
10214
10215                         "     %src0 = OpAccessChain %up_f16 %ssbo_src0 %c_i32_0 %ndx\n"
10216                         " %val_src0 = OpLoad %f16 %src0\n"
10217
10218                         "${op_arg1_calc}"
10219
10220                         " %val_bdst = ${op_code} %bool %val_src0 ${op_arg1}\n"
10221                         "  %val_dst = OpSelect %f16 %val_bdst %c_f16_1 %c_f16_0\n"
10222                         "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
10223                         "             OpStore %dst %val_dst\n"
10224                         "             OpBranch %next\n"
10225
10226                         "     %next = OpLabel\n"
10227                         "    %i_cur = OpLoad %i32 %i\n"
10228                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10229                         "             OpStore %i %i_new\n"
10230                         "             OpBranch %loop\n"
10231
10232                         "    %merge = OpLabel\n"
10233                         "             OpReturnValue %param\n"
10234
10235                         "             OpFunctionEnd\n"
10236                 );
10237
10238                 const StringTemplate arg1Calc
10239                 (
10240                         "     %src1 = OpAccessChain %up_f16 %ssbo_src1 %c_i32_0 %ndx\n"
10241                         " %val_src1 = OpLoad %f16 %src1\n"
10242                 );
10243
10244                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10245                 {
10246                         const size_t            iterations              = float16Data1.size();
10247                         const TestOp&           testOp                  = testOps[testOpsIdx];
10248                         const string            testName                = de::toLower(string(testOp.opCode)) + "_scalar";
10249                         SpecResource            specResource;
10250                         map<string, string>     specs;
10251                         VulkanFeatures          features;
10252                         map<string, string>     fragments;
10253                         vector<string>          extensions;
10254
10255                         specs["num_data_points"]        = de::toString(iterations);
10256                         specs["op_code"]                        = testOp.opCode;
10257                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10258                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10259
10260                         fragments["extension"]          = spvExtensions;
10261                         fragments["capability"]         = spvCapabilities;
10262                         fragments["execution_mode"]     = spvExecutionMode;
10263                         fragments["decoration"]         = decoration.specialize(specs);
10264                         fragments["pre_main"]           = preMain.specialize(specs);
10265                         fragments["testfun"]            = testFun.specialize(specs);
10266
10267                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10268                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Data2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10269                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10270                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10271
10272                         extensions.push_back("VK_KHR_16bit_storage");
10273                         extensions.push_back("VK_KHR_shader_float16_int8");
10274
10275                         if (nanSupported)
10276                         {
10277                                 extensions.push_back("VK_KHR_shader_float_controls");
10278
10279                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10280                         }
10281
10282                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10283                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10284
10285                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10286                 }
10287         }
10288         { // vector cases
10289                 const StringTemplate preMain
10290                 (
10291                         "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10292                         "     %v2bool = OpTypeVector %bool 2\n"
10293                         "        %f16 = OpTypeFloat 16\n"
10294                         "    %c_f16_0 = OpConstant %f16 0.0\n"
10295                         "    %c_f16_1 = OpConstant %f16 1.0\n"
10296                         "      %v2f16 = OpTypeVector %f16 2\n"
10297                         "%c_v2f16_0_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10298                         "%c_v2f16_1_1 = OpConstantComposite %v2f16 %c_f16_1 %c_f16_1\n"
10299                         "   %up_v2f16 = OpTypePointer Uniform %v2f16\n"
10300                         "   %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
10301                         "     %SSBO16 = OpTypeStruct %ra_v2f16\n"
10302                         "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10303                         "  %ssbo_src0 = OpVariable %up_SSBO16 Uniform\n"
10304                         "  %ssbo_src1 = OpVariable %up_SSBO16 Uniform\n"
10305                         "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10306                 );
10307
10308                 const StringTemplate decoration
10309                 (
10310                         "OpDecorate %ra_v2f16 ArrayStride 4\n"
10311                         "OpMemberDecorate %SSBO16 0 Offset 0\n"
10312                         "OpDecorate %SSBO16 BufferBlock\n"
10313                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
10314                         "OpDecorate %ssbo_src0 Binding 0\n"
10315                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
10316                         "OpDecorate %ssbo_src1 Binding 1\n"
10317                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
10318                         "OpDecorate %ssbo_dst Binding 2\n"
10319                 );
10320
10321                 const StringTemplate testFun
10322                 (
10323                         "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10324                         "    %param = OpFunctionParameter %v4f32\n"
10325
10326                         "    %entry = OpLabel\n"
10327                         "        %i = OpVariable %fp_i32 Function\n"
10328                         "             OpStore %i %c_i32_0\n"
10329                         "             OpBranch %loop\n"
10330
10331                         "     %loop = OpLabel\n"
10332                         "    %i_cmp = OpLoad %i32 %i\n"
10333                         "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10334                         "             OpLoopMerge %merge %next None\n"
10335                         "             OpBranchConditional %lt %write %merge\n"
10336
10337                         "    %write = OpLabel\n"
10338                         "      %ndx = OpLoad %i32 %i\n"
10339
10340                         "     %src0 = OpAccessChain %up_v2f16 %ssbo_src0 %c_i32_0 %ndx\n"
10341                         " %val_src0 = OpLoad %v2f16 %src0\n"
10342
10343                         "${op_arg1_calc}"
10344
10345                         " %val_bdst = ${op_code} %v2bool %val_src0 ${op_arg1}\n"
10346                         "  %val_dst = OpSelect %v2f16 %val_bdst %c_v2f16_1_1 %c_v2f16_0_0\n"
10347                         "      %dst = OpAccessChain %up_v2f16 %ssbo_dst %c_i32_0 %ndx\n"
10348                         "             OpStore %dst %val_dst\n"
10349                         "             OpBranch %next\n"
10350
10351                         "     %next = OpLabel\n"
10352                         "    %i_cur = OpLoad %i32 %i\n"
10353                         "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10354                         "             OpStore %i %i_new\n"
10355                         "             OpBranch %loop\n"
10356
10357                         "    %merge = OpLabel\n"
10358                         "             OpReturnValue %param\n"
10359
10360                         "             OpFunctionEnd\n"
10361                 );
10362
10363                 const StringTemplate arg1Calc
10364                 (
10365                         "     %src1 = OpAccessChain %up_v2f16 %ssbo_src1 %c_i32_0 %ndx\n"
10366                         " %val_src1 = OpLoad %v2f16 %src1\n"
10367                 );
10368
10369                 for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10370                 {
10371                         const deUint32          itemsPerVec     = 2;
10372                         const size_t            iterations      = float16DataVec1.size() / itemsPerVec;
10373                         const TestOp&           testOp          = testOps[testOpsIdx];
10374                         const string            testName        = de::toLower(string(testOp.opCode)) + "_vector";
10375                         SpecResource            specResource;
10376                         map<string, string>     specs;
10377                         vector<string>          extensions;
10378                         VulkanFeatures          features;
10379                         map<string, string>     fragments;
10380
10381                         specs["num_data_points"]        = de::toString(iterations);
10382                         specs["op_code"]                        = testOp.opCode;
10383                         specs["op_arg1"]                        = (testOp.argCount == 1) ? "" : "%val_src1";
10384                         specs["op_arg1_calc"]           = (testOp.argCount == 1) ? "" : arg1Calc.specialize(specs);
10385
10386                         fragments["extension"]          = spvExtensions;
10387                         fragments["capability"]         = spvCapabilities;
10388                         fragments["execution_mode"]     = spvExecutionMode;
10389                         fragments["decoration"]         = decoration.specialize(specs);
10390                         fragments["pre_main"]           = preMain.specialize(specs);
10391                         fragments["testfun"]            = testFun.specialize(specs);
10392
10393                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10394                         specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16DataVec2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10395                         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutVecDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10396                         specResource.verifyIO = nanSupported ? testOp.verifyFuncNan : testOp.verifyFuncNonNan;
10397
10398                         extensions.push_back("VK_KHR_16bit_storage");
10399                         extensions.push_back("VK_KHR_shader_float16_int8");
10400
10401                         if (nanSupported)
10402                         {
10403                                 extensions.push_back("VK_KHR_shader_float_controls");
10404
10405                                 features.floatControlsProperties.shaderSignedZeroInfNanPreserveFloat16 = DE_TRUE;
10406                         }
10407
10408                         features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10409                         features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10410
10411                         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10412                 }
10413         }
10414
10415         return testGroup.release();
10416 }
10417
10418 bool compareFP16FunctionSetFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10419 {
10420         if (inputs.size() != 1 || outputAllocs.size() != 1)
10421                 return false;
10422
10423         vector<deUint8> input1Bytes;
10424
10425         inputs[0].getBytes(input1Bytes);
10426
10427         const deUint16* const   input1AsFP16    = (const deUint16*)&input1Bytes[0];
10428         const deUint16* const   outputAsFP16    = (const deUint16*)outputAllocs[0]->getHostPtr();
10429         std::string                             error;
10430
10431         for (size_t idx = 0; idx < input1Bytes.size() / sizeof(deUint16); ++idx)
10432         {
10433                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
10434                 {
10435                         log << TestLog::Message << error << TestLog::EndMessage;
10436
10437                         return false;
10438                 }
10439         }
10440
10441         return true;
10442 }
10443
10444 template<class SpecResource>
10445 tcu::TestCaseGroup* createFloat16FuncSet (tcu::TestContext& testCtx)
10446 {
10447         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "function", "Float 16 function call related tests"));
10448
10449         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10450         const StringTemplate                            capabilities            ("OpCapability ${cap}\n");
10451         const deUint32                                          numDataPoints           = 256;
10452         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
10453         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
10454         map<string, string>                                     fragments;
10455
10456         struct TestType
10457         {
10458                 const deUint32  typeComponents;
10459                 const char*             typeName;
10460                 const char*             typeDecls;
10461         };
10462
10463         const TestType  testTypes[]     =
10464         {
10465                 {
10466                         1,
10467                         "f16",
10468                         ""
10469                 },
10470                 {
10471                         2,
10472                         "v2f16",
10473                         "      %v2f16 = OpTypeVector %f16 2\n"
10474                         "  %c_v2f16_0 = OpConstantComposite %v2f16 %c_f16_0 %c_f16_0\n"
10475                 },
10476                 {
10477                         4,
10478                         "v4f16",
10479                         "      %v4f16 = OpTypeVector %f16 4\n"
10480                         "  %c_v4f16_0 = OpConstantComposite %v4f16 %c_f16_0 %c_f16_0 %c_f16_0 %c_f16_0\n"
10481                 },
10482         };
10483
10484         const StringTemplate preMain
10485         (
10486                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10487                 "     %v2bool = OpTypeVector %bool 2\n"
10488                 "        %f16 = OpTypeFloat 16\n"
10489                 "    %c_f16_0 = OpConstant %f16 0.0\n"
10490
10491                 "${type_decls}"
10492
10493                 "  %${tt}_fun = OpTypeFunction %${tt} %${tt}\n"
10494                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
10495                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10496                 "     %SSBO16 = OpTypeStruct %ra_${tt}\n"
10497                 "  %up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10498                 "   %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10499                 "   %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10500         );
10501
10502         const StringTemplate decoration
10503         (
10504                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10505                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10506                 "OpDecorate %SSBO16 BufferBlock\n"
10507                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10508                 "OpDecorate %ssbo_src Binding 0\n"
10509                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10510                 "OpDecorate %ssbo_dst Binding 1\n"
10511         );
10512
10513         const StringTemplate testFun
10514         (
10515                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10516                 "    %param = OpFunctionParameter %v4f32\n"
10517                 "    %entry = OpLabel\n"
10518
10519                 "        %i = OpVariable %fp_i32 Function\n"
10520                 "             OpStore %i %c_i32_0\n"
10521                 "             OpBranch %loop\n"
10522
10523                 "     %loop = OpLabel\n"
10524                 "    %i_cmp = OpLoad %i32 %i\n"
10525                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
10526                 "             OpLoopMerge %merge %next None\n"
10527                 "             OpBranchConditional %lt %write %merge\n"
10528
10529                 "    %write = OpLabel\n"
10530                 "      %ndx = OpLoad %i32 %i\n"
10531
10532                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10533                 "  %val_src = OpLoad %${tt} %src\n"
10534
10535                 "  %val_dst = OpFunctionCall %${tt} %pass_fun %val_src\n"
10536                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10537                 "             OpStore %dst %val_dst\n"
10538                 "             OpBranch %next\n"
10539
10540                 "     %next = OpLabel\n"
10541                 "    %i_cur = OpLoad %i32 %i\n"
10542                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
10543                 "             OpStore %i %i_new\n"
10544                 "             OpBranch %loop\n"
10545
10546                 "    %merge = OpLabel\n"
10547                 "             OpReturnValue %param\n"
10548
10549                 "             OpFunctionEnd\n"
10550
10551                 " %pass_fun = OpFunction %${tt} None %${tt}_fun\n"
10552                 "   %param0 = OpFunctionParameter %${tt}\n"
10553                 " %entry_pf = OpLabel\n"
10554                 "     %res0 = OpFAdd %${tt} %param0 %c_${tt}_0\n"
10555                 "             OpReturnValue %res0\n"
10556                 "             OpFunctionEnd\n"
10557         );
10558
10559         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
10560         {
10561                 const TestType&         testType                = testTypes[testTypeIdx];
10562                 const string            testName                = testType.typeName;
10563                 const deUint32          itemsPerType    = testType.typeComponents;
10564                 const size_t            iterations              = float16InputData.size() / itemsPerType;
10565                 const size_t            typeStride              = itemsPerType * sizeof(deFloat16);
10566                 SpecResource            specResource;
10567                 map<string, string>     specs;
10568                 VulkanFeatures          features;
10569                 vector<string>          extensions;
10570
10571                 specs["cap"]                            = "StorageUniformBufferBlock16";
10572                 specs["num_data_points"]        = de::toString(iterations);
10573                 specs["tt"]                                     = testType.typeName;
10574                 specs["tt_stride"]                      = de::toString(typeStride);
10575                 specs["type_decls"]                     = testType.typeDecls;
10576
10577                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10578                 fragments["capability"]         = capabilities.specialize(specs);
10579                 fragments["decoration"]         = decoration.specialize(specs);
10580                 fragments["pre_main"]           = preMain.specialize(specs);
10581                 fragments["testfun"]            = testFun.specialize(specs);
10582
10583                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10584                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10585                 specResource.verifyIO = compareFP16FunctionSetFunc;
10586
10587                 extensions.push_back("VK_KHR_16bit_storage");
10588                 extensions.push_back("VK_KHR_shader_float16_int8");
10589
10590                 features.ext16BitStorage = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10591                 features.extFloat16Int8 = EXTFLOAT16INT8FEATURES_FLOAT16;
10592
10593                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
10594         }
10595
10596         return testGroup.release();
10597 }
10598
10599 struct getV_    { deUint32 inline operator()(deUint32 v) const  { return v;        } getV_(){} };
10600 struct getV0    { deUint32 inline operator()(deUint32 v) const  { return v & (~1); } getV0(){} };
10601 struct getV1    { deUint32 inline operator()(deUint32 v) const  { return v | ( 1); } getV1(){} };
10602
10603 template<deUint32 R, deUint32 N>
10604 inline static deUint32 getOffset(deUint32 x, deUint32 y, deUint32 n)
10605 {
10606         return N * ((R * y) + x) + n;
10607 }
10608
10609 template<deUint32 R, deUint32 N, class X0, class X1, class Y0, class Y1>
10610 struct getFDelta
10611 {
10612         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10613         {
10614                 DE_STATIC_ASSERT(R%2 == 0);
10615                 DE_ASSERT(flavor == 0);
10616                 DE_UNREF(flavor);
10617
10618                 const X0                        x0;
10619                 const X1                        x1;
10620                 const Y0                        y0;
10621                 const Y1                        y1;
10622                 const deFloat16         v0      = data[getOffset<R, N>(x0(x), y0(y), n)];
10623                 const deFloat16         v1      = data[getOffset<R, N>(x1(x), y1(y), n)];
10624                 const tcu::Float16      f0      = tcu::Float16(v0);
10625                 const tcu::Float16      f1      = tcu::Float16(v1);
10626                 const float                     d0      = f0.asFloat();
10627                 const float                     d1      = f1.asFloat();
10628                 const float                     d       = d1 - d0;
10629
10630                 return d;
10631         }
10632
10633         getFDelta(){}
10634 };
10635
10636 template<deUint32 F, class Class0, class Class1>
10637 struct getFOneOf
10638 {
10639         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10640         {
10641                 DE_ASSERT(flavor < F);
10642
10643                 if (flavor == 0)
10644                 {
10645                         Class0 c;
10646
10647                         return c(data, x, y, n, flavor);
10648                 }
10649                 else
10650                 {
10651                         Class1 c;
10652
10653                         return c(data, x, y, n, flavor - 1);
10654                 }
10655         }
10656
10657         getFOneOf(){}
10658 };
10659
10660 template<class FineX0, class FineX1, class FineY0, class FineY1>
10661 struct calcWidthOf4
10662 {
10663         float operator() (const deFloat16* data, deUint32 x, deUint32 y, deUint32 n, deUint32 flavor) const
10664         {
10665                 DE_ASSERT(flavor < 4);
10666
10667                 const deUint32                                          flavorX = (flavor & 1) == 0 ? 0 : 1;
10668                 const deUint32                                          flavorY = (flavor & 2) == 0 ? 0 : 1;
10669                 const getFOneOf<2, FineX0, FineX1>      cx;
10670                 const getFOneOf<2, FineY0, FineY1>      cy;
10671                 float                                                           v               = 0;
10672
10673                 v += fabsf(cx(data, x, y, n, flavorX));
10674                 v += fabsf(cy(data, x, y, n, flavorY));
10675
10676                 return v;
10677         }
10678
10679         calcWidthOf4(){}
10680 };
10681
10682 template<deUint32 R, deUint32 N, class Derivative>
10683 bool compareDerivativeWithFlavor (const deFloat16* inputAsFP16, const deFloat16* outputAsFP16, deUint32 flavor, std::string& error)
10684 {
10685         const deUint32          numDataPointsByAxis     = R;
10686         const Derivative        derivativeFunc;
10687
10688         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10689         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10690         for (deUint32 n = 0; n < N; ++n)
10691         {
10692                 const float             expectedFloat   = derivativeFunc(inputAsFP16, x, y, n, flavor);
10693                 deFloat16               expected                = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_NEAREST_EVEN);
10694                 const deFloat16 output                  = outputAsFP16[getOffset<R, N>(x, y, n)];
10695
10696                 bool                    reportError             = !compare16BitFloat(expected, output, error);
10697
10698                 if (reportError)
10699                 {
10700                         expected        = deFloat32To16Round(expectedFloat, DE_ROUNDINGMODE_TO_ZERO);
10701                         reportError     = !compare16BitFloat(expected, output, error);
10702                 }
10703
10704                 if (reportError)
10705                 {
10706                         error = "subcase at " + de::toString(x) + "," + de::toString(y) + "," + de::toString(n) + ": " + error;
10707
10708                         return false;
10709                 }
10710         }
10711
10712         return true;
10713 }
10714
10715 template<deUint32 R, deUint32 N, deUint32 FLAVOUR_COUNT, class Derivative>
10716 bool compareDerivative (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10717 {
10718         if (inputs.size() != 1 || outputAllocs.size() != 1)
10719                 return false;
10720
10721         deUint32                        successfulRuns                  = FLAVOUR_COUNT;
10722         std::string                     results[FLAVOUR_COUNT];
10723         vector<deUint8>         inputBytes;
10724
10725         inputs[0].getBytes(inputBytes);
10726
10727         const deFloat16*        inputAsFP16             = reinterpret_cast<deFloat16* const>(&inputBytes.front());
10728         const deFloat16*        outputAsFP16    = static_cast<deFloat16*>(outputAllocs[0]->getHostPtr());
10729
10730         DE_ASSERT(inputBytes.size() ==  R * R * N * sizeof(deFloat16));
10731
10732         for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; ++flavor)
10733                 if (compareDerivativeWithFlavor<R, N, Derivative> (inputAsFP16, outputAsFP16, flavor, results[flavor]))
10734                 {
10735                         break;
10736                 }
10737                 else
10738                 {
10739                         successfulRuns--;
10740                 }
10741
10742         if (successfulRuns == 0)
10743                 for (deUint32 flavor = 0; flavor < FLAVOUR_COUNT; flavor++)
10744                         log << TestLog::Message << "At flavor #" << flavor << " " << results[flavor] << TestLog::EndMessage;
10745
10746         return successfulRuns > 0;
10747 }
10748
10749 template<deUint32 R, deUint32 N>
10750 tcu::TestCaseGroup* createDerivativeTests (tcu::TestContext& testCtx)
10751 {
10752         typedef getFDelta<R, N, getV0, getV1, getV_, getV_> getFDxFine;
10753         typedef getFDelta<R, N, getV_, getV_, getV0, getV1> getFDyFine;
10754
10755         typedef getFDelta<R, N, getV0, getV1, getV0, getV0> getFdxCoarse0;
10756         typedef getFDelta<R, N, getV0, getV1, getV1, getV1> getFdxCoarse1;
10757         typedef getFDelta<R, N, getV0, getV0, getV0, getV1> getFdyCoarse0;
10758         typedef getFDelta<R, N, getV1, getV1, getV0, getV1> getFdyCoarse1;
10759         typedef getFOneOf<2, getFdxCoarse0, getFdxCoarse1> getFDxCoarse;
10760         typedef getFOneOf<2, getFdyCoarse0, getFdyCoarse1> getFDyCoarse;
10761
10762         typedef calcWidthOf4<getFDxFine, getFDxFine, getFDyFine, getFDyFine> getFWidthFine;
10763         typedef calcWidthOf4<getFdxCoarse0, getFdxCoarse1, getFdyCoarse0, getFdyCoarse1> getFWidthCoarse;
10764
10765         typedef getFOneOf<3, getFDxFine, getFDxCoarse> getFDx;
10766         typedef getFOneOf<3, getFDyFine, getFDyCoarse> getFDy;
10767         typedef getFOneOf<5, getFWidthFine, getFWidthCoarse> getFWidth;
10768
10769         const std::string                                       testGroupName           (std::string("derivative_") + de::toString(N));
10770         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Derivative instruction tests"));
10771
10772         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
10773         const deUint32                                          numDataPointsByAxis     = R;
10774         const deUint32                                          numDataPoints           = N * numDataPointsByAxis * numDataPointsByAxis;
10775         vector<deFloat16>                                       float16InputX;
10776         vector<deFloat16>                                       float16InputY;
10777         vector<deFloat16>                                       float16InputW;
10778         vector<deFloat16>                                       float16OutputDummy      (numDataPoints, 0);
10779         RGBA                                                            defaultColors[4];
10780
10781         getDefaultColors(defaultColors);
10782
10783         float16InputX.reserve(numDataPoints);
10784         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10785         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10786         for (deUint32 n = 0; n < N; ++n)
10787         {
10788                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(x * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10789
10790                 if (y%2 == 0)
10791                         float16InputX.push_back(tcu::Float16(sin(arg)).bits());
10792                 else
10793                         float16InputX.push_back(tcu::Float16(cos(arg)).bits());
10794         }
10795
10796         float16InputY.reserve(numDataPoints);
10797         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10798         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10799         for (deUint32 n = 0; n < N; ++n)
10800         {
10801                 const float arg = static_cast<float>(2 * DE_PI) * static_cast<float>(y * (n + 1)) / static_cast<float>(1 * numDataPointsByAxis);
10802
10803                 if (x%2 == 0)
10804                         float16InputY.push_back(tcu::Float16(sin(arg)).bits());
10805                 else
10806                         float16InputY.push_back(tcu::Float16(cos(arg)).bits());
10807         }
10808
10809         const deFloat16 testNumbers[]   =
10810         {
10811                 tcu::Float16( 2.0  ).bits(),
10812                 tcu::Float16( 4.0  ).bits(),
10813                 tcu::Float16( 8.0  ).bits(),
10814                 tcu::Float16( 16.0 ).bits(),
10815                 tcu::Float16( 32.0 ).bits(),
10816                 tcu::Float16( 64.0 ).bits(),
10817                 tcu::Float16( 128.0).bits(),
10818                 tcu::Float16( 256.0).bits(),
10819                 tcu::Float16( 512.0).bits(),
10820                 tcu::Float16(-2.0  ).bits(),
10821                 tcu::Float16(-4.0  ).bits(),
10822                 tcu::Float16(-8.0  ).bits(),
10823                 tcu::Float16(-16.0 ).bits(),
10824                 tcu::Float16(-32.0 ).bits(),
10825                 tcu::Float16(-64.0 ).bits(),
10826                 tcu::Float16(-128.0).bits(),
10827                 tcu::Float16(-256.0).bits(),
10828                 tcu::Float16(-512.0).bits(),
10829         };
10830
10831         float16InputW.reserve(numDataPoints);
10832         for (deUint32 y = 0; y < numDataPointsByAxis; ++y)
10833         for (deUint32 x = 0; x < numDataPointsByAxis; ++x)
10834         for (deUint32 n = 0; n < N; ++n)
10835                 float16InputW.push_back(testNumbers[rnd.getInt(0, DE_LENGTH_OF_ARRAY(testNumbers) - 1)]);
10836
10837         struct TestOp
10838         {
10839                 const char*                     opCode;
10840                 vector<deFloat16>&      inputData;
10841                 VerifyIOFunc            verifyFunc;
10842         };
10843
10844         const TestOp    testOps[]       =
10845         {
10846                 { "OpDPdxFine"          ,       float16InputX   ,       compareDerivative<R, N, 1, getFDxFine           >       },
10847                 { "OpDPdyFine"          ,       float16InputY   ,       compareDerivative<R, N, 1, getFDyFine           >       },
10848                 { "OpFwidthFine"        ,       float16InputW   ,       compareDerivative<R, N, 1, getFWidthFine        >       },
10849                 { "OpDPdxCoarse"        ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10850                 { "OpDPdyCoarse"        ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10851                 { "OpFwidthCoarse"      ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10852                 { "OpDPdx"                      ,       float16InputX   ,       compareDerivative<R, N, 3, getFDx                       >       },
10853                 { "OpDPdy"                      ,       float16InputY   ,       compareDerivative<R, N, 3, getFDy                       >       },
10854                 { "OpFwidth"            ,       float16InputW   ,       compareDerivative<R, N, 5, getFWidth            >       },
10855         };
10856
10857         struct TestType
10858         {
10859                 const deUint32  typeComponents;
10860                 const char*             typeName;
10861                 const char*             typeDecls;
10862         };
10863
10864         const TestType  testTypes[]     =
10865         {
10866                 {
10867                         1,
10868                         "f16",
10869                         ""
10870                 },
10871                 {
10872                         2,
10873                         "v2f16",
10874                         "      %v2f16 = OpTypeVector %f16 2\n"
10875                 },
10876                 {
10877                         4,
10878                         "v4f16",
10879                         "      %v4f16 = OpTypeVector %f16 4\n"
10880                 },
10881         };
10882
10883         const deUint32  testTypeNdx     = (N == 1) ? 0
10884                                                                 : (N == 2) ? 1
10885                                                                 : (N == 4) ? 2
10886                                                                 : DE_LENGTH_OF_ARRAY(testTypes);
10887         const TestType& testType        =       testTypes[testTypeNdx];
10888
10889         DE_ASSERT(testTypeNdx < DE_LENGTH_OF_ARRAY(testTypes));
10890         DE_ASSERT(testType.typeComponents == N);
10891
10892         const StringTemplate preMain
10893         (
10894                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
10895                 " %c_u32_xw = OpConstant %u32 ${items_by_x}\n"
10896                 "      %f16 = OpTypeFloat 16\n"
10897                 "${type_decls}"
10898                 " %up_${tt} = OpTypePointer Uniform %${tt}\n"
10899                 " %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
10900                 "   %SSBO16 = OpTypeStruct %ra_${tt}\n"
10901                 "%up_SSBO16 = OpTypePointer Uniform %SSBO16\n"
10902                 " %ssbo_src = OpVariable %up_SSBO16 Uniform\n"
10903                 " %ssbo_dst = OpVariable %up_SSBO16 Uniform\n"
10904         );
10905
10906         const StringTemplate decoration
10907         (
10908                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
10909                 "OpMemberDecorate %SSBO16 0 Offset 0\n"
10910                 "OpDecorate %SSBO16 BufferBlock\n"
10911                 "OpDecorate %ssbo_src DescriptorSet 0\n"
10912                 "OpDecorate %ssbo_src Binding 0\n"
10913                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
10914                 "OpDecorate %ssbo_dst Binding 1\n"
10915         );
10916
10917         const StringTemplate testFun
10918         (
10919                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
10920                 "    %param = OpFunctionParameter %v4f32\n"
10921                 "    %entry = OpLabel\n"
10922
10923                 "  %loc_x_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_0\n"
10924                 "  %loc_y_c = OpAccessChain %ip_f32 %BP_gl_FragCoord %c_i32_1\n"
10925                 "      %x_c = OpLoad %f32 %loc_x_c\n"
10926                 "      %y_c = OpLoad %f32 %loc_y_c\n"
10927                 "    %x_idx = OpConvertFToU %u32 %x_c\n"
10928                 "    %y_idx = OpConvertFToU %u32 %y_c\n"
10929                 "    %ndx_y = OpIMul %u32 %y_idx %c_u32_xw\n"
10930                 "      %ndx = OpIAdd %u32 %ndx_y %x_idx\n"
10931
10932                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
10933                 "  %val_src = OpLoad %${tt} %src\n"
10934                 "  %val_dst = ${op_code} %${tt} %val_src\n"
10935                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
10936                 "             OpStore %dst %val_dst\n"
10937                 "             OpBranch %merge\n"
10938
10939                 "    %merge = OpLabel\n"
10940                 "             OpReturnValue %param\n"
10941
10942                 "             OpFunctionEnd\n"
10943         );
10944
10945         for (deUint32 testOpsIdx = 0; testOpsIdx < DE_LENGTH_OF_ARRAY(testOps); ++testOpsIdx)
10946         {
10947                 const TestOp&           testOp                  = testOps[testOpsIdx];
10948                 const string            testName                = de::toLower(string(testOp.opCode));
10949                 const size_t            typeStride              = N * sizeof(deFloat16);
10950                 GraphicsResources       specResource;
10951                 map<string, string>     specs;
10952                 VulkanFeatures          features;
10953                 vector<string>          extensions;
10954                 map<string, string>     fragments;
10955                 SpecConstants           noSpecConstants;
10956                 PushConstants           noPushConstants;
10957                 GraphicsInterfaces      noInterfaces;
10958
10959                 specs["op_code"]                        = testOp.opCode;
10960                 specs["num_data_points"]        = de::toString(testOp.inputData.size() / N);
10961                 specs["items_by_x"]                     = de::toString(numDataPointsByAxis);
10962                 specs["tt"]                                     = testType.typeName;
10963                 specs["tt_stride"]                      = de::toString(typeStride);
10964                 specs["type_decls"]                     = testType.typeDecls;
10965
10966                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
10967                 fragments["capability"]         = "OpCapability DerivativeControl\nOpCapability StorageUniformBufferBlock16\n";
10968                 fragments["decoration"]         = decoration.specialize(specs);
10969                 fragments["pre_main"]           = preMain.specialize(specs);
10970                 fragments["testfun"]            = testFun.specialize(specs);
10971
10972                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(testOp.inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10973                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
10974                 specResource.verifyIO = testOp.verifyFunc;
10975
10976                 extensions.push_back("VK_KHR_16bit_storage");
10977                 extensions.push_back("VK_KHR_shader_float16_int8");
10978
10979                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
10980                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
10981
10982                 createTestForStage(VK_SHADER_STAGE_FRAGMENT_BIT, testName.c_str(), defaultColors, defaultColors, fragments, noSpecConstants,
10983                                                         noPushConstants, specResource, noInterfaces, extensions, features, testGroup.get(), QP_TEST_RESULT_FAIL, string(), true);
10984         }
10985
10986         return testGroup.release();
10987 }
10988
10989 bool compareFP16VectorExtractFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
10990 {
10991         if (inputs.size() != 2 || outputAllocs.size() != 1)
10992                 return false;
10993
10994         vector<deUint8> input1Bytes;
10995         vector<deUint8> input2Bytes;
10996
10997         inputs[0].getBytes(input1Bytes);
10998         inputs[1].getBytes(input2Bytes);
10999
11000         DE_ASSERT(input1Bytes.size() > 0);
11001         DE_ASSERT(input2Bytes.size() > 0);
11002         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
11003
11004         const size_t                    iterations              = input2Bytes.size() / sizeof(deUint32);
11005         const size_t                    components              = input1Bytes.size() / (sizeof(deFloat16) * iterations);
11006         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
11007         const deUint32* const   inputIndices    = (const deUint32*)&input2Bytes[0];
11008         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11009         std::string                             error;
11010
11011         DE_ASSERT(components == 2 || components == 4);
11012         DE_ASSERT(input1Bytes.size() == iterations * components * sizeof(deFloat16));
11013
11014         for (size_t idx = 0; idx < iterations; ++idx)
11015         {
11016                 const deUint32  componentNdx    = inputIndices[idx];
11017
11018                 DE_ASSERT(componentNdx < components);
11019
11020                 const deFloat16 expected                = input1AsFP16[components * idx + componentNdx];
11021
11022                 if (!compare16BitFloat(expected, outputAsFP16[idx], error))
11023                 {
11024                         log << TestLog::Message << "At " << idx << error << TestLog::EndMessage;
11025
11026                         return false;
11027                 }
11028         }
11029
11030         return true;
11031 }
11032
11033 template<class SpecResource>
11034 tcu::TestCaseGroup* createFloat16VectorExtractSet (tcu::TestContext& testCtx)
11035 {
11036         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorextractdynamic", "OpVectorExtractDynamic tests"));
11037
11038         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
11039         const deUint32                                          numDataPoints           = 256;
11040         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
11041         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
11042
11043         struct TestType
11044         {
11045                 const deUint32  typeComponents;
11046                 const size_t    typeStride;
11047                 const char*             typeName;
11048                 const char*             typeDecls;
11049         };
11050
11051         const TestType  testTypes[]     =
11052         {
11053                 {
11054                         2,
11055                         2 * sizeof(deFloat16),
11056                         "v2f16",
11057                         "      %v2f16 = OpTypeVector %f16 2\n"
11058                 },
11059                 {
11060                         3,
11061                         4 * sizeof(deFloat16),
11062                         "v3f16",
11063                         "      %v3f16 = OpTypeVector %f16 3\n"
11064                 },
11065                 {
11066                         4,
11067                         4 * sizeof(deFloat16),
11068                         "v4f16",
11069                         "      %v4f16 = OpTypeVector %f16 4\n"
11070                 },
11071         };
11072
11073         const StringTemplate preMain
11074         (
11075                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11076                 "        %f16 = OpTypeFloat 16\n"
11077
11078                 "${type_decl}"
11079
11080                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
11081                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
11082                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
11083                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
11084
11085                 "     %up_u32 = OpTypePointer Uniform %u32\n"
11086                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
11087                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
11088                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
11089
11090                 "     %up_f16 = OpTypePointer Uniform %f16\n"
11091                 "     %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
11092                 "   %SSBO_DST = OpTypeStruct %ra_f16\n"
11093                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
11094
11095                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
11096                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
11097                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
11098         );
11099
11100         const StringTemplate decoration
11101         (
11102                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
11103                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
11104                 "OpDecorate %SSBO_SRC BufferBlock\n"
11105                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11106                 "OpDecorate %ssbo_src Binding 0\n"
11107
11108                 "OpDecorate %ra_u32 ArrayStride 4\n"
11109                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
11110                 "OpDecorate %SSBO_IDX BufferBlock\n"
11111                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
11112                 "OpDecorate %ssbo_idx Binding 1\n"
11113
11114                 "OpDecorate %ra_f16 ArrayStride 2\n"
11115                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
11116                 "OpDecorate %SSBO_DST BufferBlock\n"
11117                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11118                 "OpDecorate %ssbo_dst Binding 2\n"
11119         );
11120
11121         const StringTemplate testFun
11122         (
11123                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11124                 "    %param = OpFunctionParameter %v4f32\n"
11125                 "    %entry = OpLabel\n"
11126
11127                 "        %i = OpVariable %fp_i32 Function\n"
11128                 "             OpStore %i %c_i32_0\n"
11129
11130                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11131                 "             OpSelectionMerge %end_if None\n"
11132                 "             OpBranchConditional %will_run %run_test %end_if\n"
11133
11134                 " %run_test = OpLabel\n"
11135                 "             OpBranch %loop\n"
11136
11137                 "     %loop = OpLabel\n"
11138                 "    %i_cmp = OpLoad %i32 %i\n"
11139                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11140                 "             OpLoopMerge %merge %next None\n"
11141                 "             OpBranchConditional %lt %write %merge\n"
11142
11143                 "    %write = OpLabel\n"
11144                 "      %ndx = OpLoad %i32 %i\n"
11145
11146                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
11147                 "  %val_src = OpLoad %${tt} %src\n"
11148
11149                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
11150                 "  %val_idx = OpLoad %u32 %src_idx\n"
11151
11152                 "  %val_dst = OpVectorExtractDynamic %f16 %val_src %val_idx\n"
11153                 "      %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
11154
11155                 "             OpStore %dst %val_dst\n"
11156                 "             OpBranch %next\n"
11157
11158                 "     %next = OpLabel\n"
11159                 "    %i_cur = OpLoad %i32 %i\n"
11160                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11161                 "             OpStore %i %i_new\n"
11162                 "             OpBranch %loop\n"
11163
11164                 "    %merge = OpLabel\n"
11165                 "             OpBranch %end_if\n"
11166                 "   %end_if = OpLabel\n"
11167                 "             OpReturnValue %param\n"
11168
11169                 "             OpFunctionEnd\n"
11170         );
11171
11172         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
11173         {
11174                 const TestType&         testType                = testTypes[testTypeIdx];
11175                 const string            testName                = testType.typeName;
11176                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
11177                 const size_t            iterations              = float16InputData.size() / itemsPerType;
11178                 SpecResource            specResource;
11179                 map<string, string>     specs;
11180                 VulkanFeatures          features;
11181                 vector<deUint32>        inputDataNdx;
11182                 map<string, string>     fragments;
11183                 vector<string>          extensions;
11184
11185                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
11186                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
11187
11188                 specs["num_data_points"]        = de::toString(iterations);
11189                 specs["tt"]                                     = testType.typeName;
11190                 specs["tt_stride"]                      = de::toString(testType.typeStride);
11191                 specs["type_decl"]                      = testType.typeDecls;
11192
11193                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11194                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11195                 fragments["decoration"]         = decoration.specialize(specs);
11196                 fragments["pre_main"]           = preMain.specialize(specs);
11197                 fragments["testfun"]            = testFun.specialize(specs);
11198
11199                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11200                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11201                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11202                 specResource.verifyIO = compareFP16VectorExtractFunc;
11203
11204                 extensions.push_back("VK_KHR_16bit_storage");
11205                 extensions.push_back("VK_KHR_shader_float16_int8");
11206
11207                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11208                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11209
11210                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11211         }
11212
11213         return testGroup.release();
11214 }
11215
11216 template<deUint32 COMPONENTS_COUNT, deUint32 REPLACEMENT>
11217 bool compareFP16VectorInsertFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11218 {
11219         if (inputs.size() != 2 || outputAllocs.size() != 1)
11220                 return false;
11221
11222         vector<deUint8> input1Bytes;
11223         vector<deUint8> input2Bytes;
11224
11225         inputs[0].getBytes(input1Bytes);
11226         inputs[1].getBytes(input2Bytes);
11227
11228         DE_ASSERT(input1Bytes.size() > 0);
11229         DE_ASSERT(input2Bytes.size() > 0);
11230         DE_ASSERT(input2Bytes.size() % sizeof(deUint32) == 0);
11231
11232         const size_t                    iterations                      = input2Bytes.size() / sizeof(deUint32);
11233         const size_t                    componentsStride        = input1Bytes.size() / (sizeof(deFloat16) * iterations);
11234         const deFloat16* const  input1AsFP16            = (const deFloat16*)&input1Bytes[0];
11235         const deUint32* const   inputIndices            = (const deUint32*)&input2Bytes[0];
11236         const deFloat16* const  outputAsFP16            = (const deFloat16*)outputAllocs[0]->getHostPtr();
11237         const deFloat16                 magic                           = tcu::Float16(float(REPLACEMENT)).bits();
11238         std::string                             error;
11239
11240         DE_ASSERT(componentsStride == 2 || componentsStride == 4);
11241         DE_ASSERT(input1Bytes.size() == iterations * componentsStride * sizeof(deFloat16));
11242
11243         for (size_t idx = 0; idx < iterations; ++idx)
11244         {
11245                 const deFloat16*        inputVec                = &input1AsFP16[componentsStride * idx];
11246                 const deFloat16*        outputVec               = &outputAsFP16[componentsStride * idx];
11247                 const deUint32          replacedCompNdx = inputIndices[idx];
11248
11249                 DE_ASSERT(replacedCompNdx < COMPONENTS_COUNT);
11250
11251                 for (size_t compNdx = 0; compNdx < COMPONENTS_COUNT; ++compNdx)
11252                 {
11253                         const deFloat16 expected        = (compNdx == replacedCompNdx) ? magic : inputVec[compNdx];
11254
11255                         if (!compare16BitFloat(expected, outputVec[compNdx], error))
11256                         {
11257                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11258
11259                                 return false;
11260                         }
11261                 }
11262         }
11263
11264         return true;
11265 }
11266
11267 template<class SpecResource>
11268 tcu::TestCaseGroup* createFloat16VectorInsertSet (tcu::TestContext& testCtx)
11269 {
11270         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorinsertdynamic", "OpVectorInsertDynamic tests"));
11271
11272         de::Random                                                      rnd                                     (deStringHash(testGroup->getName()));
11273         const deUint32                                          replacement                     = 42;
11274         const deUint32                                          numDataPoints           = 256;
11275         const vector<deFloat16>                         float16InputData        = getFloat16s(rnd, numDataPoints);
11276         const vector<deFloat16>                         float16OutputDummy      (float16InputData.size(), 0);
11277
11278         struct TestType
11279         {
11280                 const deUint32  typeComponents;
11281                 const size_t    typeStride;
11282                 const char*             typeName;
11283                 const char*             typeDecls;
11284                 VerifyIOFunc    verifyIOFunc;
11285         };
11286
11287         const TestType  testTypes[]     =
11288         {
11289                 {
11290                         2,
11291                         2 * sizeof(deFloat16),
11292                         "v2f16",
11293                         "      %v2f16 = OpTypeVector %f16 2\n",
11294                         compareFP16VectorInsertFunc<2, replacement>
11295                 },
11296                 {
11297                         3,
11298                         4 * sizeof(deFloat16),
11299                         "v3f16",
11300                         "      %v3f16 = OpTypeVector %f16 3\n",
11301                         compareFP16VectorInsertFunc<3, replacement>
11302                 },
11303                 {
11304                         4,
11305                         4 * sizeof(deFloat16),
11306                         "v4f16",
11307                         "      %v4f16 = OpTypeVector %f16 4\n",
11308                         compareFP16VectorInsertFunc<4, replacement>
11309                 },
11310         };
11311
11312         const StringTemplate preMain
11313         (
11314                 "  %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11315                 "        %f16 = OpTypeFloat 16\n"
11316                 "  %c_f16_ins = OpConstant %f16 ${replacement}\n"
11317
11318                 "${type_decl}"
11319
11320                 "   %up_${tt} = OpTypePointer Uniform %${tt}\n"
11321                 "   %ra_${tt} = OpTypeArray %${tt} %c_i32_ndp\n"
11322                 "   %SSBO_SRC = OpTypeStruct %ra_${tt}\n"
11323                 "%up_SSBO_SRC = OpTypePointer Uniform %SSBO_SRC\n"
11324
11325                 "     %up_u32 = OpTypePointer Uniform %u32\n"
11326                 "     %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
11327                 "   %SSBO_IDX = OpTypeStruct %ra_u32\n"
11328                 "%up_SSBO_IDX = OpTypePointer Uniform %SSBO_IDX\n"
11329
11330                 "   %SSBO_DST = OpTypeStruct %ra_${tt}\n"
11331                 "%up_SSBO_DST = OpTypePointer Uniform %SSBO_DST\n"
11332
11333                 "   %ssbo_src = OpVariable %up_SSBO_SRC Uniform\n"
11334                 "   %ssbo_idx = OpVariable %up_SSBO_IDX Uniform\n"
11335                 "   %ssbo_dst = OpVariable %up_SSBO_DST Uniform\n"
11336         );
11337
11338         const StringTemplate decoration
11339         (
11340                 "OpDecorate %ra_${tt} ArrayStride ${tt_stride}\n"
11341                 "OpMemberDecorate %SSBO_SRC 0 Offset 0\n"
11342                 "OpDecorate %SSBO_SRC BufferBlock\n"
11343                 "OpDecorate %ssbo_src DescriptorSet 0\n"
11344                 "OpDecorate %ssbo_src Binding 0\n"
11345
11346                 "OpDecorate %ra_u32 ArrayStride 4\n"
11347                 "OpMemberDecorate %SSBO_IDX 0 Offset 0\n"
11348                 "OpDecorate %SSBO_IDX BufferBlock\n"
11349                 "OpDecorate %ssbo_idx DescriptorSet 0\n"
11350                 "OpDecorate %ssbo_idx Binding 1\n"
11351
11352                 "OpMemberDecorate %SSBO_DST 0 Offset 0\n"
11353                 "OpDecorate %SSBO_DST BufferBlock\n"
11354                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11355                 "OpDecorate %ssbo_dst Binding 2\n"
11356         );
11357
11358         const StringTemplate testFun
11359         (
11360                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11361                 "    %param = OpFunctionParameter %v4f32\n"
11362                 "    %entry = OpLabel\n"
11363
11364                 "        %i = OpVariable %fp_i32 Function\n"
11365                 "             OpStore %i %c_i32_0\n"
11366
11367                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11368                 "             OpSelectionMerge %end_if None\n"
11369                 "             OpBranchConditional %will_run %run_test %end_if\n"
11370
11371                 " %run_test = OpLabel\n"
11372                 "             OpBranch %loop\n"
11373
11374                 "     %loop = OpLabel\n"
11375                 "    %i_cmp = OpLoad %i32 %i\n"
11376                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11377                 "             OpLoopMerge %merge %next None\n"
11378                 "             OpBranchConditional %lt %write %merge\n"
11379
11380                 "    %write = OpLabel\n"
11381                 "      %ndx = OpLoad %i32 %i\n"
11382
11383                 "      %src = OpAccessChain %up_${tt} %ssbo_src %c_i32_0 %ndx\n"
11384                 "  %val_src = OpLoad %${tt} %src\n"
11385
11386                 "  %src_idx = OpAccessChain %up_u32 %ssbo_idx %c_i32_0 %ndx\n"
11387                 "  %val_idx = OpLoad %u32 %src_idx\n"
11388
11389                 "  %val_dst = OpVectorInsertDynamic %${tt} %val_src %c_f16_ins %val_idx\n"
11390                 "      %dst = OpAccessChain %up_${tt} %ssbo_dst %c_i32_0 %ndx\n"
11391
11392                 "             OpStore %dst %val_dst\n"
11393                 "             OpBranch %next\n"
11394
11395                 "     %next = OpLabel\n"
11396                 "    %i_cur = OpLoad %i32 %i\n"
11397                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11398                 "             OpStore %i %i_new\n"
11399                 "             OpBranch %loop\n"
11400
11401                 "    %merge = OpLabel\n"
11402                 "             OpBranch %end_if\n"
11403                 "   %end_if = OpLabel\n"
11404                 "             OpReturnValue %param\n"
11405
11406                 "             OpFunctionEnd\n"
11407         );
11408
11409         for (deUint32 testTypeIdx = 0; testTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++testTypeIdx)
11410         {
11411                 const TestType&         testType                = testTypes[testTypeIdx];
11412                 const string            testName                = testType.typeName;
11413                 const size_t            itemsPerType    = testType.typeStride / sizeof(deFloat16);
11414                 const size_t            iterations              = float16InputData.size() / itemsPerType;
11415                 SpecResource            specResource;
11416                 map<string, string>     specs;
11417                 VulkanFeatures          features;
11418                 vector<deUint32>        inputDataNdx;
11419                 map<string, string>     fragments;
11420                 vector<string>          extensions;
11421
11422                 for (deUint32 ndx = 0; ndx < iterations; ++ndx)
11423                         inputDataNdx.push_back(rnd.getUint32() % testType.typeComponents);
11424
11425                 specs["num_data_points"]        = de::toString(iterations);
11426                 specs["tt"]                                     = testType.typeName;
11427                 specs["tt_stride"]                      = de::toString(testType.typeStride);
11428                 specs["type_decl"]                      = testType.typeDecls;
11429                 specs["replacement"]            = de::toString(replacement);
11430
11431                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11432                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11433                 fragments["decoration"]         = decoration.specialize(specs);
11434                 fragments["pre_main"]           = preMain.specialize(specs);
11435                 fragments["testfun"]            = testFun.specialize(specs);
11436
11437                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16InputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11438                 specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inputDataNdx)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11439                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11440                 specResource.verifyIO = testType.verifyIOFunc;
11441
11442                 extensions.push_back("VK_KHR_16bit_storage");
11443                 extensions.push_back("VK_KHR_shader_float16_int8");
11444
11445                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11446                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11447
11448                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11449         }
11450
11451         return testGroup.release();
11452 }
11453
11454 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)
11455 {
11456         const size_t    compNdxCount    = (vec1Len + vec2Len + 1);
11457         const size_t    compNdxLimited  = iteration % (compNdxCount * compNdxCount);
11458         size_t                  comp;
11459
11460         switch (componentNdx)
11461         {
11462                 case 0: comp = compNdxLimited / compNdxCount; break;
11463                 case 1: comp = compNdxLimited % compNdxCount; break;
11464                 case 2: comp = 0; break;
11465                 case 3: comp = 1; break;
11466                 default: TCU_THROW(InternalError, "Impossible");
11467         }
11468
11469         if (comp >= vec1Len + vec2Len)
11470         {
11471                 validate = false;
11472                 return 0;
11473         }
11474         else
11475         {
11476                 validate = true;
11477                 return (comp < vec1Len) ? input1Vec[comp] : input2Vec[comp - vec1Len];
11478         }
11479 }
11480
11481 template<deUint32 DST_COMPONENTS_COUNT, deUint32 SRC0_COMPONENTS_COUNT, deUint32 SRC1_COMPONENTS_COUNT>
11482 bool compareFP16VectorShuffleFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11483 {
11484         DE_STATIC_ASSERT(DST_COMPONENTS_COUNT == 2 || DST_COMPONENTS_COUNT == 3 || DST_COMPONENTS_COUNT == 4);
11485         DE_STATIC_ASSERT(SRC0_COMPONENTS_COUNT == 2 || SRC0_COMPONENTS_COUNT == 3 || SRC0_COMPONENTS_COUNT == 4);
11486         DE_STATIC_ASSERT(SRC1_COMPONENTS_COUNT == 2 || SRC1_COMPONENTS_COUNT == 3 || SRC1_COMPONENTS_COUNT == 4);
11487
11488         if (inputs.size() != 2 || outputAllocs.size() != 1)
11489                 return false;
11490
11491         vector<deUint8> input1Bytes;
11492         vector<deUint8> input2Bytes;
11493
11494         inputs[0].getBytes(input1Bytes);
11495         inputs[1].getBytes(input2Bytes);
11496
11497         DE_ASSERT(input1Bytes.size() > 0);
11498         DE_ASSERT(input2Bytes.size() > 0);
11499         DE_ASSERT(input2Bytes.size() % sizeof(deFloat16) == 0);
11500
11501         const size_t                    componentsStrideDst             = (DST_COMPONENTS_COUNT == 3) ? 4 : DST_COMPONENTS_COUNT;
11502         const size_t                    componentsStrideSrc0    = (SRC0_COMPONENTS_COUNT == 3) ? 4 : SRC0_COMPONENTS_COUNT;
11503         const size_t                    componentsStrideSrc1    = (SRC1_COMPONENTS_COUNT == 3) ? 4 : SRC1_COMPONENTS_COUNT;
11504         const size_t                    iterations                              = input1Bytes.size() / (componentsStrideSrc0 * sizeof(deFloat16));
11505         const deFloat16* const  input1AsFP16                    = (const deFloat16*)&input1Bytes[0];
11506         const deFloat16* const  input2AsFP16                    = (const deFloat16*)&input2Bytes[0];
11507         const deFloat16* const  outputAsFP16                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11508         std::string                             error;
11509
11510         DE_ASSERT(input1Bytes.size() == iterations * componentsStrideSrc0 * sizeof(deFloat16));
11511         DE_ASSERT(input2Bytes.size() == iterations * componentsStrideSrc1 * sizeof(deFloat16));
11512
11513         for (size_t idx = 0; idx < iterations; ++idx)
11514         {
11515                 const deFloat16*        input1Vec       = &input1AsFP16[componentsStrideSrc0 * idx];
11516                 const deFloat16*        input2Vec       = &input2AsFP16[componentsStrideSrc1 * idx];
11517                 const deFloat16*        outputVec       = &outputAsFP16[componentsStrideDst * idx];
11518
11519                 for (size_t compNdx = 0; compNdx < DST_COMPONENTS_COUNT; ++compNdx)
11520                 {
11521                         bool            validate        = true;
11522                         deFloat16       expected        = getShuffledComponent(idx, compNdx, input1Vec, input2Vec, SRC0_COMPONENTS_COUNT, SRC1_COMPONENTS_COUNT, validate);
11523
11524                         if (validate && !compare16BitFloat(expected, outputVec[compNdx], error))
11525                         {
11526                                 log << TestLog::Message << "At " << idx << "[" << compNdx << "]: " << error << TestLog::EndMessage;
11527
11528                                 return false;
11529                         }
11530                 }
11531         }
11532
11533         return true;
11534 }
11535
11536 VerifyIOFunc getFloat16VectorShuffleVerifyIOFunc (deUint32 dstComponentsCount, deUint32 src0ComponentsCount, deUint32 src1ComponentsCount)
11537 {
11538         DE_ASSERT(dstComponentsCount <= 4);
11539         DE_ASSERT(src0ComponentsCount <= 4);
11540         DE_ASSERT(src1ComponentsCount <= 4);
11541         deUint32 funcCode = 100 * dstComponentsCount + 10 * src0ComponentsCount + src1ComponentsCount;
11542
11543         switch (funcCode)
11544         {
11545                 case 222:return compareFP16VectorShuffleFunc<2, 2, 2>;
11546                 case 223:return compareFP16VectorShuffleFunc<2, 2, 3>;
11547                 case 224:return compareFP16VectorShuffleFunc<2, 2, 4>;
11548                 case 232:return compareFP16VectorShuffleFunc<2, 3, 2>;
11549                 case 233:return compareFP16VectorShuffleFunc<2, 3, 3>;
11550                 case 234:return compareFP16VectorShuffleFunc<2, 3, 4>;
11551                 case 242:return compareFP16VectorShuffleFunc<2, 4, 2>;
11552                 case 243:return compareFP16VectorShuffleFunc<2, 4, 3>;
11553                 case 244:return compareFP16VectorShuffleFunc<2, 4, 4>;
11554                 case 322:return compareFP16VectorShuffleFunc<3, 2, 2>;
11555                 case 323:return compareFP16VectorShuffleFunc<3, 2, 3>;
11556                 case 324:return compareFP16VectorShuffleFunc<3, 2, 4>;
11557                 case 332:return compareFP16VectorShuffleFunc<3, 3, 2>;
11558                 case 333:return compareFP16VectorShuffleFunc<3, 3, 3>;
11559                 case 334:return compareFP16VectorShuffleFunc<3, 3, 4>;
11560                 case 342:return compareFP16VectorShuffleFunc<3, 4, 2>;
11561                 case 343:return compareFP16VectorShuffleFunc<3, 4, 3>;
11562                 case 344:return compareFP16VectorShuffleFunc<3, 4, 4>;
11563                 case 422:return compareFP16VectorShuffleFunc<4, 2, 2>;
11564                 case 423:return compareFP16VectorShuffleFunc<4, 2, 3>;
11565                 case 424:return compareFP16VectorShuffleFunc<4, 2, 4>;
11566                 case 432:return compareFP16VectorShuffleFunc<4, 3, 2>;
11567                 case 433:return compareFP16VectorShuffleFunc<4, 3, 3>;
11568                 case 434:return compareFP16VectorShuffleFunc<4, 3, 4>;
11569                 case 442:return compareFP16VectorShuffleFunc<4, 4, 2>;
11570                 case 443:return compareFP16VectorShuffleFunc<4, 4, 3>;
11571                 case 444:return compareFP16VectorShuffleFunc<4, 4, 4>;
11572                 default: TCU_THROW(InternalError, "Invalid number of components specified.");
11573         }
11574 }
11575
11576 template<class SpecResource>
11577 tcu::TestCaseGroup* createFloat16VectorShuffleSet (tcu::TestContext& testCtx)
11578 {
11579         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "opvectorshuffle", "OpVectorShuffle tests"));
11580         const int                                                       testSpecificSeed        = deStringHash(testGroup->getName());
11581         const int                                                       seed                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
11582         de::Random                                                      rnd                                     (seed);
11583         const deUint32                                          numDataPoints           = 128;
11584         map<string, string>                                     fragments;
11585
11586         struct TestType
11587         {
11588                 const deUint32  typeComponents;
11589                 const char*             typeName;
11590         };
11591
11592         const TestType  testTypes[]     =
11593         {
11594                 {
11595                         2,
11596                         "v2f16",
11597                 },
11598                 {
11599                         3,
11600                         "v3f16",
11601                 },
11602                 {
11603                         4,
11604                         "v4f16",
11605                 },
11606         };
11607
11608         const StringTemplate preMain
11609         (
11610                 "    %c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
11611                 "     %c_i32_cc = OpConstant %i32 ${case_count}\n"
11612                 "          %f16 = OpTypeFloat 16\n"
11613                 "        %v2f16 = OpTypeVector %f16 2\n"
11614                 "        %v3f16 = OpTypeVector %f16 3\n"
11615                 "        %v4f16 = OpTypeVector %f16 4\n"
11616
11617                 "     %up_v2f16 = OpTypePointer Uniform %v2f16\n"
11618                 "     %ra_v2f16 = OpTypeArray %v2f16 %c_i32_ndp\n"
11619                 "   %SSBO_v2f16 = OpTypeStruct %ra_v2f16\n"
11620                 "%up_SSBO_v2f16 = OpTypePointer Uniform %SSBO_v2f16\n"
11621
11622                 "     %up_v3f16 = OpTypePointer Uniform %v3f16\n"
11623                 "     %ra_v3f16 = OpTypeArray %v3f16 %c_i32_ndp\n"
11624                 "   %SSBO_v3f16 = OpTypeStruct %ra_v3f16\n"
11625                 "%up_SSBO_v3f16 = OpTypePointer Uniform %SSBO_v3f16\n"
11626
11627                 "     %up_v4f16 = OpTypePointer Uniform %v4f16\n"
11628                 "     %ra_v4f16 = OpTypeArray %v4f16 %c_i32_ndp\n"
11629                 "   %SSBO_v4f16 = OpTypeStruct %ra_v4f16\n"
11630                 "%up_SSBO_v4f16 = OpTypePointer Uniform %SSBO_v4f16\n"
11631
11632                 "        %fun_t = OpTypeFunction %${tt_dst} %${tt_src0} %${tt_src1} %i32\n"
11633
11634                 "    %ssbo_src0 = OpVariable %up_SSBO_${tt_src0} Uniform\n"
11635                 "    %ssbo_src1 = OpVariable %up_SSBO_${tt_src1} Uniform\n"
11636                 "     %ssbo_dst = OpVariable %up_SSBO_${tt_dst} Uniform\n"
11637         );
11638
11639         const StringTemplate decoration
11640         (
11641                 "OpDecorate %ra_v2f16 ArrayStride 4\n"
11642                 "OpDecorate %ra_v3f16 ArrayStride 8\n"
11643                 "OpDecorate %ra_v4f16 ArrayStride 8\n"
11644
11645                 "OpMemberDecorate %SSBO_v2f16 0 Offset 0\n"
11646                 "OpDecorate %SSBO_v2f16 BufferBlock\n"
11647
11648                 "OpMemberDecorate %SSBO_v3f16 0 Offset 0\n"
11649                 "OpDecorate %SSBO_v3f16 BufferBlock\n"
11650
11651                 "OpMemberDecorate %SSBO_v4f16 0 Offset 0\n"
11652                 "OpDecorate %SSBO_v4f16 BufferBlock\n"
11653
11654                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
11655                 "OpDecorate %ssbo_src0 Binding 0\n"
11656                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
11657                 "OpDecorate %ssbo_src1 Binding 1\n"
11658                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11659                 "OpDecorate %ssbo_dst Binding 2\n"
11660         );
11661
11662         const StringTemplate testFun
11663         (
11664                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11665                 "    %param = OpFunctionParameter %v4f32\n"
11666                 "    %entry = OpLabel\n"
11667
11668                 "        %i = OpVariable %fp_i32 Function\n"
11669                 "             OpStore %i %c_i32_0\n"
11670
11671                 " %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11672                 "             OpSelectionMerge %end_if None\n"
11673                 "             OpBranchConditional %will_run %run_test %end_if\n"
11674
11675                 " %run_test = OpLabel\n"
11676                 "             OpBranch %loop\n"
11677
11678                 "     %loop = OpLabel\n"
11679                 "    %i_cmp = OpLoad %i32 %i\n"
11680                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11681                 "             OpLoopMerge %merge %next None\n"
11682                 "             OpBranchConditional %lt %write %merge\n"
11683
11684                 "    %write = OpLabel\n"
11685                 "      %ndx = OpLoad %i32 %i\n"
11686                 "     %src0 = OpAccessChain %up_${tt_src0} %ssbo_src0 %c_i32_0 %ndx\n"
11687                 " %val_src0 = OpLoad %${tt_src0} %src0\n"
11688                 "     %src1 = OpAccessChain %up_${tt_src1} %ssbo_src1 %c_i32_0 %ndx\n"
11689                 " %val_src1 = OpLoad %${tt_src1} %src1\n"
11690                 "  %val_dst = OpFunctionCall %${tt_dst} %sw_fun %val_src0 %val_src1 %ndx\n"
11691                 "      %dst = OpAccessChain %up_${tt_dst} %ssbo_dst %c_i32_0 %ndx\n"
11692                 "             OpStore %dst %val_dst\n"
11693                 "             OpBranch %next\n"
11694
11695                 "     %next = OpLabel\n"
11696                 "    %i_cur = OpLoad %i32 %i\n"
11697                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
11698                 "             OpStore %i %i_new\n"
11699                 "             OpBranch %loop\n"
11700
11701                 "    %merge = OpLabel\n"
11702                 "             OpBranch %end_if\n"
11703                 "   %end_if = OpLabel\n"
11704                 "             OpReturnValue %param\n"
11705                 "             OpFunctionEnd\n"
11706                 "\n"
11707
11708                 "   %sw_fun = OpFunction %${tt_dst} None %fun_t\n"
11709                 "%sw_param0 = OpFunctionParameter %${tt_src0}\n"
11710                 "%sw_param1 = OpFunctionParameter %${tt_src1}\n"
11711                 "%sw_paramn = OpFunctionParameter %i32\n"
11712                 " %sw_entry = OpLabel\n"
11713                 "   %modulo = OpSMod %i32 %sw_paramn %c_i32_cc\n"
11714                 "             OpSelectionMerge %switch_e None\n"
11715                 "             OpSwitch %modulo %default ${case_list}\n"
11716                 "${case_bodies}"
11717                 "%default   = OpLabel\n"
11718                 "             OpUnreachable\n" // Unreachable default case for switch statement
11719                 "%switch_e  = OpLabel\n"
11720                 "             OpUnreachable\n" // Unreachable merge block for switch statement
11721                 "             OpFunctionEnd\n"
11722         );
11723
11724         const StringTemplate testCaseBody
11725         (
11726                 "%case_${case_ndx}    = OpLabel\n"
11727                 "%val_dst_${case_ndx} = OpVectorShuffle %${tt_dst} %sw_param0 %sw_param1 ${shuffle}\n"
11728                 "             OpReturnValue %val_dst_${case_ndx}\n"
11729         );
11730
11731         for (deUint32 dstTypeIdx = 0; dstTypeIdx < DE_LENGTH_OF_ARRAY(testTypes); ++dstTypeIdx)
11732         {
11733                 const TestType& dstType                 = testTypes[dstTypeIdx];
11734
11735                 for (deUint32 comp0Idx = 0; comp0Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp0Idx)
11736                 {
11737                         const TestType& src0Type        = testTypes[comp0Idx];
11738
11739                         for (deUint32 comp1Idx = 0; comp1Idx < DE_LENGTH_OF_ARRAY(testTypes); ++comp1Idx)
11740                         {
11741                                 const TestType&                 src1Type                        = testTypes[comp1Idx];
11742                                 const deUint32                  input0Stride            = (src0Type.typeComponents == 3) ? 4 : src0Type.typeComponents;
11743                                 const deUint32                  input1Stride            = (src1Type.typeComponents == 3) ? 4 : src1Type.typeComponents;
11744                                 const deUint32                  outputStride            = (dstType.typeComponents == 3) ? 4 : dstType.typeComponents;
11745                                 const vector<deFloat16> float16Input0Data       = getFloat16s(rnd, input0Stride * numDataPoints);
11746                                 const vector<deFloat16> float16Input1Data       = getFloat16s(rnd, input1Stride * numDataPoints);
11747                                 const vector<deFloat16> float16OutputDummy      (outputStride * numDataPoints, 0);
11748                                 const string                    testName                        = de::toString(dstType.typeComponents) + de::toString(src0Type.typeComponents) + de::toString(src1Type.typeComponents);
11749                                 deUint32                                caseCount                       = 0;
11750                                 SpecResource                    specResource;
11751                                 map<string, string>             specs;
11752                                 vector<string>                  extensions;
11753                                 VulkanFeatures                  features;
11754                                 string                                  caseBodies;
11755                                 string                                  caseList;
11756
11757                                 // Generate case
11758                                 {
11759                                         vector<string>  componentList;
11760
11761                                         // Generate component possible indices for OpVectorShuffle for components 0 and 1 in output vector
11762                                         {
11763                                                 deUint32                caseNo          = 0;
11764
11765                                                 for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < src0Type.typeComponents; ++comp0IdxLocal)
11766                                                         componentList.push_back(de::toString(caseNo++));
11767                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < src1Type.typeComponents; ++comp1IdxLocal)
11768                                                         componentList.push_back(de::toString(caseNo++));
11769                                                 componentList.push_back("0xFFFFFFFF");
11770                                         }
11771
11772                                         for (deUint32 comp0IdxLocal = 0; comp0IdxLocal < componentList.size(); ++comp0IdxLocal)
11773                                         {
11774                                                 for (deUint32 comp1IdxLocal = 0; comp1IdxLocal < componentList.size(); ++comp1IdxLocal)
11775                                                 {
11776                                                         map<string, string>     specCase;
11777                                                         string                          shuffle         = componentList[comp0IdxLocal] + " " + componentList[comp1IdxLocal];
11778
11779                                                         for (deUint32 compIdx = 2; compIdx < dstType.typeComponents; ++compIdx)
11780                                                                 shuffle += " " + de::toString(compIdx - 2);
11781
11782                                                         specCase["case_ndx"]    = de::toString(caseCount);
11783                                                         specCase["shuffle"]             = shuffle;
11784                                                         specCase["tt_dst"]              = dstType.typeName;
11785
11786                                                         caseBodies      += testCaseBody.specialize(specCase);
11787                                                         caseList        += de::toString(caseCount) + " %case_" + de::toString(caseCount) + " ";
11788
11789                                                         caseCount++;
11790                                                 }
11791                                         }
11792                                 }
11793
11794                                 specs["num_data_points"]        = de::toString(numDataPoints);
11795                                 specs["tt_dst"]                         = dstType.typeName;
11796                                 specs["tt_src0"]                        = src0Type.typeName;
11797                                 specs["tt_src1"]                        = src1Type.typeName;
11798                                 specs["case_bodies"]            = caseBodies;
11799                                 specs["case_list"]                      = caseList;
11800                                 specs["case_count"]                     = de::toString(caseCount);
11801
11802                                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
11803                                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
11804                                 fragments["decoration"]         = decoration.specialize(specs);
11805                                 fragments["pre_main"]           = preMain.specialize(specs);
11806                                 fragments["testfun"]            = testFun.specialize(specs);
11807
11808                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input0Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11809                                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(float16Input1Data)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11810                                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16OutputDummy)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
11811                                 specResource.verifyIO = getFloat16VectorShuffleVerifyIOFunc(dstType.typeComponents, src0Type.typeComponents, src1Type.typeComponents);
11812
11813                                 extensions.push_back("VK_KHR_16bit_storage");
11814                                 extensions.push_back("VK_KHR_shader_float16_int8");
11815
11816                                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
11817                                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
11818
11819                                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
11820                         }
11821                 }
11822         }
11823
11824         return testGroup.release();
11825 }
11826
11827 bool compareFP16CompositeFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>&, TestLog& log)
11828 {
11829         if (inputs.size() != 1 || outputAllocs.size() != 1)
11830                 return false;
11831
11832         vector<deUint8> input1Bytes;
11833
11834         inputs[0].getBytes(input1Bytes);
11835
11836         DE_ASSERT(input1Bytes.size() > 0);
11837         DE_ASSERT(input1Bytes.size() % sizeof(deFloat16) == 0);
11838
11839         const size_t                    iterations              = input1Bytes.size() / sizeof(deFloat16);
11840         const deFloat16* const  input1AsFP16    = (const deFloat16*)&input1Bytes[0];
11841         const deFloat16* const  outputAsFP16    = (const deFloat16*)outputAllocs[0]->getHostPtr();
11842         const deFloat16                 exceptionValue  = tcu::Float16(-1.0).bits();
11843         std::string                             error;
11844
11845         for (size_t idx = 0; idx < iterations; ++idx)
11846         {
11847                 if (input1AsFP16[idx] == exceptionValue)
11848                         continue;
11849
11850                 if (!compare16BitFloat(input1AsFP16[idx], outputAsFP16[idx], error))
11851                 {
11852                         log << TestLog::Message << "At " << idx << ":" << error << TestLog::EndMessage;
11853
11854                         return false;
11855                 }
11856         }
11857
11858         return true;
11859 }
11860
11861 template<class SpecResource>
11862 tcu::TestCaseGroup* createFloat16CompositeConstructSet (tcu::TestContext& testCtx)
11863 {
11864         de::MovePtr<tcu::TestCaseGroup>         testGroup                               (new tcu::TestCaseGroup(testCtx, "opcompositeconstruct", "OpCompositeConstruct tests"));
11865         const deUint32                                          numElements                             = 8;
11866         const string                                            testName                                = "struct";
11867         const deUint32                                          structItemsCount                = 88;
11868         const deUint32                                          exceptionIndices[]              = { 1, 7, 15, 17, 25, 33, 51, 55, 59, 63, 67, 71, 84, 85, 86, 87 };
11869         const deFloat16                                         exceptionValue                  = tcu::Float16(-1.0).bits();
11870         const deUint32                                          fieldModifier                   = 2;
11871         const deUint32                                          fieldModifiedMulIndex   = 60;
11872         const deUint32                                          fieldModifiedAddIndex   = 66;
11873
11874         const StringTemplate preMain
11875         (
11876                 "    %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
11877                 "          %f16 = OpTypeFloat 16\n"
11878                 "        %v2f16 = OpTypeVector %f16 2\n"
11879                 "        %v3f16 = OpTypeVector %f16 3\n"
11880                 "        %v4f16 = OpTypeVector %f16 4\n"
11881                 "    %c_f16_mod = OpConstant %f16 ${field_modifier}\n"
11882
11883                 "${consts}"
11884
11885                 "      %c_u32_5 = OpConstant %u32 5\n"
11886
11887                 " %f16arr3      = OpTypeArray %f16 %c_u32_3\n"
11888                 " %v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
11889                 " %v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
11890                 " %v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
11891                 " %v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
11892                 " %struct16     = OpTypeStruct %f16 %v2f16arr3\n"
11893                 " %struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
11894                 " %st_test      = OpTypeStruct %f16 %v2f16 %v3f16 %v4f16 %f16arr3 %struct16arr3 %v2f16arr5 %f16 %v3f16arr5 %v4f16arr3\n"
11895
11896                 "        %up_st = OpTypePointer Uniform %st_test\n"
11897                 "        %ra_st = OpTypeArray %st_test %c_i32_ndp\n"
11898                 "      %SSBO_st = OpTypeStruct %ra_st\n"
11899                 "   %up_SSBO_st = OpTypePointer Uniform %SSBO_st\n"
11900
11901                 "     %ssbo_dst = OpVariable %up_SSBO_st Uniform\n"
11902         );
11903
11904         const StringTemplate decoration
11905         (
11906                 "OpDecorate %SSBO_st BufferBlock\n"
11907                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
11908                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
11909                 "OpDecorate %ssbo_dst Binding 1\n"
11910
11911                 "OpMemberDecorate %SSBO_st 0 Offset 0\n"
11912
11913                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
11914                 "OpMemberDecorate %struct16 0 Offset 0\n"
11915                 "OpMemberDecorate %struct16 1 Offset 4\n"
11916                 "OpDecorate %struct16arr3 ArrayStride 16\n"
11917                 "OpDecorate %f16arr3 ArrayStride 2\n"
11918                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
11919                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
11920                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
11921
11922                 "OpMemberDecorate %st_test 0 Offset 0\n"
11923                 "OpMemberDecorate %st_test 1 Offset 4\n"
11924                 "OpMemberDecorate %st_test 2 Offset 8\n"
11925                 "OpMemberDecorate %st_test 3 Offset 16\n"
11926                 "OpMemberDecorate %st_test 4 Offset 24\n"
11927                 "OpMemberDecorate %st_test 5 Offset 32\n"
11928                 "OpMemberDecorate %st_test 6 Offset 80\n"
11929                 "OpMemberDecorate %st_test 7 Offset 100\n"
11930                 "OpMemberDecorate %st_test 8 Offset 104\n"
11931                 "OpMemberDecorate %st_test 9 Offset 144\n"
11932         );
11933
11934         const StringTemplate testFun
11935         (
11936                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
11937                 "     %param = OpFunctionParameter %v4f32\n"
11938                 "     %entry = OpLabel\n"
11939
11940                 "         %i = OpVariable %fp_i32 Function\n"
11941                 "              OpStore %i %c_i32_0\n"
11942
11943                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
11944                 "              OpSelectionMerge %end_if None\n"
11945                 "              OpBranchConditional %will_run %run_test %end_if\n"
11946
11947                 "  %run_test = OpLabel\n"
11948                 "              OpBranch %loop\n"
11949
11950                 "      %loop = OpLabel\n"
11951                 "     %i_cmp = OpLoad %i32 %i\n"
11952                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
11953                 "              OpLoopMerge %merge %next None\n"
11954                 "              OpBranchConditional %lt %write %merge\n"
11955
11956                 "     %write = OpLabel\n"
11957                 "       %ndx = OpLoad %i32 %i\n"
11958
11959                 "      %fld1 = OpCompositeConstruct %v2f16 %c_f16_2 %c_f16_3\n"
11960                 "      %fld2 = OpCompositeConstruct %v3f16 %c_f16_4 %c_f16_5 %c_f16_6\n"
11961                 "      %fld3 = OpCompositeConstruct %v4f16 %c_f16_8 %c_f16_9 %c_f16_10 %c_f16_11\n"
11962
11963                 "      %fld4 = OpCompositeConstruct %f16arr3 %c_f16_12 %c_f16_13 %c_f16_14\n"
11964
11965                 "%fld5_0_1_0 = OpCompositeConstruct %v2f16 %c_f16_18 %c_f16_19\n"
11966                 "%fld5_0_1_1 = OpCompositeConstruct %v2f16 %c_f16_20 %c_f16_21\n"
11967                 "%fld5_0_1_2 = OpCompositeConstruct %v2f16 %c_f16_22 %c_f16_23\n"
11968                 "  %fld5_0_1 = OpCompositeConstruct %v2f16arr3 %fld5_0_1_0 %fld5_0_1_1 %fld5_0_1_2\n"
11969                 "    %fld5_0 = OpCompositeConstruct %struct16 %c_f16_16 %fld5_0_1\n"
11970
11971                 "%fld5_1_1_0 = OpCompositeConstruct %v2f16 %c_f16_26 %c_f16_27\n"
11972                 "%fld5_1_1_1 = OpCompositeConstruct %v2f16 %c_f16_28 %c_f16_29\n"
11973                 "%fld5_1_1_2 = OpCompositeConstruct %v2f16 %c_f16_30 %c_f16_31\n"
11974                 "  %fld5_1_1 = OpCompositeConstruct %v2f16arr3 %fld5_1_1_0 %fld5_1_1_1 %fld5_1_1_2\n"
11975                 "    %fld5_1 = OpCompositeConstruct %struct16 %c_f16_24 %fld5_1_1\n"
11976
11977                 "%fld5_2_1_0 = OpCompositeConstruct %v2f16 %c_f16_34 %c_f16_35\n"
11978                 "%fld5_2_1_1 = OpCompositeConstruct %v2f16 %c_f16_36 %c_f16_37\n"
11979                 "%fld5_2_1_2 = OpCompositeConstruct %v2f16 %c_f16_38 %c_f16_39\n"
11980                 "  %fld5_2_1 = OpCompositeConstruct %v2f16arr3 %fld5_2_1_0 %fld5_2_1_1 %fld5_2_1_2\n"
11981                 "    %fld5_2 = OpCompositeConstruct %struct16 %c_f16_32 %fld5_2_1\n"
11982
11983                 "      %fld5 = OpCompositeConstruct %struct16arr3 %fld5_0 %fld5_1 %fld5_2\n"
11984
11985                 "    %fld6_0 = OpCompositeConstruct %v2f16 %c_f16_40 %c_f16_41\n"
11986                 "    %fld6_1 = OpCompositeConstruct %v2f16 %c_f16_42 %c_f16_43\n"
11987                 "    %fld6_2 = OpCompositeConstruct %v2f16 %c_f16_44 %c_f16_45\n"
11988                 "    %fld6_3 = OpCompositeConstruct %v2f16 %c_f16_46 %c_f16_47\n"
11989                 "    %fld6_4 = OpCompositeConstruct %v2f16 %c_f16_48 %c_f16_49\n"
11990                 "      %fld6 = OpCompositeConstruct %v2f16arr5 %fld6_0 %fld6_1 %fld6_2 %fld6_3 %fld6_4\n"
11991
11992                 "      %fndx = OpConvertSToF %f16 %ndx\n"
11993                 "  %fld8_2a0 = OpFMul %f16 %fndx %c_f16_mod\n"
11994                 "  %fld8_3b1 = OpFAdd %f16 %fndx %c_f16_mod\n"
11995
11996                 "   %fld8_2a = OpCompositeConstruct %v2f16 %fld8_2a0 %c_f16_61\n"
11997                 "   %fld8_3b = OpCompositeConstruct %v2f16 %c_f16_65 %fld8_3b1\n"
11998                 "    %fld8_0 = OpCompositeConstruct %v3f16 %c_f16_52 %c_f16_53 %c_f16_54\n"
11999                 "    %fld8_1 = OpCompositeConstruct %v3f16 %c_f16_56 %c_f16_57 %c_f16_58\n"
12000                 "    %fld8_2 = OpCompositeConstruct %v3f16 %fld8_2a %c_f16_62\n"
12001                 "    %fld8_3 = OpCompositeConstruct %v3f16 %c_f16_64 %fld8_3b\n"
12002                 "    %fld8_4 = OpCompositeConstruct %v3f16 %c_f16_68 %c_f16_69 %c_f16_70\n"
12003                 "      %fld8 = OpCompositeConstruct %v3f16arr5 %fld8_0 %fld8_1 %fld8_2 %fld8_3 %fld8_4\n"
12004
12005                 "    %fld9_0 = OpCompositeConstruct %v4f16 %c_f16_72 %c_f16_73 %c_f16_74 %c_f16_75\n"
12006                 "    %fld9_1 = OpCompositeConstruct %v4f16 %c_f16_76 %c_f16_77 %c_f16_78 %c_f16_79\n"
12007                 "    %fld9_2 = OpCompositeConstruct %v4f16 %c_f16_80 %c_f16_81 %c_f16_82 %c_f16_83\n"
12008                 "      %fld9 = OpCompositeConstruct %v4f16arr3 %fld9_0 %fld9_1 %fld9_2\n"
12009
12010                 "    %st_val = OpCompositeConstruct %st_test %c_f16_0 %fld1 %fld2 %fld3 %fld4 %fld5 %fld6 %c_f16_50 %fld8 %fld9\n"
12011                 "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %ndx\n"
12012                 "              OpStore %dst %st_val\n"
12013
12014                 "              OpBranch %next\n"
12015
12016                 "      %next = OpLabel\n"
12017                 "     %i_cur = OpLoad %i32 %i\n"
12018                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
12019                 "              OpStore %i %i_new\n"
12020                 "              OpBranch %loop\n"
12021
12022                 "     %merge = OpLabel\n"
12023                 "              OpBranch %end_if\n"
12024                 "    %end_if = OpLabel\n"
12025                 "              OpReturnValue %param\n"
12026                 "              OpFunctionEnd\n"
12027         );
12028
12029         {
12030                 SpecResource            specResource;
12031                 map<string, string>     specs;
12032                 VulkanFeatures          features;
12033                 map<string, string>     fragments;
12034                 vector<string>          extensions;
12035                 vector<deFloat16>       expectedOutput;
12036                 string                          consts;
12037
12038                 for (deUint32 elementNdx = 0; elementNdx < numElements; ++elementNdx)
12039                 {
12040                         vector<deFloat16>       expectedIterationOutput;
12041
12042                         for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
12043                                 expectedIterationOutput.push_back(tcu::Float16(float(structItemNdx)).bits());
12044
12045                         for (deUint32 structItemNdx = 0; structItemNdx < DE_LENGTH_OF_ARRAY(exceptionIndices); ++structItemNdx)
12046                                 expectedIterationOutput[exceptionIndices[structItemNdx]] = exceptionValue;
12047
12048                         expectedIterationOutput[fieldModifiedMulIndex] = tcu::Float16(float(elementNdx * fieldModifier)).bits();
12049                         expectedIterationOutput[fieldModifiedAddIndex] = tcu::Float16(float(elementNdx + fieldModifier)).bits();
12050
12051                         expectedOutput.insert(expectedOutput.end(), expectedIterationOutput.begin(), expectedIterationOutput.end());
12052                 }
12053
12054                 for (deUint32 i = 0; i < structItemsCount; ++i)
12055                         consts += "     %c_f16_" + de::toString(i) + " = OpConstant %f16 "  + de::toString(i) + "\n";
12056
12057                 specs["num_elements"]           = de::toString(numElements);
12058                 specs["struct_item_size"]       = de::toString(structItemsCount * sizeof(deFloat16));
12059                 specs["field_modifier"]         = de::toString(fieldModifier);
12060                 specs["consts"]                         = consts;
12061
12062                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
12063                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
12064                 fragments["decoration"]         = decoration.specialize(specs);
12065                 fragments["pre_main"]           = preMain.specialize(specs);
12066                 fragments["testfun"]            = testFun.specialize(specs);
12067
12068                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12069                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(expectedOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12070                 specResource.verifyIO = compareFP16CompositeFunc;
12071
12072                 extensions.push_back("VK_KHR_16bit_storage");
12073                 extensions.push_back("VK_KHR_shader_float16_int8");
12074
12075                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
12076                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
12077
12078                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
12079         }
12080
12081         return testGroup.release();
12082 }
12083
12084 template<class SpecResource>
12085 tcu::TestCaseGroup* createFloat16CompositeInsertExtractSet (tcu::TestContext& testCtx, const char* op)
12086 {
12087         de::MovePtr<tcu::TestCaseGroup>         testGroup               (new tcu::TestCaseGroup(testCtx, de::toLower(op).c_str(), op));
12088         const deFloat16                                         exceptionValue  = tcu::Float16(-1.0).bits();
12089         const string                                            opName                  (op);
12090         const deUint32                                          opIndex                 = (opName == "OpCompositeInsert") ? 0
12091                                                                                                                 : (opName == "OpCompositeExtract") ? 1
12092                                                                                                                 : -1;
12093
12094         const StringTemplate preMain
12095         (
12096                 "   %c_i32_ndp = OpConstant %i32 ${num_elements}\n"
12097                 "         %f16 = OpTypeFloat 16\n"
12098                 "       %v2f16 = OpTypeVector %f16 2\n"
12099                 "       %v3f16 = OpTypeVector %f16 3\n"
12100                 "       %v4f16 = OpTypeVector %f16 4\n"
12101                 "    %c_f16_na = OpConstant %f16 -1.0\n"
12102                 "     %c_u32_5 = OpConstant %u32 5\n"
12103
12104                 "%f16arr3      = OpTypeArray %f16 %c_u32_3\n"
12105                 "%v2f16arr3    = OpTypeArray %v2f16 %c_u32_3\n"
12106                 "%v2f16arr5    = OpTypeArray %v2f16 %c_u32_5\n"
12107                 "%v3f16arr5    = OpTypeArray %v3f16 %c_u32_5\n"
12108                 "%v4f16arr3    = OpTypeArray %v4f16 %c_u32_3\n"
12109                 "%struct16     = OpTypeStruct %f16 %v2f16arr3\n"
12110                 "%struct16arr3 = OpTypeArray %struct16 %c_u32_3\n"
12111                 "%st_test      = OpTypeStruct %${field_type}\n"
12112
12113                 "      %up_f16 = OpTypePointer Uniform %f16\n"
12114                 "       %up_st = OpTypePointer Uniform %st_test\n"
12115                 "      %ra_f16 = OpTypeArray %f16 %c_i32_ndp\n"
12116                 "       %ra_st = OpTypeArray %st_test %c_i32_1\n"
12117
12118                 "${op_premain_decls}"
12119
12120                 " %up_SSBO_src = OpTypePointer Uniform %SSBO_src\n"
12121                 " %up_SSBO_dst = OpTypePointer Uniform %SSBO_dst\n"
12122
12123                 "    %ssbo_src = OpVariable %up_SSBO_src Uniform\n"
12124                 "    %ssbo_dst = OpVariable %up_SSBO_dst Uniform\n"
12125         );
12126
12127         const StringTemplate decoration
12128         (
12129                 "OpDecorate %SSBO_src BufferBlock\n"
12130                 "OpDecorate %SSBO_dst BufferBlock\n"
12131                 "OpDecorate %ra_f16 ArrayStride 2\n"
12132                 "OpDecorate %ra_st ArrayStride ${struct_item_size}\n"
12133                 "OpDecorate %ssbo_src DescriptorSet 0\n"
12134                 "OpDecorate %ssbo_src Binding 0\n"
12135                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
12136                 "OpDecorate %ssbo_dst Binding 1\n"
12137
12138                 "OpMemberDecorate %SSBO_src 0 Offset 0\n"
12139                 "OpMemberDecorate %SSBO_dst 0 Offset 0\n"
12140
12141                 "OpDecorate %v2f16arr3 ArrayStride 4\n"
12142                 "OpMemberDecorate %struct16 0 Offset 0\n"
12143                 "OpMemberDecorate %struct16 1 Offset 4\n"
12144                 "OpDecorate %struct16arr3 ArrayStride 16\n"
12145                 "OpDecorate %f16arr3 ArrayStride 2\n"
12146                 "OpDecorate %v2f16arr5 ArrayStride 4\n"
12147                 "OpDecorate %v3f16arr5 ArrayStride 8\n"
12148                 "OpDecorate %v4f16arr3 ArrayStride 8\n"
12149
12150                 "OpMemberDecorate %st_test 0 Offset 0\n"
12151         );
12152
12153         const StringTemplate testFun
12154         (
12155                 " %test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
12156                 "     %param = OpFunctionParameter %v4f32\n"
12157                 "     %entry = OpLabel\n"
12158
12159                 "         %i = OpVariable %fp_i32 Function\n"
12160                 "              OpStore %i %c_i32_0\n"
12161
12162                 "  %will_run = OpFunctionCall %bool %isUniqueIdZero\n"
12163                 "              OpSelectionMerge %end_if None\n"
12164                 "              OpBranchConditional %will_run %run_test %end_if\n"
12165
12166                 "  %run_test = OpLabel\n"
12167                 "              OpBranch %loop\n"
12168
12169                 "      %loop = OpLabel\n"
12170                 "     %i_cmp = OpLoad %i32 %i\n"
12171                 "        %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
12172                 "              OpLoopMerge %merge %next None\n"
12173                 "              OpBranchConditional %lt %write %merge\n"
12174
12175                 "     %write = OpLabel\n"
12176                 "       %ndx = OpLoad %i32 %i\n"
12177
12178                 "${op_sw_fun_call}"
12179
12180                 "              OpStore %dst %val_dst\n"
12181                 "              OpBranch %next\n"
12182
12183                 "      %next = OpLabel\n"
12184                 "     %i_cur = OpLoad %i32 %i\n"
12185                 "     %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
12186                 "              OpStore %i %i_new\n"
12187                 "              OpBranch %loop\n"
12188
12189                 "     %merge = OpLabel\n"
12190                 "              OpBranch %end_if\n"
12191                 "    %end_if = OpLabel\n"
12192                 "              OpReturnValue %param\n"
12193                 "              OpFunctionEnd\n"
12194
12195                 "${op_sw_fun_header}"
12196                 " %sw_param = OpFunctionParameter %st_test\n"
12197                 "%sw_paramn = OpFunctionParameter %i32\n"
12198                 " %sw_entry = OpLabel\n"
12199                 "             OpSelectionMerge %switch_e None\n"
12200                 "             OpSwitch %sw_paramn %default ${case_list}\n"
12201
12202                 "${case_bodies}"
12203
12204                 "%default   = OpLabel\n"
12205                 "             OpReturnValue ${op_case_default_value}\n"
12206                 "%switch_e  = OpLabel\n"
12207                 "             OpUnreachable\n" // Unreachable merge block for switch statement
12208                 "             OpFunctionEnd\n"
12209         );
12210
12211         const StringTemplate testCaseBody
12212         (
12213                 "%case_${case_ndx}    = OpLabel\n"
12214                 "%val_ret_${case_ndx} = ${op_name} ${op_args_part} ${access_path}\n"
12215                 "             OpReturnValue %val_ret_${case_ndx}\n"
12216         );
12217
12218         struct OpParts
12219         {
12220                 const char*     premainDecls;
12221                 const char*     swFunCall;
12222                 const char*     swFunHeader;
12223                 const char*     caseDefaultValue;
12224                 const char*     argsPartial;
12225         };
12226
12227         OpParts                                                         opPartsArray[]                  =
12228         {
12229                 // OpCompositeInsert
12230                 {
12231                         "       %fun_t = OpTypeFunction %st_test %f16 %st_test %i32\n"
12232                         "    %SSBO_src = OpTypeStruct %ra_f16\n"
12233                         "    %SSBO_dst = OpTypeStruct %ra_st\n",
12234
12235                         "       %src = OpAccessChain %up_f16 %ssbo_src %c_i32_0 %ndx\n"
12236                         "       %dst = OpAccessChain %up_st %ssbo_dst %c_i32_0 %c_i32_0\n"
12237                         "   %val_new = OpLoad %f16 %src\n"
12238                         "   %val_old = OpLoad %st_test %dst\n"
12239                         "   %val_dst = OpFunctionCall %st_test %sw_fun %val_new %val_old %ndx\n",
12240
12241                         "   %sw_fun = OpFunction %st_test None %fun_t\n"
12242                         "%sw_paramv = OpFunctionParameter %f16\n",
12243
12244                         "%sw_param",
12245
12246                         "%st_test %sw_paramv %sw_param",
12247                 },
12248                 // OpCompositeExtract
12249                 {
12250                         "       %fun_t = OpTypeFunction %f16 %st_test %i32\n"
12251                         "    %SSBO_src = OpTypeStruct %ra_st\n"
12252                         "    %SSBO_dst = OpTypeStruct %ra_f16\n",
12253
12254                         "       %src = OpAccessChain %up_st %ssbo_src %c_i32_0 %c_i32_0\n"
12255                         "       %dst = OpAccessChain %up_f16 %ssbo_dst %c_i32_0 %ndx\n"
12256                         "   %val_src = OpLoad %st_test %src\n"
12257                         "   %val_dst = OpFunctionCall %f16 %sw_fun %val_src %ndx\n",
12258
12259                         "   %sw_fun = OpFunction %f16 None %fun_t\n",
12260
12261                         "%c_f16_na",
12262
12263                         "%f16 %sw_param",
12264                 },
12265         };
12266
12267         DE_ASSERT(opIndex >= 0 && opIndex < DE_LENGTH_OF_ARRAY(opPartsArray));
12268
12269         const char*     accessPathF16[] =
12270         {
12271                 "0",                    // %f16
12272                 DE_NULL,
12273         };
12274         const char*     accessPathV2F16[] =
12275         {
12276                 "0 0",                  // %v2f16
12277                 "0 1",
12278         };
12279         const char*     accessPathV3F16[] =
12280         {
12281                 "0 0",                  // %v3f16
12282                 "0 1",
12283                 "0 2",
12284                 DE_NULL,
12285         };
12286         const char*     accessPathV4F16[] =
12287         {
12288                 "0 0",                  // %v4f16"
12289                 "0 1",
12290                 "0 2",
12291                 "0 3",
12292         };
12293         const char*     accessPathF16Arr3[] =
12294         {
12295                 "0 0",                  // %f16arr3
12296                 "0 1",
12297                 "0 2",
12298                 DE_NULL,
12299         };
12300         const char*     accessPathStruct16Arr3[] =
12301         {
12302                 "0 0 0",                // %struct16arr3
12303                 DE_NULL,
12304                 "0 0 1 0 0",
12305                 "0 0 1 0 1",
12306                 "0 0 1 1 0",
12307                 "0 0 1 1 1",
12308                 "0 0 1 2 0",
12309                 "0 0 1 2 1",
12310                 "0 1 0",
12311                 DE_NULL,
12312                 "0 1 1 0 0",
12313                 "0 1 1 0 1",
12314                 "0 1 1 1 0",
12315                 "0 1 1 1 1",
12316                 "0 1 1 2 0",
12317                 "0 1 1 2 1",
12318                 "0 2 0",
12319                 DE_NULL,
12320                 "0 2 1 0 0",
12321                 "0 2 1 0 1",
12322                 "0 2 1 1 0",
12323                 "0 2 1 1 1",
12324                 "0 2 1 2 0",
12325                 "0 2 1 2 1",
12326         };
12327         const char*     accessPathV2F16Arr5[] =
12328         {
12329                 "0 0 0",                // %v2f16arr5
12330                 "0 0 1",
12331                 "0 1 0",
12332                 "0 1 1",
12333                 "0 2 0",
12334                 "0 2 1",
12335                 "0 3 0",
12336                 "0 3 1",
12337                 "0 4 0",
12338                 "0 4 1",
12339         };
12340         const char*     accessPathV3F16Arr5[] =
12341         {
12342                 "0 0 0",                // %v3f16arr5
12343                 "0 0 1",
12344                 "0 0 2",
12345                 DE_NULL,
12346                 "0 1 0",
12347                 "0 1 1",
12348                 "0 1 2",
12349                 DE_NULL,
12350                 "0 2 0",
12351                 "0 2 1",
12352                 "0 2 2",
12353                 DE_NULL,
12354                 "0 3 0",
12355                 "0 3 1",
12356                 "0 3 2",
12357                 DE_NULL,
12358                 "0 4 0",
12359                 "0 4 1",
12360                 "0 4 2",
12361                 DE_NULL,
12362         };
12363         const char*     accessPathV4F16Arr3[] =
12364         {
12365                 "0 0 0",                // %v4f16arr3
12366                 "0 0 1",
12367                 "0 0 2",
12368                 "0 0 3",
12369                 "0 1 0",
12370                 "0 1 1",
12371                 "0 1 2",
12372                 "0 1 3",
12373                 "0 2 0",
12374                 "0 2 1",
12375                 "0 2 2",
12376                 "0 2 3",
12377                 DE_NULL,
12378                 DE_NULL,
12379                 DE_NULL,
12380                 DE_NULL,
12381         };
12382
12383         struct TypeTestParameters
12384         {
12385                 const char*             name;
12386                 size_t                  accessPathLength;
12387                 const char**    accessPath;
12388         };
12389
12390         const TypeTestParameters typeTestParameters[] =
12391         {
12392                 {       "f16",                  DE_LENGTH_OF_ARRAY(accessPathF16),                      accessPathF16                   },
12393                 {       "v2f16",                DE_LENGTH_OF_ARRAY(accessPathV2F16),            accessPathV2F16                 },
12394                 {       "v3f16",                DE_LENGTH_OF_ARRAY(accessPathV3F16),            accessPathV3F16                 },
12395                 {       "v4f16",                DE_LENGTH_OF_ARRAY(accessPathV4F16),            accessPathV4F16                 },
12396                 {       "f16arr3",              DE_LENGTH_OF_ARRAY(accessPathF16Arr3),          accessPathF16Arr3               },
12397                 {       "v2f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV2F16Arr5),        accessPathV2F16Arr5             },
12398                 {       "v3f16arr5",    DE_LENGTH_OF_ARRAY(accessPathV3F16Arr5),        accessPathV3F16Arr5             },
12399                 {       "v4f16arr3",    DE_LENGTH_OF_ARRAY(accessPathV4F16Arr3),        accessPathV4F16Arr3             },
12400                 {       "struct16arr3", DE_LENGTH_OF_ARRAY(accessPathStruct16Arr3),     accessPathStruct16Arr3  },
12401         };
12402
12403         for (size_t typeTestNdx = 0; typeTestNdx < DE_LENGTH_OF_ARRAY(typeTestParameters); ++typeTestNdx)
12404         {
12405                 const OpParts           opParts                         = opPartsArray[opIndex];
12406                 const string            testName                        = typeTestParameters[typeTestNdx].name;
12407                 const size_t            structItemsCount        = typeTestParameters[typeTestNdx].accessPathLength;
12408                 const char**            accessPath                      = typeTestParameters[typeTestNdx].accessPath;
12409                 SpecResource            specResource;
12410                 map<string, string>     specs;
12411                 VulkanFeatures          features;
12412                 map<string, string>     fragments;
12413                 vector<string>          extensions;
12414                 vector<deFloat16>       inputFP16;
12415                 vector<deFloat16>       dummyFP16Output;
12416
12417                 // Generate values for input
12418                 inputFP16.reserve(structItemsCount);
12419                 for (deUint32 structItemNdx = 0; structItemNdx < structItemsCount; ++structItemNdx)
12420                         inputFP16.push_back((accessPath[structItemNdx] == DE_NULL) ? exceptionValue : tcu::Float16(float(structItemNdx)).bits());
12421
12422                 dummyFP16Output.resize(structItemsCount);
12423
12424                 // Generate cases for OpSwitch
12425                 {
12426                         string  caseBodies;
12427                         string  caseList;
12428
12429                         for (deUint32 caseNdx = 0; caseNdx < structItemsCount; ++caseNdx)
12430                                 if (accessPath[caseNdx] != DE_NULL)
12431                                 {
12432                                         map<string, string>     specCase;
12433
12434                                         specCase["case_ndx"]            = de::toString(caseNdx);
12435                                         specCase["access_path"]         = accessPath[caseNdx];
12436                                         specCase["op_args_part"]        = opParts.argsPartial;
12437                                         specCase["op_name"]                     = opName;
12438
12439                                         caseBodies      += testCaseBody.specialize(specCase);
12440                                         caseList        += de::toString(caseNdx) + " %case_" + de::toString(caseNdx) + " ";
12441                                 }
12442
12443                         specs["case_bodies"]    = caseBodies;
12444                         specs["case_list"]              = caseList;
12445                 }
12446
12447                 specs["num_elements"]                   = de::toString(structItemsCount);
12448                 specs["field_type"]                             = typeTestParameters[typeTestNdx].name;
12449                 specs["struct_item_size"]               = de::toString(structItemsCount * sizeof(deFloat16));
12450                 specs["op_premain_decls"]               = opParts.premainDecls;
12451                 specs["op_sw_fun_call"]                 = opParts.swFunCall;
12452                 specs["op_sw_fun_header"]               = opParts.swFunHeader;
12453                 specs["op_case_default_value"]  = opParts.caseDefaultValue;
12454
12455                 fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"";
12456                 fragments["capability"]         = "OpCapability StorageUniformBufferBlock16\n";
12457                 fragments["decoration"]         = decoration.specialize(specs);
12458                 fragments["pre_main"]           = preMain.specialize(specs);
12459                 fragments["testfun"]            = testFun.specialize(specs);
12460
12461                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputFP16)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12462                 specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(dummyFP16Output)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
12463                 specResource.verifyIO = compareFP16CompositeFunc;
12464
12465                 extensions.push_back("VK_KHR_16bit_storage");
12466                 extensions.push_back("VK_KHR_shader_float16_int8");
12467
12468                 features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
12469                 features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
12470
12471                 finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
12472         }
12473
12474         return testGroup.release();
12475 }
12476
12477 struct fp16PerComponent
12478 {
12479         fp16PerComponent()
12480                 : flavor(0)
12481                 , floatFormat16 (-14, 15, 10, true)
12482                 , outCompCount(0)
12483                 , argCompCount(3, 0)
12484         {
12485         }
12486
12487         bool                    callOncePerComponent    ()                                                                      { return true; }
12488         deUint32                getComponentValidity    ()                                                                      { return static_cast<deUint32>(-1); }
12489
12490         virtual double  getULPs                                 (vector<const deFloat16*>&)                     { return 1.0; }
12491         virtual double  getMin                                  (double value, double ulps)                     { return value - floatFormat16.ulp(deAbs(value), ulps); }
12492         virtual double  getMax                                  (double value, double ulps)                     { return value + floatFormat16.ulp(deAbs(value), ulps); }
12493
12494         virtual size_t  getFlavorCount                  ()                                                                      { return flavorNames.empty() ? 1 : flavorNames.size(); }
12495         virtual void    setFlavor                               (size_t flavorNo)                                       { DE_ASSERT(flavorNo < getFlavorCount()); flavor = flavorNo; }
12496         virtual size_t  getFlavor                               ()                                                                      { return flavor; }
12497         virtual string  getCurrentFlavorName    ()                                                                      { return flavorNames.empty() ? string("") : flavorNames[getFlavor()]; }
12498
12499         virtual void    setOutCompCount                 (size_t compCount)                                      { outCompCount = compCount; }
12500         virtual size_t  getOutCompCount                 ()                                                                      { return outCompCount; }
12501
12502         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)        { argCompCount[argNo] = compCount; }
12503         virtual size_t  getArgCompCount                 (size_t argNo)                                          { return argCompCount[argNo]; }
12504
12505 protected:
12506         size_t                          flavor;
12507         tcu::FloatFormat        floatFormat16;
12508         size_t                          outCompCount;
12509         vector<size_t>          argCompCount;
12510         vector<string>          flavorNames;
12511 };
12512
12513 struct fp16OpFNegate : public fp16PerComponent
12514 {
12515         template <class fp16type>
12516         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12517         {
12518                 const fp16type  x               (*in[0]);
12519                 const double    d               (x.asDouble());
12520                 const double    result  (0.0 - d);
12521
12522                 out[0] = fp16type(result).bits();
12523                 min[0] = getMin(result, getULPs(in));
12524                 max[0] = getMax(result, getULPs(in));
12525
12526                 return true;
12527         }
12528 };
12529
12530 struct fp16Round : public fp16PerComponent
12531 {
12532         fp16Round() : fp16PerComponent()
12533         {
12534                 flavorNames.push_back("Floor(x+0.5)");
12535                 flavorNames.push_back("Floor(x-0.5)");
12536                 flavorNames.push_back("RoundEven");
12537         }
12538
12539         template<class fp16type>
12540         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12541         {
12542                 const fp16type  x               (*in[0]);
12543                 const double    d               (x.asDouble());
12544                 double                  result  (0.0);
12545
12546                 switch (flavor)
12547                 {
12548                         case 0:         result = deRound(d);            break;
12549                         case 1:         result = deFloor(d - 0.5);      break;
12550                         case 2:         result = deRoundEven(d);        break;
12551                         default:        TCU_THROW(InternalError, "Invalid flavor specified");
12552                 }
12553
12554                 out[0] = fp16type(result).bits();
12555                 min[0] = getMin(result, getULPs(in));
12556                 max[0] = getMax(result, getULPs(in));
12557
12558                 return true;
12559         }
12560 };
12561
12562 struct fp16RoundEven : public fp16PerComponent
12563 {
12564         template<class fp16type>
12565         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12566         {
12567                 const fp16type  x               (*in[0]);
12568                 const double    d               (x.asDouble());
12569                 const double    result  (deRoundEven(d));
12570
12571                 out[0] = fp16type(result).bits();
12572                 min[0] = getMin(result, getULPs(in));
12573                 max[0] = getMax(result, getULPs(in));
12574
12575                 return true;
12576         }
12577 };
12578
12579 struct fp16Trunc : public fp16PerComponent
12580 {
12581         template<class fp16type>
12582         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12583         {
12584                 const fp16type  x               (*in[0]);
12585                 const double    d               (x.asDouble());
12586                 const double    result  (deTrunc(d));
12587
12588                 out[0] = fp16type(result).bits();
12589                 min[0] = getMin(result, getULPs(in));
12590                 max[0] = getMax(result, getULPs(in));
12591
12592                 return true;
12593         }
12594 };
12595
12596 struct fp16FAbs : public fp16PerComponent
12597 {
12598         template<class fp16type>
12599         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12600         {
12601                 const fp16type  x               (*in[0]);
12602                 const double    d               (x.asDouble());
12603                 const double    result  (deAbs(d));
12604
12605                 out[0] = fp16type(result).bits();
12606                 min[0] = getMin(result, getULPs(in));
12607                 max[0] = getMax(result, getULPs(in));
12608
12609                 return true;
12610         }
12611 };
12612
12613 struct fp16FSign : public fp16PerComponent
12614 {
12615         template<class fp16type>
12616         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12617         {
12618                 const fp16type  x               (*in[0]);
12619                 const double    d               (x.asDouble());
12620                 const double    result  (deSign(d));
12621
12622                 if (x.isNaN())
12623                         return false;
12624
12625                 out[0] = fp16type(result).bits();
12626                 min[0] = getMin(result, getULPs(in));
12627                 max[0] = getMax(result, getULPs(in));
12628
12629                 return true;
12630         }
12631 };
12632
12633 struct fp16Floor : public fp16PerComponent
12634 {
12635         template<class fp16type>
12636         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12637         {
12638                 const fp16type  x               (*in[0]);
12639                 const double    d               (x.asDouble());
12640                 const double    result  (deFloor(d));
12641
12642                 out[0] = fp16type(result).bits();
12643                 min[0] = getMin(result, getULPs(in));
12644                 max[0] = getMax(result, getULPs(in));
12645
12646                 return true;
12647         }
12648 };
12649
12650 struct fp16Ceil : public fp16PerComponent
12651 {
12652         template<class fp16type>
12653         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12654         {
12655                 const fp16type  x               (*in[0]);
12656                 const double    d               (x.asDouble());
12657                 const double    result  (deCeil(d));
12658
12659                 out[0] = fp16type(result).bits();
12660                 min[0] = getMin(result, getULPs(in));
12661                 max[0] = getMax(result, getULPs(in));
12662
12663                 return true;
12664         }
12665 };
12666
12667 struct fp16Fract : public fp16PerComponent
12668 {
12669         template<class fp16type>
12670         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12671         {
12672                 const fp16type  x               (*in[0]);
12673                 const double    d               (x.asDouble());
12674                 const double    result  (deFrac(d));
12675
12676                 out[0] = fp16type(result).bits();
12677                 min[0] = getMin(result, getULPs(in));
12678                 max[0] = getMax(result, getULPs(in));
12679
12680                 return true;
12681         }
12682 };
12683
12684 struct fp16Radians : public fp16PerComponent
12685 {
12686         virtual double getULPs (vector<const deFloat16*>& in)
12687         {
12688                 DE_UNREF(in);
12689
12690                 return 2.5;
12691         }
12692
12693         template<class fp16type>
12694         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12695         {
12696                 const fp16type  x               (*in[0]);
12697                 const float             d               (x.asFloat());
12698                 const float             result  (deFloatRadians(d));
12699
12700                 out[0] = fp16type(result).bits();
12701                 min[0] = getMin(result, getULPs(in));
12702                 max[0] = getMax(result, getULPs(in));
12703
12704                 return true;
12705         }
12706 };
12707
12708 struct fp16Degrees : public fp16PerComponent
12709 {
12710         virtual double getULPs (vector<const deFloat16*>& in)
12711         {
12712                 DE_UNREF(in);
12713
12714                 return 2.5;
12715         }
12716
12717         template<class fp16type>
12718         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12719         {
12720                 const fp16type  x               (*in[0]);
12721                 const float             d               (x.asFloat());
12722                 const float             result  (deFloatDegrees(d));
12723
12724                 out[0] = fp16type(result).bits();
12725                 min[0] = getMin(result, getULPs(in));
12726                 max[0] = getMax(result, getULPs(in));
12727
12728                 return true;
12729         }
12730 };
12731
12732 struct fp16Sin : public fp16PerComponent
12733 {
12734         template<class fp16type>
12735         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12736         {
12737                 const fp16type  x                       (*in[0]);
12738                 const double    d                       (x.asDouble());
12739                 const double    result          (deSin(d));
12740                 const double    unspecUlp       (16.0);
12741                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12742
12743                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12744                         return false;
12745
12746                 out[0] = fp16type(result).bits();
12747                 min[0] = result - err;
12748                 max[0] = result + err;
12749
12750                 return true;
12751         }
12752 };
12753
12754 struct fp16Cos : public fp16PerComponent
12755 {
12756         template<class fp16type>
12757         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12758         {
12759                 const fp16type  x                       (*in[0]);
12760                 const double    d                       (x.asDouble());
12761                 const double    result          (deCos(d));
12762                 const double    unspecUlp       (16.0);
12763                 const double    err                     (de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE) ? deLdExp(1.0, -7) : floatFormat16.ulp(deAbs(result), unspecUlp));
12764
12765                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12766                         return false;
12767
12768                 out[0] = fp16type(result).bits();
12769                 min[0] = result - err;
12770                 max[0] = result + err;
12771
12772                 return true;
12773         }
12774 };
12775
12776 struct fp16Tan : public fp16PerComponent
12777 {
12778         template<class fp16type>
12779         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12780         {
12781                 const fp16type  x               (*in[0]);
12782                 const double    d               (x.asDouble());
12783                 const double    result  (deTan(d));
12784
12785                 if (!de::inRange(d, -DE_PI_DOUBLE, DE_PI_DOUBLE))
12786                         return false;
12787
12788                 out[0] = fp16type(result).bits();
12789                 {
12790                         const double    err                     = deLdExp(1.0, -7);
12791                         const double    s1                      = deSin(d) + err;
12792                         const double    s2                      = deSin(d) - err;
12793                         const double    c1                      = deCos(d) + err;
12794                         const double    c2                      = deCos(d) - err;
12795                         const double    edgeVals[]      = {s1/c1, s1/c2, s2/c1, s2/c2};
12796                         double                  edgeLeft        = out[0];
12797                         double                  edgeRight       = out[0];
12798
12799                         if (deSign(c1 * c2) < 0.0)
12800                         {
12801                                 edgeLeft        = -std::numeric_limits<double>::infinity();
12802                                 edgeRight       = +std::numeric_limits<double>::infinity();
12803                         }
12804                         else
12805                         {
12806                                 edgeLeft        = *std::min_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12807                                 edgeRight       = *std::max_element(&edgeVals[0], &edgeVals[DE_LENGTH_OF_ARRAY(edgeVals)]);
12808                         }
12809
12810                         min[0] = edgeLeft;
12811                         max[0] = edgeRight;
12812                 }
12813
12814                 return true;
12815         }
12816 };
12817
12818 struct fp16Asin : public fp16PerComponent
12819 {
12820         template<class fp16type>
12821         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12822         {
12823                 const fp16type  x               (*in[0]);
12824                 const double    d               (x.asDouble());
12825                 const double    result  (deAsin(d));
12826                 const double    error   (deAtan2(d, sqrt(1.0 - d * d)));
12827
12828                 if (!x.isNaN() && deAbs(d) > 1.0)
12829                         return false;
12830
12831                 out[0] = fp16type(result).bits();
12832                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12833                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12834
12835                 return true;
12836         }
12837 };
12838
12839 struct fp16Acos : public fp16PerComponent
12840 {
12841         template<class fp16type>
12842         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12843         {
12844                 const fp16type  x               (*in[0]);
12845                 const double    d               (x.asDouble());
12846                 const double    result  (deAcos(d));
12847                 const double    error   (deAtan2(sqrt(1.0 - d * d), d));
12848
12849                 if (!x.isNaN() && deAbs(d) > 1.0)
12850                         return false;
12851
12852                 out[0] = fp16type(result).bits();
12853                 min[0] = result - floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12854                 max[0] = result + floatFormat16.ulp(deAbs(error), 2 * 5.0); // This is not a precision test. Value is not from spec
12855
12856                 return true;
12857         }
12858 };
12859
12860 struct fp16Atan : public fp16PerComponent
12861 {
12862         virtual double getULPs(vector<const deFloat16*>& in)
12863         {
12864                 DE_UNREF(in);
12865
12866                 return 2 * 5.0; // This is not a precision test. Value is not from spec
12867         }
12868
12869         template<class fp16type>
12870         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12871         {
12872                 const fp16type  x               (*in[0]);
12873                 const double    d               (x.asDouble());
12874                 const double    result  (deAtanOver(d));
12875
12876                 out[0] = fp16type(result).bits();
12877                 min[0] = getMin(result, getULPs(in));
12878                 max[0] = getMax(result, getULPs(in));
12879
12880                 return true;
12881         }
12882 };
12883
12884 struct fp16Sinh : public fp16PerComponent
12885 {
12886         fp16Sinh() : fp16PerComponent()
12887         {
12888                 flavorNames.push_back("Double");
12889                 flavorNames.push_back("ExpFP16");
12890         }
12891
12892         template<class fp16type>
12893         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12894         {
12895                 const fp16type  x               (*in[0]);
12896                 const double    d               (x.asDouble());
12897                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12898                 double                  result  (0.0);
12899                 double                  error   (0.0);
12900
12901                 if (getFlavor() == 0)
12902                 {
12903                         result  = deSinh(d);
12904                         error   = floatFormat16.ulp(deAbs(result), ulps);
12905                 }
12906                 else if (getFlavor() == 1)
12907                 {
12908                         const fp16type  epx     (deExp(d));
12909                         const fp16type  enx     (deExp(-d));
12910                         const fp16type  esx     (epx.asDouble() - enx.asDouble());
12911                         const fp16type  sx2     (esx.asDouble() / 2.0);
12912
12913                         result  = sx2.asDouble();
12914                         error   = deAbs(floatFormat16.ulp(epx.asDouble(), ulps)) + deAbs(floatFormat16.ulp(enx.asDouble(), ulps));
12915                 }
12916                 else
12917                 {
12918                         TCU_THROW(InternalError, "Unknown flavor");
12919                 }
12920
12921                 out[0] = fp16type(result).bits();
12922                 min[0] = result - error;
12923                 max[0] = result + error;
12924
12925                 return true;
12926         }
12927 };
12928
12929 struct fp16Cosh : public fp16PerComponent
12930 {
12931         fp16Cosh() : fp16PerComponent()
12932         {
12933                 flavorNames.push_back("Double");
12934                 flavorNames.push_back("ExpFP16");
12935         }
12936
12937         template<class fp16type>
12938         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
12939         {
12940                 const fp16type  x               (*in[0]);
12941                 const double    d               (x.asDouble());
12942                 const double    ulps    (64 * (1.0 + 2 * deAbs(d))); // This is not a precision test. Value is not from spec
12943                 double                  result  (0.0);
12944
12945                 if (getFlavor() == 0)
12946                 {
12947                         result = deCosh(d);
12948                 }
12949                 else if (getFlavor() == 1)
12950                 {
12951                         const fp16type  epx     (deExp(d));
12952                         const fp16type  enx     (deExp(-d));
12953                         const fp16type  esx     (epx.asDouble() + enx.asDouble());
12954                         const fp16type  sx2     (esx.asDouble() / 2.0);
12955
12956                         result = sx2.asDouble();
12957                 }
12958                 else
12959                 {
12960                         TCU_THROW(InternalError, "Unknown flavor");
12961                 }
12962
12963                 out[0] = fp16type(result).bits();
12964                 min[0] = result - floatFormat16.ulp(deAbs(result), ulps);
12965                 max[0] = result + floatFormat16.ulp(deAbs(result), ulps);
12966
12967                 return true;
12968         }
12969 };
12970
12971 struct fp16Tanh : public fp16PerComponent
12972 {
12973         fp16Tanh() : fp16PerComponent()
12974         {
12975                 flavorNames.push_back("Tanh");
12976                 flavorNames.push_back("SinhCosh");
12977                 flavorNames.push_back("SinhCoshFP16");
12978                 flavorNames.push_back("PolyFP16");
12979         }
12980
12981         virtual double getULPs (vector<const deFloat16*>& in)
12982         {
12983                 const tcu::Float16      x       (*in[0]);
12984                 const double            d       (x.asDouble());
12985
12986                 return 2 * (1.0 + 2 * deAbs(d)); // This is not a precision test. Value is not from spec
12987         }
12988
12989         template<class fp16type>
12990         inline double calcPoly (const fp16type& espx, const fp16type& esnx, const fp16type& ecpx, const fp16type& ecnx)
12991         {
12992                 const fp16type  esx     (espx.asDouble() - esnx.asDouble());
12993                 const fp16type  sx2     (esx.asDouble() / 2.0);
12994                 const fp16type  ecx     (ecpx.asDouble() + ecnx.asDouble());
12995                 const fp16type  cx2     (ecx.asDouble() / 2.0);
12996                 const fp16type  tg      (sx2.asDouble() / cx2.asDouble());
12997                 const double    rez     (tg.asDouble());
12998
12999                 return rez;
13000         }
13001
13002         template<class fp16type>
13003         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13004         {
13005                 const fp16type  x               (*in[0]);
13006                 const double    d               (x.asDouble());
13007                 double                  result  (0.0);
13008
13009                 if (getFlavor() == 0)
13010                 {
13011                         result  = deTanh(d);
13012                         min[0]  = getMin(result, getULPs(in));
13013                         max[0]  = getMax(result, getULPs(in));
13014                 }
13015                 else if (getFlavor() == 1)
13016                 {
13017                         result  = deSinh(d) / deCosh(d);
13018                         min[0]  = getMin(result, getULPs(in));
13019                         max[0]  = getMax(result, getULPs(in));
13020                 }
13021                 else if (getFlavor() == 2)
13022                 {
13023                         const fp16type  s       (deSinh(d));
13024                         const fp16type  c       (deCosh(d));
13025
13026                         result  = s.asDouble() / c.asDouble();
13027                         min[0]  = getMin(result, getULPs(in));
13028                         max[0]  = getMax(result, getULPs(in));
13029                 }
13030                 else if (getFlavor() == 3)
13031                 {
13032                         const double    ulps    (getULPs(in));
13033                         const double    epxm    (deExp( d));
13034                         const double    enxm    (deExp(-d));
13035                         const double    epxmerr = floatFormat16.ulp(epxm, ulps);
13036                         const double    enxmerr = floatFormat16.ulp(enxm, ulps);
13037                         const fp16type  epx[]   = { fp16type(epxm - epxmerr), fp16type(epxm + epxmerr) };
13038                         const fp16type  enx[]   = { fp16type(enxm - enxmerr), fp16type(enxm + enxmerr) };
13039                         const fp16type  epxm16  (epxm);
13040                         const fp16type  enxm16  (enxm);
13041                         vector<double>  tgs;
13042
13043                         for (size_t spNdx = 0; spNdx < DE_LENGTH_OF_ARRAY(epx); ++spNdx)
13044                         for (size_t snNdx = 0; snNdx < DE_LENGTH_OF_ARRAY(enx); ++snNdx)
13045                         for (size_t cpNdx = 0; cpNdx < DE_LENGTH_OF_ARRAY(epx); ++cpNdx)
13046                         for (size_t cnNdx = 0; cnNdx < DE_LENGTH_OF_ARRAY(enx); ++cnNdx)
13047                         {
13048                                 const double tgh = calcPoly(epx[spNdx], enx[snNdx], epx[cpNdx], enx[cnNdx]);
13049
13050                                 tgs.push_back(tgh);
13051                         }
13052
13053                         result = calcPoly(epxm16, enxm16, epxm16, enxm16);
13054                         min[0] = *std::min_element(tgs.begin(), tgs.end());
13055                         max[0] = *std::max_element(tgs.begin(), tgs.end());
13056                 }
13057                 else
13058                 {
13059                         TCU_THROW(InternalError, "Unknown flavor");
13060                 }
13061
13062                 out[0] = fp16type(result).bits();
13063
13064                 return true;
13065         }
13066 };
13067
13068 struct fp16Asinh : public fp16PerComponent
13069 {
13070         fp16Asinh() : fp16PerComponent()
13071         {
13072                 flavorNames.push_back("Double");
13073                 flavorNames.push_back("PolyFP16Wiki");
13074                 flavorNames.push_back("PolyFP16Abs");
13075         }
13076
13077         virtual double getULPs (vector<const deFloat16*>& in)
13078         {
13079                 DE_UNREF(in);
13080
13081                 return 256.0; // This is not a precision test. Value is not from spec
13082         }
13083
13084         template<class fp16type>
13085         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13086         {
13087                 const fp16type  x               (*in[0]);
13088                 const double    d               (x.asDouble());
13089                 double                  result  (0.0);
13090
13091                 if (getFlavor() == 0)
13092                 {
13093                         result = deAsinh(d);
13094                 }
13095                 else if (getFlavor() == 1)
13096                 {
13097                         const fp16type  x2              (d * d);
13098                         const fp16type  x2p1    (x2.asDouble() + 1.0);
13099                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
13100                         const fp16type  sxsq    (d + sq.asDouble());
13101                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
13102
13103                         if (lsxsq.isInf())
13104                                 return false;
13105
13106                         result = lsxsq.asDouble();
13107                 }
13108                 else if (getFlavor() == 2)
13109                 {
13110                         const fp16type  x2              (d * d);
13111                         const fp16type  x2p1    (x2.asDouble() + 1.0);
13112                         const fp16type  sq              (deSqrt(x2p1.asDouble()));
13113                         const fp16type  sxsq    (deAbs(d) + sq.asDouble());
13114                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
13115
13116                         result = deSign(d) * lsxsq.asDouble();
13117                 }
13118                 else
13119                 {
13120                         TCU_THROW(InternalError, "Unknown flavor");
13121                 }
13122
13123                 out[0] = fp16type(result).bits();
13124                 min[0] = getMin(result, getULPs(in));
13125                 max[0] = getMax(result, getULPs(in));
13126
13127                 return true;
13128         }
13129 };
13130
13131 struct fp16Acosh : public fp16PerComponent
13132 {
13133         fp16Acosh() : fp16PerComponent()
13134         {
13135                 flavorNames.push_back("Double");
13136                 flavorNames.push_back("PolyFP16");
13137         }
13138
13139         virtual double getULPs (vector<const deFloat16*>& in)
13140         {
13141                 DE_UNREF(in);
13142
13143                 return 16.0; // This is not a precision test. Value is not from spec
13144         }
13145
13146         template<class fp16type>
13147         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13148         {
13149                 const fp16type  x               (*in[0]);
13150                 const double    d               (x.asDouble());
13151                 double                  result  (0.0);
13152
13153                 if (!x.isNaN() && d < 1.0)
13154                         return false;
13155
13156                 if (getFlavor() == 0)
13157                 {
13158                         result = deAcosh(d);
13159                 }
13160                 else if (getFlavor() == 1)
13161                 {
13162                         const fp16type  x2              (d * d);
13163                         const fp16type  x2m1    (x2.asDouble() - 1.0);
13164                         const fp16type  sq              (deSqrt(x2m1.asDouble()));
13165                         const fp16type  sxsq    (d + sq.asDouble());
13166                         const fp16type  lsxsq   (deLog(sxsq.asDouble()));
13167
13168                         result = lsxsq.asDouble();
13169                 }
13170                 else
13171                 {
13172                         TCU_THROW(InternalError, "Unknown flavor");
13173                 }
13174
13175                 out[0] = fp16type(result).bits();
13176                 min[0] = getMin(result, getULPs(in));
13177                 max[0] = getMax(result, getULPs(in));
13178
13179                 return true;
13180         }
13181 };
13182
13183 struct fp16Atanh : public fp16PerComponent
13184 {
13185         fp16Atanh() : fp16PerComponent()
13186         {
13187                 flavorNames.push_back("Double");
13188                 flavorNames.push_back("PolyFP16");
13189         }
13190
13191         template<class fp16type>
13192         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13193         {
13194                 const fp16type  x               (*in[0]);
13195                 const double    d               (x.asDouble());
13196                 double                  result  (0.0);
13197
13198                 if (deAbs(d) >= 1.0)
13199                         return false;
13200
13201                 if (getFlavor() == 0)
13202                 {
13203                         const double    ulps    (16.0); // This is not a precision test. Value is not from spec
13204
13205                         result = deAtanh(d);
13206                         min[0] = getMin(result, ulps);
13207                         max[0] = getMax(result, ulps);
13208                 }
13209                 else if (getFlavor() == 1)
13210                 {
13211                         const fp16type  x1a             (1.0 + d);
13212                         const fp16type  x1b             (1.0 - d);
13213                         const fp16type  x1d             (x1a.asDouble() / x1b.asDouble());
13214                         const fp16type  lx1d    (deLog(x1d.asDouble()));
13215                         const fp16type  lx1d2   (0.5 * lx1d.asDouble());
13216                         const double    error   (2 * (de::inRange(deAbs(x1d.asDouble()), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(x1d.asDouble()), 3.0)));
13217
13218                         result = lx1d2.asDouble();
13219                         min[0] = result - error;
13220                         max[0] = result + error;
13221                 }
13222                 else
13223                 {
13224                         TCU_THROW(InternalError, "Unknown flavor");
13225                 }
13226
13227                 out[0] = fp16type(result).bits();
13228
13229                 return true;
13230         }
13231 };
13232
13233 struct fp16Exp : public fp16PerComponent
13234 {
13235         template<class fp16type>
13236         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13237         {
13238                 const fp16type  x               (*in[0]);
13239                 const double    d               (x.asDouble());
13240                 const double    ulps    (10.0 * (1.0 + 2.0 * deAbs(d)));
13241                 const double    result  (deExp(d));
13242
13243                 out[0] = fp16type(result).bits();
13244                 min[0] = getMin(result, ulps);
13245                 max[0] = getMax(result, ulps);
13246
13247                 return true;
13248         }
13249 };
13250
13251 struct fp16Log : public fp16PerComponent
13252 {
13253         template<class fp16type>
13254         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13255         {
13256                 const fp16type  x               (*in[0]);
13257                 const double    d               (x.asDouble());
13258                 const double    result  (deLog(d));
13259                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13260
13261                 if (d <= 0.0)
13262                         return false;
13263
13264                 out[0] = fp16type(result).bits();
13265                 min[0] = result - error;
13266                 max[0] = result + error;
13267
13268                 return true;
13269         }
13270 };
13271
13272 struct fp16Exp2 : public fp16PerComponent
13273 {
13274         template<class fp16type>
13275         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13276         {
13277                 const fp16type  x               (*in[0]);
13278                 const double    d               (x.asDouble());
13279                 const double    result  (deExp2(d));
13280                 const double    ulps    (1.0 + 2.0 * deAbs(fp16type(in[0][0]).asDouble()));
13281
13282                 out[0] = fp16type(result).bits();
13283                 min[0] = getMin(result, ulps);
13284                 max[0] = getMax(result, ulps);
13285
13286                 return true;
13287         }
13288 };
13289
13290 struct fp16Log2 : public fp16PerComponent
13291 {
13292         template<class fp16type>
13293         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13294         {
13295                 const fp16type  x               (*in[0]);
13296                 const double    d               (x.asDouble());
13297                 const double    result  (deLog2(d));
13298                 const double    error   (de::inRange(deAbs(d), 0.5, 2.0) ? deLdExp(2.0, -7) : floatFormat16.ulp(deAbs(result), 3.0));
13299
13300                 if (d <= 0.0)
13301                         return false;
13302
13303                 out[0] = fp16type(result).bits();
13304                 min[0] = result - error;
13305                 max[0] = result + error;
13306
13307                 return true;
13308         }
13309 };
13310
13311 struct fp16Sqrt : public fp16PerComponent
13312 {
13313         virtual double getULPs (vector<const deFloat16*>& in)
13314         {
13315                 DE_UNREF(in);
13316
13317                 return 6.0;
13318         }
13319
13320         template<class fp16type>
13321         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13322         {
13323                 const fp16type  x               (*in[0]);
13324                 const double    d               (x.asDouble());
13325                 const double    result  (deSqrt(d));
13326
13327                 if (!x.isNaN() && d < 0.0)
13328                         return false;
13329
13330                 out[0] = fp16type(result).bits();
13331                 min[0] = getMin(result, getULPs(in));
13332                 max[0] = getMax(result, getULPs(in));
13333
13334                 return true;
13335         }
13336 };
13337
13338 struct fp16InverseSqrt : public fp16PerComponent
13339 {
13340         virtual double getULPs (vector<const deFloat16*>& in)
13341         {
13342                 DE_UNREF(in);
13343
13344                 return 2.0;
13345         }
13346
13347         template<class fp16type>
13348         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13349         {
13350                 const fp16type  x               (*in[0]);
13351                 const double    d               (x.asDouble());
13352                 const double    result  (1.0/deSqrt(d));
13353
13354                 if (!x.isNaN() && d <= 0.0)
13355                         return false;
13356
13357                 out[0] = fp16type(result).bits();
13358                 min[0] = getMin(result, getULPs(in));
13359                 max[0] = getMax(result, getULPs(in));
13360
13361                 return true;
13362         }
13363 };
13364
13365 struct fp16ModfFrac : public fp16PerComponent
13366 {
13367         template<class fp16type>
13368         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13369         {
13370                 const fp16type  x               (*in[0]);
13371                 const double    d               (x.asDouble());
13372                 double                  i               (0.0);
13373                 const double    result  (deModf(d, &i));
13374
13375                 if (x.isInf() || x.isNaN())
13376                         return false;
13377
13378                 out[0] = fp16type(result).bits();
13379                 min[0] = getMin(result, getULPs(in));
13380                 max[0] = getMax(result, getULPs(in));
13381
13382                 return true;
13383         }
13384 };
13385
13386 struct fp16ModfInt : public fp16PerComponent
13387 {
13388         template<class fp16type>
13389         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13390         {
13391                 const fp16type  x               (*in[0]);
13392                 const double    d               (x.asDouble());
13393                 double                  i               (0.0);
13394                 const double    dummy   (deModf(d, &i));
13395                 const double    result  (i);
13396
13397                 DE_UNREF(dummy);
13398
13399                 if (x.isInf() || x.isNaN())
13400                         return false;
13401
13402                 out[0] = fp16type(result).bits();
13403                 min[0] = getMin(result, getULPs(in));
13404                 max[0] = getMax(result, getULPs(in));
13405
13406                 return true;
13407         }
13408 };
13409
13410 struct fp16FrexpS : public fp16PerComponent
13411 {
13412         template<class fp16type>
13413         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13414         {
13415                 const fp16type  x               (*in[0]);
13416                 const double    d               (x.asDouble());
13417                 int                             e               (0);
13418                 const double    result  (deFrExp(d, &e));
13419
13420                 if (x.isNaN() || x.isInf())
13421                         return false;
13422
13423                 out[0] = fp16type(result).bits();
13424                 min[0] = getMin(result, getULPs(in));
13425                 max[0] = getMax(result, getULPs(in));
13426
13427                 return true;
13428         }
13429 };
13430
13431 struct fp16FrexpE : public fp16PerComponent
13432 {
13433         template<class fp16type>
13434         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13435         {
13436                 const fp16type  x               (*in[0]);
13437                 const double    d               (x.asDouble());
13438                 int                             e               (0);
13439                 const double    dummy   (deFrExp(d, &e));
13440                 const double    result  (static_cast<double>(e));
13441
13442                 DE_UNREF(dummy);
13443
13444                 if (x.isNaN() || x.isInf())
13445                         return false;
13446
13447                 out[0] = fp16type(result).bits();
13448                 min[0] = getMin(result, getULPs(in));
13449                 max[0] = getMax(result, getULPs(in));
13450
13451                 return true;
13452         }
13453 };
13454
13455 struct fp16OpFAdd : public fp16PerComponent
13456 {
13457         template<class fp16type>
13458         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13459         {
13460                 const fp16type  x               (*in[0]);
13461                 const fp16type  y               (*in[1]);
13462                 const double    xd              (x.asDouble());
13463                 const double    yd              (y.asDouble());
13464                 const double    result  (xd + yd);
13465
13466                 out[0] = fp16type(result).bits();
13467                 min[0] = getMin(result, getULPs(in));
13468                 max[0] = getMax(result, getULPs(in));
13469
13470                 return true;
13471         }
13472 };
13473
13474 struct fp16OpFSub : public fp16PerComponent
13475 {
13476         template<class fp16type>
13477         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13478         {
13479                 const fp16type  x               (*in[0]);
13480                 const fp16type  y               (*in[1]);
13481                 const double    xd              (x.asDouble());
13482                 const double    yd              (y.asDouble());
13483                 const double    result  (xd - yd);
13484
13485                 out[0] = fp16type(result).bits();
13486                 min[0] = getMin(result, getULPs(in));
13487                 max[0] = getMax(result, getULPs(in));
13488
13489                 return true;
13490         }
13491 };
13492
13493 struct fp16OpFMul : public fp16PerComponent
13494 {
13495         template<class fp16type>
13496         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13497         {
13498                 const fp16type  x               (*in[0]);
13499                 const fp16type  y               (*in[1]);
13500                 const double    xd              (x.asDouble());
13501                 const double    yd              (y.asDouble());
13502                 const double    result  (xd * yd);
13503
13504                 out[0] = fp16type(result).bits();
13505                 min[0] = getMin(result, getULPs(in));
13506                 max[0] = getMax(result, getULPs(in));
13507
13508                 return true;
13509         }
13510 };
13511
13512 struct fp16OpFDiv : public fp16PerComponent
13513 {
13514         fp16OpFDiv() : fp16PerComponent()
13515         {
13516                 flavorNames.push_back("DirectDiv");
13517                 flavorNames.push_back("InverseDiv");
13518         }
13519
13520         template<class fp16type>
13521         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13522         {
13523                 const fp16type  x                       (*in[0]);
13524                 const fp16type  y                       (*in[1]);
13525                 const double    xd                      (x.asDouble());
13526                 const double    yd                      (y.asDouble());
13527                 const double    unspecUlp       (16.0);
13528                 const double    ulpCnt          (de::inRange(deAbs(yd), deLdExp(1, -14), deLdExp(1, 14)) ? 2.5 : unspecUlp);
13529                 double                  result          (0.0);
13530
13531                 if (y.isZero())
13532                         return false;
13533
13534                 if (getFlavor() == 0)
13535                 {
13536                         result = (xd / yd);
13537                 }
13538                 else if (getFlavor() == 1)
13539                 {
13540                         const double    invyd   (1.0 / yd);
13541                         const fp16type  invy    (invyd);
13542
13543                         result = (xd * invy.asDouble());
13544                 }
13545                 else
13546                 {
13547                         TCU_THROW(InternalError, "Unknown flavor");
13548                 }
13549
13550                 out[0] = fp16type(result).bits();
13551                 min[0] = getMin(result, ulpCnt);
13552                 max[0] = getMax(result, ulpCnt);
13553
13554                 return true;
13555         }
13556 };
13557
13558 struct fp16Atan2 : public fp16PerComponent
13559 {
13560         fp16Atan2() : fp16PerComponent()
13561         {
13562                 flavorNames.push_back("DoubleCalc");
13563                 flavorNames.push_back("DoubleCalc_PI");
13564         }
13565
13566         virtual double getULPs(vector<const deFloat16*>& in)
13567         {
13568                 DE_UNREF(in);
13569
13570                 return 2 * 5.0; // This is not a precision test. Value is not from spec
13571         }
13572
13573         template<class fp16type>
13574         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13575         {
13576                 const fp16type  x               (*in[0]);
13577                 const fp16type  y               (*in[1]);
13578                 const double    xd              (x.asDouble());
13579                 const double    yd              (y.asDouble());
13580                 double                  result  (0.0);
13581
13582                 if (x.isZero() && y.isZero())
13583                         return false;
13584
13585                 if (getFlavor() == 0)
13586                 {
13587                         result  = deAtan2(xd, yd);
13588                 }
13589                 else if (getFlavor() == 1)
13590                 {
13591                         const double    ulps    (2.0 * 5.0); // This is not a precision test. Value is not from spec
13592                         const double    eps             (floatFormat16.ulp(DE_PI_DOUBLE, ulps));
13593
13594                         result  = deAtan2(xd, yd);
13595
13596                         if (de::inRange(deAbs(result), DE_PI_DOUBLE - eps, DE_PI_DOUBLE + eps))
13597                                 result  = -result;
13598                 }
13599                 else
13600                 {
13601                         TCU_THROW(InternalError, "Unknown flavor");
13602                 }
13603
13604                 out[0] = fp16type(result).bits();
13605                 min[0] = getMin(result, getULPs(in));
13606                 max[0] = getMax(result, getULPs(in));
13607
13608                 return true;
13609         }
13610 };
13611
13612 struct fp16Pow : public fp16PerComponent
13613 {
13614         fp16Pow() : fp16PerComponent()
13615         {
13616                 flavorNames.push_back("Pow");
13617                 flavorNames.push_back("PowLog2");
13618                 flavorNames.push_back("PowLog2FP16");
13619         }
13620
13621         template<class fp16type>
13622         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13623         {
13624                 const fp16type  x               (*in[0]);
13625                 const fp16type  y               (*in[1]);
13626                 const double    xd              (x.asDouble());
13627                 const double    yd              (y.asDouble());
13628                 const double    logxeps (de::inRange(deAbs(xd), 0.5, 2.0) ? deLdExp(1.0, -7) : floatFormat16.ulp(deLog2(xd), 3.0));
13629                 const double    ulps1   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) - logxeps)));
13630                 const double    ulps2   (1.0 + 4.0 * deAbs(yd * (deLog2(xd) + logxeps)));
13631                 const double    ulps    (deMax(deAbs(ulps1), deAbs(ulps2)));
13632                 double                  result  (0.0);
13633
13634                 if (xd < 0.0)
13635                         return false;
13636
13637                 if (x.isZero() && yd <= 0.0)
13638                         return false;
13639
13640                 if (getFlavor() == 0)
13641                 {
13642                         result = dePow(xd, yd);
13643                 }
13644                 else if (getFlavor() == 1)
13645                 {
13646                         const double    l2d     (deLog2(xd));
13647                         const double    e2d     (deExp2(yd * l2d));
13648
13649                         result = e2d;
13650                 }
13651                 else if (getFlavor() == 2)
13652                 {
13653                         const double    l2d     (deLog2(xd));
13654                         const fp16type  l2      (l2d);
13655                         const double    e2d     (deExp2(yd * l2.asDouble()));
13656                         const fp16type  e2      (e2d);
13657
13658                         result = e2.asDouble();
13659                 }
13660                 else
13661                 {
13662                         TCU_THROW(InternalError, "Unknown flavor");
13663                 }
13664
13665                 out[0] = fp16type(result).bits();
13666                 min[0] = getMin(result, ulps);
13667                 max[0] = getMax(result, ulps);
13668
13669                 return true;
13670         }
13671 };
13672
13673 struct fp16FMin : public fp16PerComponent
13674 {
13675         template<class fp16type>
13676         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13677         {
13678                 const fp16type  x               (*in[0]);
13679                 const fp16type  y               (*in[1]);
13680                 const double    xd              (x.asDouble());
13681                 const double    yd              (y.asDouble());
13682                 const double    result  (deMin(xd, yd));
13683
13684                 if (x.isNaN() || y.isNaN())
13685                         return false;
13686
13687                 out[0] = fp16type(result).bits();
13688                 min[0] = getMin(result, getULPs(in));
13689                 max[0] = getMax(result, getULPs(in));
13690
13691                 return true;
13692         }
13693 };
13694
13695 struct fp16FMax : public fp16PerComponent
13696 {
13697         template<class fp16type>
13698         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13699         {
13700                 const fp16type  x               (*in[0]);
13701                 const fp16type  y               (*in[1]);
13702                 const double    xd              (x.asDouble());
13703                 const double    yd              (y.asDouble());
13704                 const double    result  (deMax(xd, yd));
13705
13706                 if (x.isNaN() || y.isNaN())
13707                         return false;
13708
13709                 out[0] = fp16type(result).bits();
13710                 min[0] = getMin(result, getULPs(in));
13711                 max[0] = getMax(result, getULPs(in));
13712
13713                 return true;
13714         }
13715 };
13716
13717 struct fp16Step : public fp16PerComponent
13718 {
13719         template<class fp16type>
13720         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13721         {
13722                 const fp16type  edge    (*in[0]);
13723                 const fp16type  x               (*in[1]);
13724                 const double    edged   (edge.asDouble());
13725                 const double    xd              (x.asDouble());
13726                 const double    result  (deStep(edged, xd));
13727
13728                 out[0] = fp16type(result).bits();
13729                 min[0] = getMin(result, getULPs(in));
13730                 max[0] = getMax(result, getULPs(in));
13731
13732                 return true;
13733         }
13734 };
13735
13736 struct fp16Ldexp : public fp16PerComponent
13737 {
13738         template<class fp16type>
13739         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13740         {
13741                 const fp16type  x               (*in[0]);
13742                 const fp16type  y               (*in[1]);
13743                 const double    xd              (x.asDouble());
13744                 const int               yd              (static_cast<int>(deTrunc(y.asDouble())));
13745                 const double    result  (deLdExp(xd, yd));
13746
13747                 if (y.isNaN() || y.isInf() || y.isDenorm() || yd < -14 || yd > 15)
13748                         return false;
13749
13750                 // Spec: "If this product is too large to be represented in the floating-point type, the result is undefined."
13751                 if (fp16type(result).isInf())
13752                         return false;
13753
13754                 out[0] = fp16type(result).bits();
13755                 min[0] = getMin(result, getULPs(in));
13756                 max[0] = getMax(result, getULPs(in));
13757
13758                 return true;
13759         }
13760 };
13761
13762 struct fp16FClamp : public fp16PerComponent
13763 {
13764         template<class fp16type>
13765         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13766         {
13767                 const fp16type  x               (*in[0]);
13768                 const fp16type  minVal  (*in[1]);
13769                 const fp16type  maxVal  (*in[2]);
13770                 const double    xd              (x.asDouble());
13771                 const double    minVald (minVal.asDouble());
13772                 const double    maxVald (maxVal.asDouble());
13773                 const double    result  (deClamp(xd, minVald, maxVald));
13774
13775                 if (minVal.isNaN() || maxVal.isNaN() || minVald > maxVald)
13776                         return false;
13777
13778                 out[0] = fp16type(result).bits();
13779                 min[0] = getMin(result, getULPs(in));
13780                 max[0] = getMax(result, getULPs(in));
13781
13782                 return true;
13783         }
13784 };
13785
13786 struct fp16FMix : public fp16PerComponent
13787 {
13788         fp16FMix() : fp16PerComponent()
13789         {
13790                 flavorNames.push_back("DoubleCalc");
13791                 flavorNames.push_back("EmulatingFP16");
13792                 flavorNames.push_back("EmulatingFP16YminusX");
13793         }
13794
13795         template<class fp16type>
13796         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13797         {
13798                 const fp16type  x               (*in[0]);
13799                 const fp16type  y               (*in[1]);
13800                 const fp16type  a               (*in[2]);
13801                 const double    ulps    (8.0); // This is not a precision test. Value is not from spec
13802                 double                  result  (0.0);
13803
13804                 if (getFlavor() == 0)
13805                 {
13806                         const double    xd              (x.asDouble());
13807                         const double    yd              (y.asDouble());
13808                         const double    ad              (a.asDouble());
13809                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13810                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13811                         const double    eps             (xeps + yeps);
13812
13813                         result = deMix(xd, yd, ad);
13814                         min[0] = result - eps;
13815                         max[0] = result + eps;
13816                 }
13817                 else if (getFlavor() == 1)
13818                 {
13819                         const double    xd              (x.asDouble());
13820                         const double    yd              (y.asDouble());
13821                         const double    ad              (a.asDouble());
13822                         const fp16type  am              (1.0 - ad);
13823                         const double    amd             (am.asDouble());
13824                         const fp16type  xam             (xd * amd);
13825                         const double    xamd    (xam.asDouble());
13826                         const fp16type  ya              (yd * ad);
13827                         const double    yad             (ya.asDouble());
13828                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13829                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13830                         const double    eps             (xeps + yeps);
13831
13832                         result = xamd + yad;
13833                         min[0] = result - eps;
13834                         max[0] = result + eps;
13835                 }
13836                 else if (getFlavor() == 2)
13837                 {
13838                         const double    xd              (x.asDouble());
13839                         const double    yd              (y.asDouble());
13840                         const double    ad              (a.asDouble());
13841                         const fp16type  ymx             (yd - xd);
13842                         const double    ymxd    (ymx.asDouble());
13843                         const fp16type  ymxa    (ymxd * ad);
13844                         const double    ymxad   (ymxa.asDouble());
13845                         const double    xeps    (floatFormat16.ulp(deAbs(xd * (1.0 - ad)), ulps));
13846                         const double    yeps    (floatFormat16.ulp(deAbs(yd * ad), ulps));
13847                         const double    eps             (xeps + yeps);
13848
13849                         result = xd + ymxad;
13850                         min[0] = result - eps;
13851                         max[0] = result + eps;
13852                 }
13853                 else
13854                 {
13855                         TCU_THROW(InternalError, "Unknown flavor");
13856                 }
13857
13858                 out[0] = fp16type(result).bits();
13859
13860                 return true;
13861         }
13862 };
13863
13864 struct fp16SmoothStep : public fp16PerComponent
13865 {
13866         fp16SmoothStep() : fp16PerComponent()
13867         {
13868                 flavorNames.push_back("FloatCalc");
13869                 flavorNames.push_back("EmulatingFP16");
13870                 flavorNames.push_back("EmulatingFP16WClamp");
13871         }
13872
13873         virtual double getULPs(vector<const deFloat16*>& in)
13874         {
13875                 DE_UNREF(in);
13876
13877                 return 4.0; // This is not a precision test. Value is not from spec
13878         }
13879
13880         template<class fp16type>
13881         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13882         {
13883                 const fp16type  edge0   (*in[0]);
13884                 const fp16type  edge1   (*in[1]);
13885                 const fp16type  x               (*in[2]);
13886                 double                  result  (0.0);
13887
13888                 if (edge0.isNaN() || edge1.isNaN() || x.isNaN() || edge0.asDouble() >= edge1.asDouble())
13889                         return false;
13890
13891                 if (edge0.isInf() || edge1.isInf() || x.isInf())
13892                         return false;
13893
13894                 if (getFlavor() == 0)
13895                 {
13896                         const float     edge0d  (edge0.asFloat());
13897                         const float     edge1d  (edge1.asFloat());
13898                         const float     xd              (x.asFloat());
13899                         const float     sstep   (deFloatSmoothStep(edge0d, edge1d, xd));
13900
13901                         result = sstep;
13902                 }
13903                 else if (getFlavor() == 1)
13904                 {
13905                         const double    edge0d  (edge0.asDouble());
13906                         const double    edge1d  (edge1.asDouble());
13907                         const double    xd              (x.asDouble());
13908
13909                         if (xd <= edge0d)
13910                                 result = 0.0;
13911                         else if (xd >= edge1d)
13912                                 result = 1.0;
13913                         else
13914                         {
13915                                 const fp16type  a       (xd - edge0d);
13916                                 const fp16type  b       (edge1d - edge0d);
13917                                 const fp16type  t       (a.asDouble() / b.asDouble());
13918                                 const fp16type  t2      (2.0 * t.asDouble());
13919                                 const fp16type  t3      (3.0 - t2.asDouble());
13920                                 const fp16type  t4      (t.asDouble() * t3.asDouble());
13921                                 const fp16type  t5      (t.asDouble() * t4.asDouble());
13922
13923                                 result = t5.asDouble();
13924                         }
13925                 }
13926                 else if (getFlavor() == 2)
13927                 {
13928                         const double    edge0d  (edge0.asDouble());
13929                         const double    edge1d  (edge1.asDouble());
13930                         const double    xd              (x.asDouble());
13931                         const fp16type  a       (xd - edge0d);
13932                         const fp16type  b       (edge1d - edge0d);
13933                         const fp16type  bi      (1.0 / b.asDouble());
13934                         const fp16type  t0      (a.asDouble() * bi.asDouble());
13935                         const double    tc      (deClamp(t0.asDouble(), 0.0, 1.0));
13936                         const fp16type  t       (tc);
13937                         const fp16type  t2      (2.0 * t.asDouble());
13938                         const fp16type  t3      (3.0 - t2.asDouble());
13939                         const fp16type  t4      (t.asDouble() * t3.asDouble());
13940                         const fp16type  t5      (t.asDouble() * t4.asDouble());
13941
13942                         result = t5.asDouble();
13943                 }
13944                 else
13945                 {
13946                         TCU_THROW(InternalError, "Unknown flavor");
13947                 }
13948
13949                 out[0] = fp16type(result).bits();
13950                 min[0] = getMin(result, getULPs(in));
13951                 max[0] = getMax(result, getULPs(in));
13952
13953                 return true;
13954         }
13955 };
13956
13957 struct fp16Fma : public fp16PerComponent
13958 {
13959         fp16Fma()
13960         {
13961                 flavorNames.push_back("DoubleCalc");
13962                 flavorNames.push_back("EmulatingFP16");
13963         }
13964
13965         virtual double getULPs(vector<const deFloat16*>& in)
13966         {
13967                 DE_UNREF(in);
13968
13969                 return 16.0;
13970         }
13971
13972         template<class fp16type>
13973         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
13974         {
13975                 DE_ASSERT(in.size() == 3);
13976                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
13977                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
13978                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
13979                 DE_ASSERT(getOutCompCount() > 0);
13980
13981                 const fp16type  a               (*in[0]);
13982                 const fp16type  b               (*in[1]);
13983                 const fp16type  c               (*in[2]);
13984                 double                  result  (0.0);
13985
13986                 if (getFlavor() == 0)
13987                 {
13988                         const double    ad      (a.asDouble());
13989                         const double    bd      (b.asDouble());
13990                         const double    cd      (c.asDouble());
13991
13992                         result  = deMadd(ad, bd, cd);
13993                 }
13994                 else if (getFlavor() == 1)
13995                 {
13996                         const double    ad      (a.asDouble());
13997                         const double    bd      (b.asDouble());
13998                         const double    cd      (c.asDouble());
13999                         const fp16type  ab      (ad * bd);
14000                         const fp16type  r       (ab.asDouble() + cd);
14001
14002                         result  = r.asDouble();
14003                 }
14004                 else
14005                 {
14006                         TCU_THROW(InternalError, "Unknown flavor");
14007                 }
14008
14009                 out[0] = fp16type(result).bits();
14010                 min[0] = getMin(result, getULPs(in));
14011                 max[0] = getMax(result, getULPs(in));
14012
14013                 return true;
14014         }
14015 };
14016
14017
14018 struct fp16AllComponents : public fp16PerComponent
14019 {
14020         bool            callOncePerComponent    ()      { return false; }
14021 };
14022
14023 struct fp16Length : public fp16AllComponents
14024 {
14025         fp16Length() : fp16AllComponents()
14026         {
14027                 flavorNames.push_back("EmulatingFP16");
14028                 flavorNames.push_back("DoubleCalc");
14029         }
14030
14031         virtual double getULPs(vector<const deFloat16*>& in)
14032         {
14033                 DE_UNREF(in);
14034
14035                 return 4.0;
14036         }
14037
14038         template<class fp16type>
14039         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14040         {
14041                 DE_ASSERT(getOutCompCount() == 1);
14042                 DE_ASSERT(in.size() == 1);
14043
14044                 double  result  (0.0);
14045
14046                 if (getFlavor() == 0)
14047                 {
14048                         fp16type        r       (0.0);
14049
14050                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14051                         {
14052                                 const fp16type  x       (in[0][componentNdx]);
14053                                 const fp16type  q       (x.asDouble() * x.asDouble());
14054
14055                                 r = fp16type(r.asDouble() + q.asDouble());
14056                         }
14057
14058                         result = deSqrt(r.asDouble());
14059
14060                         out[0] = fp16type(result).bits();
14061                 }
14062                 else if (getFlavor() == 1)
14063                 {
14064                         double  r       (0.0);
14065
14066                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14067                         {
14068                                 const fp16type  x       (in[0][componentNdx]);
14069                                 const double    q       (x.asDouble() * x.asDouble());
14070
14071                                 r += q;
14072                         }
14073
14074                         result = deSqrt(r);
14075
14076                         out[0] = fp16type(result).bits();
14077                 }
14078                 else
14079                 {
14080                         TCU_THROW(InternalError, "Unknown flavor");
14081                 }
14082
14083                 min[0] = getMin(result, getULPs(in));
14084                 max[0] = getMax(result, getULPs(in));
14085
14086                 return true;
14087         }
14088 };
14089
14090 struct fp16Distance : public fp16AllComponents
14091 {
14092         fp16Distance() : fp16AllComponents()
14093         {
14094                 flavorNames.push_back("EmulatingFP16");
14095                 flavorNames.push_back("DoubleCalc");
14096         }
14097
14098         virtual double getULPs(vector<const deFloat16*>& in)
14099         {
14100                 DE_UNREF(in);
14101
14102                 return 4.0;
14103         }
14104
14105         template<class fp16type>
14106         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14107         {
14108                 DE_ASSERT(getOutCompCount() == 1);
14109                 DE_ASSERT(in.size() == 2);
14110                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
14111
14112                 double  result  (0.0);
14113
14114                 if (getFlavor() == 0)
14115                 {
14116                         fp16type        r       (0.0);
14117
14118                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14119                         {
14120                                 const fp16type  x       (in[0][componentNdx]);
14121                                 const fp16type  y       (in[1][componentNdx]);
14122                                 const fp16type  d       (x.asDouble() - y.asDouble());
14123                                 const fp16type  q       (d.asDouble() * d.asDouble());
14124
14125                                 r = fp16type(r.asDouble() + q.asDouble());
14126                         }
14127
14128                         result = deSqrt(r.asDouble());
14129                 }
14130                 else if (getFlavor() == 1)
14131                 {
14132                         double  r       (0.0);
14133
14134                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14135                         {
14136                                 const fp16type  x       (in[0][componentNdx]);
14137                                 const fp16type  y       (in[1][componentNdx]);
14138                                 const double    d       (x.asDouble() - y.asDouble());
14139                                 const double    q       (d * d);
14140
14141                                 r += q;
14142                         }
14143
14144                         result = deSqrt(r);
14145                 }
14146                 else
14147                 {
14148                         TCU_THROW(InternalError, "Unknown flavor");
14149                 }
14150
14151                 out[0] = fp16type(result).bits();
14152                 min[0] = getMin(result, getULPs(in));
14153                 max[0] = getMax(result, getULPs(in));
14154
14155                 return true;
14156         }
14157 };
14158
14159 struct fp16Cross : public fp16AllComponents
14160 {
14161         fp16Cross() : fp16AllComponents()
14162         {
14163                 flavorNames.push_back("EmulatingFP16");
14164                 flavorNames.push_back("DoubleCalc");
14165         }
14166
14167         virtual double getULPs(vector<const deFloat16*>& in)
14168         {
14169                 DE_UNREF(in);
14170
14171                 return 4.0;
14172         }
14173
14174         template<class fp16type>
14175         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14176         {
14177                 DE_ASSERT(getOutCompCount() == 3);
14178                 DE_ASSERT(in.size() == 2);
14179                 DE_ASSERT(getArgCompCount(0) == 3);
14180                 DE_ASSERT(getArgCompCount(1) == 3);
14181
14182                 if (getFlavor() == 0)
14183                 {
14184                         const fp16type  x0              (in[0][0]);
14185                         const fp16type  x1              (in[0][1]);
14186                         const fp16type  x2              (in[0][2]);
14187                         const fp16type  y0              (in[1][0]);
14188                         const fp16type  y1              (in[1][1]);
14189                         const fp16type  y2              (in[1][2]);
14190                         const fp16type  x1y2    (x1.asDouble() * y2.asDouble());
14191                         const fp16type  y1x2    (y1.asDouble() * x2.asDouble());
14192                         const fp16type  x2y0    (x2.asDouble() * y0.asDouble());
14193                         const fp16type  y2x0    (y2.asDouble() * x0.asDouble());
14194                         const fp16type  x0y1    (x0.asDouble() * y1.asDouble());
14195                         const fp16type  y0x1    (y0.asDouble() * x1.asDouble());
14196
14197                         out[0] = fp16type(x1y2.asDouble() - y1x2.asDouble()).bits();
14198                         out[1] = fp16type(x2y0.asDouble() - y2x0.asDouble()).bits();
14199                         out[2] = fp16type(x0y1.asDouble() - y0x1.asDouble()).bits();
14200                 }
14201                 else if (getFlavor() == 1)
14202                 {
14203                         const fp16type  x0              (in[0][0]);
14204                         const fp16type  x1              (in[0][1]);
14205                         const fp16type  x2              (in[0][2]);
14206                         const fp16type  y0              (in[1][0]);
14207                         const fp16type  y1              (in[1][1]);
14208                         const fp16type  y2              (in[1][2]);
14209                         const double    x1y2    (x1.asDouble() * y2.asDouble());
14210                         const double    y1x2    (y1.asDouble() * x2.asDouble());
14211                         const double    x2y0    (x2.asDouble() * y0.asDouble());
14212                         const double    y2x0    (y2.asDouble() * x0.asDouble());
14213                         const double    x0y1    (x0.asDouble() * y1.asDouble());
14214                         const double    y0x1    (y0.asDouble() * x1.asDouble());
14215
14216                         out[0] = fp16type(x1y2 - y1x2).bits();
14217                         out[1] = fp16type(x2y0 - y2x0).bits();
14218                         out[2] = fp16type(x0y1 - y0x1).bits();
14219                 }
14220                 else
14221                 {
14222                         TCU_THROW(InternalError, "Unknown flavor");
14223                 }
14224
14225                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14226                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14227                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14228                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14229
14230                 return true;
14231         }
14232 };
14233
14234 struct fp16Normalize : public fp16AllComponents
14235 {
14236         fp16Normalize() : fp16AllComponents()
14237         {
14238                 flavorNames.push_back("EmulatingFP16");
14239                 flavorNames.push_back("DoubleCalc");
14240
14241                 // flavorNames will be extended later
14242         }
14243
14244         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14245         {
14246                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14247
14248                 if (argNo == 0 && argCompCount[argNo] == 0)
14249                 {
14250                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14251                         std::vector<int>        indices;
14252
14253                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14254                                 indices.push_back(static_cast<int>(componentNdx));
14255
14256                         m_permutations.reserve(maxPermutationsCount);
14257
14258                         permutationsFlavorStart = flavorNames.size();
14259
14260                         do
14261                         {
14262                                 tcu::UVec4      permutation;
14263                                 std::string     name            = "Permutted_";
14264
14265                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14266                                 {
14267                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14268                                         name += de::toString(indices[componentNdx]);
14269                                 }
14270
14271                                 m_permutations.push_back(permutation);
14272                                 flavorNames.push_back(name);
14273
14274                         } while(std::next_permutation(indices.begin(), indices.end()));
14275
14276                         permutationsFlavorEnd = flavorNames.size();
14277                 }
14278
14279                 fp16AllComponents::setArgCompCount(argNo, compCount);
14280         }
14281         virtual double getULPs(vector<const deFloat16*>& in)
14282         {
14283                 DE_UNREF(in);
14284
14285                 return 8.0;
14286         }
14287
14288         template<class fp16type>
14289         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14290         {
14291                 DE_ASSERT(in.size() == 1);
14292                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14293
14294                 if (getFlavor() == 0)
14295                 {
14296                         fp16type        r(0.0);
14297
14298                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14299                         {
14300                                 const fp16type  x       (in[0][componentNdx]);
14301                                 const fp16type  q       (x.asDouble() * x.asDouble());
14302
14303                                 r = fp16type(r.asDouble() + q.asDouble());
14304                         }
14305
14306                         r = fp16type(deSqrt(r.asDouble()));
14307
14308                         if (r.isZero())
14309                                 return false;
14310
14311                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14312                         {
14313                                 const fp16type  x       (in[0][componentNdx]);
14314
14315                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14316                         }
14317                 }
14318                 else if (getFlavor() == 1)
14319                 {
14320                         double  r(0.0);
14321
14322                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14323                         {
14324                                 const fp16type  x       (in[0][componentNdx]);
14325                                 const double    q       (x.asDouble() * x.asDouble());
14326
14327                                 r += q;
14328                         }
14329
14330                         r = deSqrt(r);
14331
14332                         if (r == 0)
14333                                 return false;
14334
14335                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14336                         {
14337                                 const fp16type  x       (in[0][componentNdx]);
14338
14339                                 out[componentNdx] = fp16type(x.asDouble() / r).bits();
14340                         }
14341                 }
14342                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14343                 {
14344                         const int                       compCount               (static_cast<int>(getArgCompCount(0)));
14345                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14346                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14347                         fp16type                        r                               (0.0);
14348
14349                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14350                         {
14351                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14352                                 const fp16type  x                               (in[0][componentNdx]);
14353                                 const fp16type  q                               (x.asDouble() * x.asDouble());
14354
14355                                 r = fp16type(r.asDouble() + q.asDouble());
14356                         }
14357
14358                         r = fp16type(deSqrt(r.asDouble()));
14359
14360                         if (r.isZero())
14361                                 return false;
14362
14363                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14364                         {
14365                                 const size_t    componentNdx    (permutation[permComponentNdx]);
14366                                 const fp16type  x                               (in[0][componentNdx]);
14367
14368                                 out[componentNdx] = fp16type(x.asDouble() / r.asDouble()).bits();
14369                         }
14370                 }
14371                 else
14372                 {
14373                         TCU_THROW(InternalError, "Unknown flavor");
14374                 }
14375
14376                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14377                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14378                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14379                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14380
14381                 return true;
14382         }
14383
14384 private:
14385         std::vector<tcu::UVec4> m_permutations;
14386         size_t                                  permutationsFlavorStart;
14387         size_t                                  permutationsFlavorEnd;
14388 };
14389
14390 struct fp16FaceForward : public fp16AllComponents
14391 {
14392         virtual double getULPs(vector<const deFloat16*>& in)
14393         {
14394                 DE_UNREF(in);
14395
14396                 return 4.0;
14397         }
14398
14399         template<class fp16type>
14400         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14401         {
14402                 DE_ASSERT(in.size() == 3);
14403                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14404                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14405                 DE_ASSERT(getArgCompCount(2) == getOutCompCount());
14406
14407                 fp16type        dp(0.0);
14408
14409                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14410                 {
14411                         const fp16type  x       (in[1][componentNdx]);
14412                         const fp16type  y       (in[2][componentNdx]);
14413                         const double    xd      (x.asDouble());
14414                         const double    yd      (y.asDouble());
14415                         const fp16type  q       (xd * yd);
14416
14417                         dp = fp16type(dp.asDouble() + q.asDouble());
14418                 }
14419
14420                 if (dp.isNaN() || dp.isZero())
14421                         return false;
14422
14423                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14424                 {
14425                         const fp16type  n       (in[0][componentNdx]);
14426
14427                         out[componentNdx] = (dp.signBit() == 1) ? n.bits() : fp16type(-n.asDouble()).bits();
14428                 }
14429
14430                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14431                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14432                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14433                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14434
14435                 return true;
14436         }
14437 };
14438
14439 struct fp16Reflect : public fp16AllComponents
14440 {
14441         fp16Reflect() : fp16AllComponents()
14442         {
14443                 flavorNames.push_back("EmulatingFP16");
14444                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14445                 flavorNames.push_back("FloatCalc");
14446                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14447                 flavorNames.push_back("EmulatingFP16+2Nfirst");
14448                 flavorNames.push_back("EmulatingFP16+2Ifirst");
14449         }
14450
14451         virtual double getULPs(vector<const deFloat16*>& in)
14452         {
14453                 DE_UNREF(in);
14454
14455                 return 256.0; // This is not a precision test. Value is not from spec
14456         }
14457
14458         template<class fp16type>
14459         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14460         {
14461                 DE_ASSERT(in.size() == 2);
14462                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14463                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14464
14465                 if (getFlavor() < 4)
14466                 {
14467                         const bool      keepZeroSign    ((flavor & 1) != 0 ? true : false);
14468                         const bool      floatCalc               ((flavor & 2) != 0 ? true : false);
14469
14470                         if (floatCalc)
14471                         {
14472                                 float   dp(0.0f);
14473
14474                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14475                                 {
14476                                         const fp16type  i       (in[0][componentNdx]);
14477                                         const fp16type  n       (in[1][componentNdx]);
14478                                         const float             id      (i.asFloat());
14479                                         const float             nd      (n.asFloat());
14480                                         const float             qd      (id * nd);
14481
14482                                         if (keepZeroSign)
14483                                                 dp = (componentNdx == 0) ? qd : dp + qd;
14484                                         else
14485                                                 dp = dp + qd;
14486                                 }
14487
14488                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14489                                 {
14490                                         const fp16type  i               (in[0][componentNdx]);
14491                                         const fp16type  n               (in[1][componentNdx]);
14492                                         const float             dpnd    (dp * n.asFloat());
14493                                         const float             dpn2d   (2.0f * dpnd);
14494                                         const float             idpn2d  (i.asFloat() - dpn2d);
14495                                         const fp16type  result  (idpn2d);
14496
14497                                         out[componentNdx] = result.bits();
14498                                 }
14499                         }
14500                         else
14501                         {
14502                                 fp16type        dp(0.0);
14503
14504                                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14505                                 {
14506                                         const fp16type  i       (in[0][componentNdx]);
14507                                         const fp16type  n       (in[1][componentNdx]);
14508                                         const double    id      (i.asDouble());
14509                                         const double    nd      (n.asDouble());
14510                                         const fp16type  q       (id * nd);
14511
14512                                         if (keepZeroSign)
14513                                                 dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14514                                         else
14515                                                 dp = fp16type(dp.asDouble() + q.asDouble());
14516                                 }
14517
14518                                 if (dp.isNaN())
14519                                         return false;
14520
14521                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14522                                 {
14523                                         const fp16type  i               (in[0][componentNdx]);
14524                                         const fp16type  n               (in[1][componentNdx]);
14525                                         const fp16type  dpn             (dp.asDouble() * n.asDouble());
14526                                         const fp16type  dpn2    (2 * dpn.asDouble());
14527                                         const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14528
14529                                         out[componentNdx] = idpn2.bits();
14530                                 }
14531                         }
14532                 }
14533                 else if (getFlavor() == 4)
14534                 {
14535                         fp16type        dp(0.0);
14536
14537                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14538                         {
14539                                 const fp16type  i       (in[0][componentNdx]);
14540                                 const fp16type  n       (in[1][componentNdx]);
14541                                 const double    id      (i.asDouble());
14542                                 const double    nd      (n.asDouble());
14543                                 const fp16type  q       (id * nd);
14544
14545                                 dp = fp16type(dp.asDouble() + q.asDouble());
14546                         }
14547
14548                         if (dp.isNaN())
14549                                 return false;
14550
14551                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14552                         {
14553                                 const fp16type  i               (in[0][componentNdx]);
14554                                 const fp16type  n               (in[1][componentNdx]);
14555                                 const fp16type  n2              (2 * n.asDouble());
14556                                 const fp16type  dpn2    (dp.asDouble() * n2.asDouble());
14557                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14558
14559                                 out[componentNdx] = idpn2.bits();
14560                         }
14561                 }
14562                 else if (getFlavor() == 5)
14563                 {
14564                         fp16type        dp2(0.0);
14565
14566                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14567                         {
14568                                 const fp16type  i       (in[0][componentNdx]);
14569                                 const fp16type  n       (in[1][componentNdx]);
14570                                 const fp16type  i2      (2.0 * i.asDouble());
14571                                 const double    i2d     (i2.asDouble());
14572                                 const double    nd      (n.asDouble());
14573                                 const fp16type  q       (i2d * nd);
14574
14575                                 dp2 = fp16type(dp2.asDouble() + q.asDouble());
14576                         }
14577
14578                         if (dp2.isNaN())
14579                                 return false;
14580
14581                         for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14582                         {
14583                                 const fp16type  i               (in[0][componentNdx]);
14584                                 const fp16type  n               (in[1][componentNdx]);
14585                                 const fp16type  dpn2    (dp2.asDouble() * n.asDouble());
14586                                 const fp16type  idpn2   (i.asDouble() - dpn2.asDouble());
14587
14588                                 out[componentNdx] = idpn2.bits();
14589                         }
14590                 }
14591                 else
14592                 {
14593                         TCU_THROW(InternalError, "Unknown flavor");
14594                 }
14595
14596                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14597                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14598                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14599                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14600
14601                 return true;
14602         }
14603 };
14604
14605 struct fp16Refract : public fp16AllComponents
14606 {
14607         fp16Refract() : fp16AllComponents()
14608         {
14609                 flavorNames.push_back("EmulatingFP16");
14610                 flavorNames.push_back("EmulatingFP16+KeepZeroSign");
14611                 flavorNames.push_back("FloatCalc");
14612                 flavorNames.push_back("FloatCalc+KeepZeroSign");
14613         }
14614
14615         virtual double getULPs(vector<const deFloat16*>& in)
14616         {
14617                 DE_UNREF(in);
14618
14619                 return 8192.0; // This is not a precision test. Value is not from spec
14620         }
14621
14622         template<class fp16type>
14623         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14624         {
14625                 DE_ASSERT(in.size() == 3);
14626                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14627                 DE_ASSERT(getArgCompCount(1) == getOutCompCount());
14628                 DE_ASSERT(getArgCompCount(2) == 1);
14629
14630                 const bool              keepZeroSign    ((flavor & 1) != 0 ? true : false);
14631                 const bool              doubleCalc              ((flavor & 2) != 0 ? true : false);
14632                 const fp16type  eta                             (*in[2]);
14633
14634                 if (doubleCalc)
14635                 {
14636                         double  dp      (0.0);
14637
14638                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14639                         {
14640                                 const fp16type  i       (in[0][componentNdx]);
14641                                 const fp16type  n       (in[1][componentNdx]);
14642                                 const double    id      (i.asDouble());
14643                                 const double    nd      (n.asDouble());
14644                                 const double    qd      (id * nd);
14645
14646                                 if (keepZeroSign)
14647                                         dp = (componentNdx == 0) ? qd : dp + qd;
14648                                 else
14649                                         dp = dp + qd;
14650                         }
14651
14652                         const double    eta2    (eta.asDouble() * eta.asDouble());
14653                         const double    dp2             (dp * dp);
14654                         const double    dp1             (1.0 - dp2);
14655                         const double    dpe             (eta2 * dp1);
14656                         const double    k               (1.0 - dpe);
14657
14658                         if (k < 0.0)
14659                         {
14660                                 const fp16type  zero    (0.0);
14661
14662                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14663                                         out[componentNdx] = zero.bits();
14664                         }
14665                         else
14666                         {
14667                                 const double    sk      (deSqrt(k));
14668
14669                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14670                                 {
14671                                         const fp16type  i               (in[0][componentNdx]);
14672                                         const fp16type  n               (in[1][componentNdx]);
14673                                         const double    etai    (i.asDouble() * eta.asDouble());
14674                                         const double    etadp   (eta.asDouble() * dp);
14675                                         const double    etadpk  (etadp + sk);
14676                                         const double    etadpkn (etadpk * n.asDouble());
14677                                         const double    full    (etai - etadpkn);
14678                                         const fp16type  result  (full);
14679
14680                                         if (result.isInf())
14681                                                 return false;
14682
14683                                         out[componentNdx] = result.bits();
14684                                 }
14685                         }
14686                 }
14687                 else
14688                 {
14689                         fp16type        dp      (0.0);
14690
14691                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14692                         {
14693                                 const fp16type  i       (in[0][componentNdx]);
14694                                 const fp16type  n       (in[1][componentNdx]);
14695                                 const double    id      (i.asDouble());
14696                                 const double    nd      (n.asDouble());
14697                                 const fp16type  q       (id * nd);
14698
14699                                 if (keepZeroSign)
14700                                         dp = (componentNdx == 0) ? q : fp16type(dp.asDouble() + q.asDouble());
14701                                 else
14702                                         dp = fp16type(dp.asDouble() + q.asDouble());
14703                         }
14704
14705                         if (dp.isNaN())
14706                                 return false;
14707
14708                         const fp16type  eta2(eta.asDouble() * eta.asDouble());
14709                         const fp16type  dp2     (dp.asDouble() * dp.asDouble());
14710                         const fp16type  dp1     (1.0 - dp2.asDouble());
14711                         const fp16type  dpe     (eta2.asDouble() * dp1.asDouble());
14712                         const fp16type  k       (1.0 - dpe.asDouble());
14713
14714                         if (k.asDouble() < 0.0)
14715                         {
14716                                 const fp16type  zero    (0.0);
14717
14718                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14719                                         out[componentNdx] = zero.bits();
14720                         }
14721                         else
14722                         {
14723                                 const fp16type  sk      (deSqrt(k.asDouble()));
14724
14725                                 for (size_t componentNdx = 0; componentNdx < getOutCompCount(); ++componentNdx)
14726                                 {
14727                                         const fp16type  i               (in[0][componentNdx]);
14728                                         const fp16type  n               (in[1][componentNdx]);
14729                                         const fp16type  etai    (i.asDouble() * eta.asDouble());
14730                                         const fp16type  etadp   (eta.asDouble() * dp.asDouble());
14731                                         const fp16type  etadpk  (etadp.asDouble() + sk.asDouble());
14732                                         const fp16type  etadpkn (etadpk.asDouble() * n.asDouble());
14733                                         const fp16type  full    (etai.asDouble() - etadpkn.asDouble());
14734
14735                                         if (full.isNaN() || full.isInf())
14736                                                 return false;
14737
14738                                         out[componentNdx] = full.bits();
14739                                 }
14740                         }
14741                 }
14742
14743                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14744                         min[ndx] = getMin(fp16type(out[ndx]).asDouble(), getULPs(in));
14745                 for (size_t ndx = 0; ndx < getOutCompCount(); ++ndx)
14746                         max[ndx] = getMax(fp16type(out[ndx]).asDouble(), getULPs(in));
14747
14748                 return true;
14749         }
14750 };
14751
14752 struct fp16Dot : public fp16AllComponents
14753 {
14754         fp16Dot() : fp16AllComponents()
14755         {
14756                 flavorNames.push_back("EmulatingFP16");
14757                 flavorNames.push_back("FloatCalc");
14758                 flavorNames.push_back("DoubleCalc");
14759
14760                 // flavorNames will be extended later
14761         }
14762
14763         virtual void    setArgCompCount                 (size_t argNo, size_t compCount)
14764         {
14765                 DE_ASSERT(argCompCount[argNo] == 0); // Once only
14766
14767                 if (argNo == 0 && argCompCount[argNo] == 0)
14768                 {
14769                         const size_t            maxPermutationsCount    = 24u; // Equal to 4!
14770                         std::vector<int>        indices;
14771
14772                         for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14773                                 indices.push_back(static_cast<int>(componentNdx));
14774
14775                         m_permutations.reserve(maxPermutationsCount);
14776
14777                         permutationsFlavorStart = flavorNames.size();
14778
14779                         do
14780                         {
14781                                 tcu::UVec4      permutation;
14782                                 std::string     name            = "Permutted_";
14783
14784                                 for (size_t componentNdx = 0; componentNdx < compCount; ++componentNdx)
14785                                 {
14786                                         permutation[static_cast<int>(componentNdx)] = indices[componentNdx];
14787                                         name += de::toString(indices[componentNdx]);
14788                                 }
14789
14790                                 m_permutations.push_back(permutation);
14791                                 flavorNames.push_back(name);
14792
14793                         } while(std::next_permutation(indices.begin(), indices.end()));
14794
14795                         permutationsFlavorEnd = flavorNames.size();
14796                 }
14797
14798                 fp16AllComponents::setArgCompCount(argNo, compCount);
14799         }
14800
14801         virtual double  getULPs(vector<const deFloat16*>& in)
14802         {
14803                 DE_UNREF(in);
14804
14805                 return 16.0; // This is not a precision test. Value is not from spec
14806         }
14807
14808         template<class fp16type>
14809         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14810         {
14811                 DE_ASSERT(in.size() == 2);
14812                 DE_ASSERT(getArgCompCount(0) == getArgCompCount(1));
14813                 DE_ASSERT(getOutCompCount() == 1);
14814
14815                 double  result  (0.0);
14816                 double  eps             (0.0);
14817
14818                 if (getFlavor() == 0)
14819                 {
14820                         fp16type        dp      (0.0);
14821
14822                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14823                         {
14824                                 const fp16type  x       (in[0][componentNdx]);
14825                                 const fp16type  y       (in[1][componentNdx]);
14826                                 const fp16type  q       (x.asDouble() * y.asDouble());
14827
14828                                 dp = fp16type(dp.asDouble() + q.asDouble());
14829                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14830                         }
14831
14832                         result = dp.asDouble();
14833                 }
14834                 else if (getFlavor() == 1)
14835                 {
14836                         float   dp      (0.0);
14837
14838                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14839                         {
14840                                 const fp16type  x       (in[0][componentNdx]);
14841                                 const fp16type  y       (in[1][componentNdx]);
14842                                 const float             q       (x.asFloat() * y.asFloat());
14843
14844                                 dp += q;
14845                                 eps += floatFormat16.ulp(static_cast<double>(q), 2.0);
14846                         }
14847
14848                         result = dp;
14849                 }
14850                 else if (getFlavor() == 2)
14851                 {
14852                         double  dp      (0.0);
14853
14854                         for (size_t componentNdx = 0; componentNdx < getArgCompCount(1); ++componentNdx)
14855                         {
14856                                 const fp16type  x       (in[0][componentNdx]);
14857                                 const fp16type  y       (in[1][componentNdx]);
14858                                 const double    q       (x.asDouble() * y.asDouble());
14859
14860                                 dp += q;
14861                                 eps += floatFormat16.ulp(q, 2.0);
14862                         }
14863
14864                         result = dp;
14865                 }
14866                 else if (de::inBounds<size_t>(getFlavor(), permutationsFlavorStart, permutationsFlavorEnd))
14867                 {
14868                         const int                       compCount               (static_cast<int>(getArgCompCount(1)));
14869                         const size_t            permutationNdx  (getFlavor() - permutationsFlavorStart);
14870                         const tcu::UVec4&       permutation             (m_permutations[permutationNdx]);
14871                         fp16type                        dp                              (0.0);
14872
14873                         for (int permComponentNdx = 0; permComponentNdx < compCount; ++permComponentNdx)
14874                         {
14875                                 const size_t            componentNdx    (permutation[permComponentNdx]);
14876                                 const fp16type          x                               (in[0][componentNdx]);
14877                                 const fp16type          y                               (in[1][componentNdx]);
14878                                 const fp16type          q                               (x.asDouble() * y.asDouble());
14879
14880                                 dp = fp16type(dp.asDouble() + q.asDouble());
14881                                 eps += floatFormat16.ulp(q.asDouble(), 2.0);
14882                         }
14883
14884                         result = dp.asDouble();
14885                 }
14886                 else
14887                 {
14888                         TCU_THROW(InternalError, "Unknown flavor");
14889                 }
14890
14891                 out[0] = fp16type(result).bits();
14892                 min[0] = result - eps;
14893                 max[0] = result + eps;
14894
14895                 return true;
14896         }
14897
14898 private:
14899         std::vector<tcu::UVec4> m_permutations;
14900         size_t                                  permutationsFlavorStart;
14901         size_t                                  permutationsFlavorEnd;
14902 };
14903
14904 struct fp16VectorTimesScalar : public fp16AllComponents
14905 {
14906         virtual double getULPs(vector<const deFloat16*>& in)
14907         {
14908                 DE_UNREF(in);
14909
14910                 return 2.0;
14911         }
14912
14913         template<class fp16type>
14914         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14915         {
14916                 DE_ASSERT(in.size() == 2);
14917                 DE_ASSERT(getArgCompCount(0) == getOutCompCount());
14918                 DE_ASSERT(getArgCompCount(1) == 1);
14919
14920                 fp16type        s       (*in[1]);
14921
14922                 for (size_t componentNdx = 0; componentNdx < getArgCompCount(0); ++componentNdx)
14923                 {
14924                         const fp16type  x          (in[0][componentNdx]);
14925                         const double    result (s.asDouble() * x.asDouble());
14926                         const fp16type  m          (result);
14927
14928                         out[componentNdx] = m.bits();
14929                         min[componentNdx] = getMin(result, getULPs(in));
14930                         max[componentNdx] = getMax(result, getULPs(in));
14931                 }
14932
14933                 return true;
14934         }
14935 };
14936
14937 struct fp16MatrixBase : public fp16AllComponents
14938 {
14939         deUint32                getComponentValidity                    ()
14940         {
14941                 return static_cast<deUint32>(-1);
14942         }
14943
14944         inline size_t   getNdx                                                  (const size_t rowCount, const size_t col, const size_t row)
14945         {
14946                 const size_t minComponentCount  = 0;
14947                 const size_t maxComponentCount  = 3;
14948                 const size_t alignedRowsCount   = (rowCount == 3) ? 4 : rowCount;
14949
14950                 DE_ASSERT(de::inRange(rowCount, minComponentCount + 1, maxComponentCount + 1));
14951                 DE_ASSERT(de::inRange(col, minComponentCount, maxComponentCount));
14952                 DE_ASSERT(de::inBounds(row, minComponentCount, rowCount));
14953                 DE_UNREF(minComponentCount);
14954                 DE_UNREF(maxComponentCount);
14955
14956                 return col * alignedRowsCount + row;
14957         }
14958
14959         deUint32                getComponentMatrixValidityMask  (size_t cols, size_t rows)
14960         {
14961                 deUint32        result  = 0u;
14962
14963                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
14964                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
14965                         {
14966                                 const size_t bitNdx = getNdx(rows, colNdx, rowNdx);
14967
14968                                 DE_ASSERT(bitNdx < sizeof(result) * 8);
14969
14970                                 result |= (1<<bitNdx);
14971                         }
14972
14973                 return result;
14974         }
14975 };
14976
14977 template<size_t cols, size_t rows>
14978 struct fp16Transpose : public fp16MatrixBase
14979 {
14980         virtual double getULPs(vector<const deFloat16*>& in)
14981         {
14982                 DE_UNREF(in);
14983
14984                 return 1.0;
14985         }
14986
14987         deUint32        getComponentValidity    ()
14988         {
14989                 return getComponentMatrixValidityMask(rows, cols);
14990         }
14991
14992         template<class fp16type>
14993         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
14994         {
14995                 DE_ASSERT(in.size() == 1);
14996
14997                 const size_t            alignedCols     = (cols == 3) ? 4 : cols;
14998                 const size_t            alignedRows     = (rows == 3) ? 4 : rows;
14999                 vector<deFloat16>       output          (alignedCols * alignedRows, 0);
15000
15001                 DE_ASSERT(output.size() == alignedCols * alignedRows);
15002
15003                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15004                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15005                                 output[rowNdx * alignedCols + colNdx] = in[0][colNdx * alignedRows + rowNdx];
15006
15007                 deMemcpy(out, &output[0], sizeof(deFloat16) * output.size());
15008                 deMemcpy(min, &output[0], sizeof(deFloat16) * output.size());
15009                 deMemcpy(max, &output[0], sizeof(deFloat16) * output.size());
15010
15011                 return true;
15012         }
15013 };
15014
15015 template<size_t cols, size_t rows>
15016 struct fp16MatrixTimesScalar : public fp16MatrixBase
15017 {
15018         virtual double getULPs(vector<const deFloat16*>& in)
15019         {
15020                 DE_UNREF(in);
15021
15022                 return 4.0;
15023         }
15024
15025         deUint32        getComponentValidity    ()
15026         {
15027                 return getComponentMatrixValidityMask(cols, rows);
15028         }
15029
15030         template<class fp16type>
15031         bool calc(vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15032         {
15033                 DE_ASSERT(in.size() == 2);
15034                 DE_ASSERT(getArgCompCount(1) == 1);
15035
15036                 const fp16type  y                       (in[1][0]);
15037                 const float             scalar          (y.asFloat());
15038                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15039                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15040
15041                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
15042                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
15043                 DE_UNREF(alignedCols);
15044
15045                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15046                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15047                         {
15048                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15049                                 const fp16type  x       (in[0][ndx]);
15050                                 const double    result  (scalar * x.asFloat());
15051
15052                                 out[ndx] = fp16type(result).bits();
15053                                 min[ndx] = getMin(result, getULPs(in));
15054                                 max[ndx] = getMax(result, getULPs(in));
15055                         }
15056
15057                 return true;
15058         }
15059 };
15060
15061 template<size_t cols, size_t rows>
15062 struct fp16VectorTimesMatrix : public fp16MatrixBase
15063 {
15064         fp16VectorTimesMatrix() : fp16MatrixBase()
15065         {
15066                 flavorNames.push_back("EmulatingFP16");
15067                 flavorNames.push_back("FloatCalc");
15068         }
15069
15070         virtual double getULPs (vector<const deFloat16*>& in)
15071         {
15072                 DE_UNREF(in);
15073
15074                 return (8.0 * cols);
15075         }
15076
15077         deUint32 getComponentValidity ()
15078         {
15079                 return getComponentMatrixValidityMask(cols, 1);
15080         }
15081
15082         template<class fp16type>
15083         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15084         {
15085                 DE_ASSERT(in.size() == 2);
15086
15087                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15088                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15089
15090                 DE_ASSERT(getOutCompCount() == cols);
15091                 DE_ASSERT(getArgCompCount(0) == rows);
15092                 DE_ASSERT(getArgCompCount(1) == alignedCols * alignedRows);
15093                 DE_UNREF(alignedCols);
15094
15095                 if (getFlavor() == 0)
15096                 {
15097                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15098                         {
15099                                 fp16type        s       (fp16type::zero(1));
15100
15101                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15102                                 {
15103                                         const fp16type  v       (in[0][rowNdx]);
15104                                         const float             vf      (v.asFloat());
15105                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
15106                                         const fp16type  x       (in[1][ndx]);
15107                                         const float             xf      (x.asFloat());
15108                                         const fp16type  m       (vf * xf);
15109
15110                                         s = fp16type(s.asFloat() + m.asFloat());
15111                                 }
15112
15113                                 out[colNdx] = s.bits();
15114                                 min[colNdx] = getMin(s.asDouble(), getULPs(in));
15115                                 max[colNdx] = getMax(s.asDouble(), getULPs(in));
15116                         }
15117                 }
15118                 else if (getFlavor() == 1)
15119                 {
15120                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15121                         {
15122                                 float   s       (0.0f);
15123
15124                                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15125                                 {
15126                                         const fp16type  v       (in[0][rowNdx]);
15127                                         const float             vf      (v.asFloat());
15128                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
15129                                         const fp16type  x       (in[1][ndx]);
15130                                         const float             xf      (x.asFloat());
15131                                         const float             m       (vf * xf);
15132
15133                                         s += m;
15134                                 }
15135
15136                                 out[colNdx] = fp16type(s).bits();
15137                                 min[colNdx] = getMin(static_cast<double>(s), getULPs(in));
15138                                 max[colNdx] = getMax(static_cast<double>(s), getULPs(in));
15139                         }
15140                 }
15141                 else
15142                 {
15143                         TCU_THROW(InternalError, "Unknown flavor");
15144                 }
15145
15146                 return true;
15147         }
15148 };
15149
15150 template<size_t cols, size_t rows>
15151 struct fp16MatrixTimesVector : public fp16MatrixBase
15152 {
15153         fp16MatrixTimesVector() : fp16MatrixBase()
15154         {
15155                 flavorNames.push_back("EmulatingFP16");
15156                 flavorNames.push_back("FloatCalc");
15157         }
15158
15159         virtual double getULPs (vector<const deFloat16*>& in)
15160         {
15161                 DE_UNREF(in);
15162
15163                 return (8.0 * rows);
15164         }
15165
15166         deUint32 getComponentValidity ()
15167         {
15168                 return getComponentMatrixValidityMask(rows, 1);
15169         }
15170
15171         template<class fp16type>
15172         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15173         {
15174                 DE_ASSERT(in.size() == 2);
15175
15176                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15177                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15178
15179                 DE_ASSERT(getOutCompCount() == rows);
15180                 DE_ASSERT(getArgCompCount(0) == alignedCols * alignedRows);
15181                 DE_ASSERT(getArgCompCount(1) == cols);
15182                 DE_UNREF(alignedCols);
15183
15184                 if (getFlavor() == 0)
15185                 {
15186                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15187                         {
15188                                 fp16type        s       (fp16type::zero(1));
15189
15190                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15191                                 {
15192                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
15193                                         const fp16type  x       (in[0][ndx]);
15194                                         const float             xf      (x.asFloat());
15195                                         const fp16type  v       (in[1][colNdx]);
15196                                         const float             vf      (v.asFloat());
15197                                         const fp16type  m       (vf * xf);
15198
15199                                         s = fp16type(s.asFloat() + m.asFloat());
15200                                 }
15201
15202                                 out[rowNdx] = s.bits();
15203                                 min[rowNdx] = getMin(s.asDouble(), getULPs(in));
15204                                 max[rowNdx] = getMax(s.asDouble(), getULPs(in));
15205                         }
15206                 }
15207                 else if (getFlavor() == 1)
15208                 {
15209                         for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15210                         {
15211                                 float   s       (0.0f);
15212
15213                                 for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15214                                 {
15215                                         const size_t    ndx     (colNdx * alignedRows + rowNdx);
15216                                         const fp16type  x       (in[0][ndx]);
15217                                         const float             xf      (x.asFloat());
15218                                         const fp16type  v       (in[1][colNdx]);
15219                                         const float             vf      (v.asFloat());
15220                                         const float             m       (vf * xf);
15221
15222                                         s += m;
15223                                 }
15224
15225                                 out[rowNdx] = fp16type(s).bits();
15226                                 min[rowNdx] = getMin(static_cast<double>(s), getULPs(in));
15227                                 max[rowNdx] = getMax(static_cast<double>(s), getULPs(in));
15228                         }
15229                 }
15230                 else
15231                 {
15232                         TCU_THROW(InternalError, "Unknown flavor");
15233                 }
15234
15235                 return true;
15236         }
15237 };
15238
15239 template<size_t colsL, size_t rowsL, size_t colsR, size_t rowsR>
15240 struct fp16MatrixTimesMatrix : public fp16MatrixBase
15241 {
15242         fp16MatrixTimesMatrix() : fp16MatrixBase()
15243         {
15244                 flavorNames.push_back("EmulatingFP16");
15245                 flavorNames.push_back("FloatCalc");
15246         }
15247
15248         virtual double getULPs (vector<const deFloat16*>& in)
15249         {
15250                 DE_UNREF(in);
15251
15252                 return 32.0;
15253         }
15254
15255         deUint32 getComponentValidity ()
15256         {
15257                 return getComponentMatrixValidityMask(colsR, rowsL);
15258         }
15259
15260         template<class fp16type>
15261         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15262         {
15263                 DE_STATIC_ASSERT(colsL == rowsR);
15264
15265                 DE_ASSERT(in.size() == 2);
15266
15267                 const size_t    alignedColsL    = (colsL == 3) ? 4 : colsL;
15268                 const size_t    alignedRowsL    = (rowsL == 3) ? 4 : rowsL;
15269                 const size_t    alignedColsR    = (colsR == 3) ? 4 : colsR;
15270                 const size_t    alignedRowsR    = (rowsR == 3) ? 4 : rowsR;
15271
15272                 DE_ASSERT(getOutCompCount() == alignedColsR * alignedRowsL);
15273                 DE_ASSERT(getArgCompCount(0) == alignedColsL * alignedRowsL);
15274                 DE_ASSERT(getArgCompCount(1) == alignedColsR * alignedRowsR);
15275                 DE_UNREF(alignedColsL);
15276                 DE_UNREF(alignedColsR);
15277
15278                 if (getFlavor() == 0)
15279                 {
15280                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15281                         {
15282                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15283                                 {
15284                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15285                                         fp16type                s       (fp16type::zero(1));
15286
15287                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15288                                         {
15289                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15290                                                 const fp16type  l               (in[0][ndxl]);
15291                                                 const float             lf              (l.asFloat());
15292                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15293                                                 const fp16type  r               (in[1][ndxr]);
15294                                                 const float             rf              (r.asFloat());
15295                                                 const fp16type  m               (lf * rf);
15296
15297                                                 s = fp16type(s.asFloat() + m.asFloat());
15298                                         }
15299
15300                                         out[ndx] = s.bits();
15301                                         min[ndx] = getMin(s.asDouble(), getULPs(in));
15302                                         max[ndx] = getMax(s.asDouble(), getULPs(in));
15303                                 }
15304                         }
15305                 }
15306                 else if (getFlavor() == 1)
15307                 {
15308                         for (size_t rowNdx = 0; rowNdx < rowsL; ++rowNdx)
15309                         {
15310                                 for (size_t colNdx = 0; colNdx < colsR; ++colNdx)
15311                                 {
15312                                         const size_t    ndx     (colNdx * alignedRowsL + rowNdx);
15313                                         float                   s       (0.0f);
15314
15315                                         for (size_t commonNdx = 0; commonNdx < colsL; ++commonNdx)
15316                                         {
15317                                                 const size_t    ndxl    (commonNdx * alignedRowsL + rowNdx);
15318                                                 const fp16type  l               (in[0][ndxl]);
15319                                                 const float             lf              (l.asFloat());
15320                                                 const size_t    ndxr    (colNdx * alignedRowsR + commonNdx);
15321                                                 const fp16type  r               (in[1][ndxr]);
15322                                                 const float             rf              (r.asFloat());
15323                                                 const float             m               (lf * rf);
15324
15325                                                 s += m;
15326                                         }
15327
15328                                         out[ndx] = fp16type(s).bits();
15329                                         min[ndx] = getMin(static_cast<double>(s), getULPs(in));
15330                                         max[ndx] = getMax(static_cast<double>(s), getULPs(in));
15331                                 }
15332                         }
15333                 }
15334                 else
15335                 {
15336                         TCU_THROW(InternalError, "Unknown flavor");
15337                 }
15338
15339                 return true;
15340         }
15341 };
15342
15343 template<size_t cols, size_t rows>
15344 struct fp16OuterProduct : public fp16MatrixBase
15345 {
15346         virtual double getULPs (vector<const deFloat16*>& in)
15347         {
15348                 DE_UNREF(in);
15349
15350                 return 2.0;
15351         }
15352
15353         deUint32 getComponentValidity ()
15354         {
15355                 return getComponentMatrixValidityMask(cols, rows);
15356         }
15357
15358         template<class fp16type>
15359         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15360         {
15361                 DE_ASSERT(in.size() == 2);
15362
15363                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15364                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15365
15366                 DE_ASSERT(getArgCompCount(0) == rows);
15367                 DE_ASSERT(getArgCompCount(1) == cols);
15368                 DE_ASSERT(getOutCompCount() == alignedCols * alignedRows);
15369                 DE_UNREF(alignedCols);
15370
15371                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15372                 {
15373                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15374                         {
15375                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15376                                 const fp16type  x       (in[0][rowNdx]);
15377                                 const float             xf      (x.asFloat());
15378                                 const fp16type  y       (in[1][colNdx]);
15379                                 const float             yf      (y.asFloat());
15380                                 const fp16type  m       (xf * yf);
15381
15382                                 out[ndx] = m.bits();
15383                                 min[ndx] = getMin(m.asDouble(), getULPs(in));
15384                                 max[ndx] = getMax(m.asDouble(), getULPs(in));
15385                         }
15386                 }
15387
15388                 return true;
15389         }
15390 };
15391
15392 template<size_t size>
15393 struct fp16Determinant;
15394
15395 template<>
15396 struct fp16Determinant<2> : public fp16MatrixBase
15397 {
15398         virtual double getULPs (vector<const deFloat16*>& in)
15399         {
15400                 DE_UNREF(in);
15401
15402                 return 128.0; // This is not a precision test. Value is not from spec
15403         }
15404
15405         deUint32 getComponentValidity ()
15406         {
15407                 return 1;
15408         }
15409
15410         template<class fp16type>
15411         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15412         {
15413                 const size_t    cols            = 2;
15414                 const size_t    rows            = 2;
15415                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15416                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15417
15418                 DE_ASSERT(in.size() == 1);
15419                 DE_ASSERT(getOutCompCount() == 1);
15420                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15421                 DE_UNREF(alignedCols);
15422                 DE_UNREF(alignedRows);
15423
15424                 // [ a b ]
15425                 // [ c d ]
15426                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15427                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15428                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15429                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15430                 const float             ad              (a * d);
15431                 const fp16type  adf16   (ad);
15432                 const float             bc              (b * c);
15433                 const fp16type  bcf16   (bc);
15434                 const float             r               (adf16.asFloat() - bcf16.asFloat());
15435                 const fp16type  rf16    (r);
15436
15437                 out[0] = rf16.bits();
15438                 min[0] = getMin(r, getULPs(in));
15439                 max[0] = getMax(r, getULPs(in));
15440
15441                 return true;
15442         }
15443 };
15444
15445 template<>
15446 struct fp16Determinant<3> : public fp16MatrixBase
15447 {
15448         virtual double getULPs (vector<const deFloat16*>& in)
15449         {
15450                 DE_UNREF(in);
15451
15452                 return 128.0; // This is not a precision test. Value is not from spec
15453         }
15454
15455         deUint32 getComponentValidity ()
15456         {
15457                 return 1;
15458         }
15459
15460         template<class fp16type>
15461         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15462         {
15463                 const size_t    cols            = 3;
15464                 const size_t    rows            = 3;
15465                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15466                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15467
15468                 DE_ASSERT(in.size() == 1);
15469                 DE_ASSERT(getOutCompCount() == 1);
15470                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15471                 DE_UNREF(alignedCols);
15472                 DE_UNREF(alignedRows);
15473
15474                 // [ a b c ]
15475                 // [ d e f ]
15476                 // [ g h i ]
15477                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15478                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15479                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15480                 const float             d               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15481                 const float             e               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15482                 const float             f               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15483                 const float             g               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15484                 const float             h               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15485                 const float             i               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15486                 const fp16type  aei             (a * e * i);
15487                 const fp16type  bfg             (b * f * g);
15488                 const fp16type  cdh             (c * d * h);
15489                 const fp16type  ceg             (c * e * g);
15490                 const fp16type  bdi             (b * d * i);
15491                 const fp16type  afh             (a * f * h);
15492                 const float             r               (aei.asFloat() + bfg.asFloat() + cdh.asFloat() - ceg.asFloat() - bdi.asFloat() - afh.asFloat());
15493                 const fp16type  rf16    (r);
15494
15495                 out[0] = rf16.bits();
15496                 min[0] = getMin(r, getULPs(in));
15497                 max[0] = getMax(r, getULPs(in));
15498
15499                 return true;
15500         }
15501 };
15502
15503 template<>
15504 struct fp16Determinant<4> : public fp16MatrixBase
15505 {
15506         virtual double getULPs (vector<const deFloat16*>& in)
15507         {
15508                 DE_UNREF(in);
15509
15510                 return 128.0; // This is not a precision test. Value is not from spec
15511         }
15512
15513         deUint32 getComponentValidity ()
15514         {
15515                 return 1;
15516         }
15517
15518         template<class fp16type>
15519         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15520         {
15521                 const size_t    rows            = 4;
15522                 const size_t    cols            = 4;
15523                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15524                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15525
15526                 DE_ASSERT(in.size() == 1);
15527                 DE_ASSERT(getOutCompCount() == 1);
15528                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15529                 DE_UNREF(alignedCols);
15530                 DE_UNREF(alignedRows);
15531
15532                 // [ a b c d ]
15533                 // [ e f g h ]
15534                 // [ i j k l ]
15535                 // [ m n o p ]
15536                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15537                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15538                 const float             c               (fp16type(in[0][getNdx(rows, 2, 0)]).asFloat());
15539                 const float             d               (fp16type(in[0][getNdx(rows, 3, 0)]).asFloat());
15540                 const float             e               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15541                 const float             f               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15542                 const float             g               (fp16type(in[0][getNdx(rows, 2, 1)]).asFloat());
15543                 const float             h               (fp16type(in[0][getNdx(rows, 3, 1)]).asFloat());
15544                 const float             i               (fp16type(in[0][getNdx(rows, 0, 2)]).asFloat());
15545                 const float             j               (fp16type(in[0][getNdx(rows, 1, 2)]).asFloat());
15546                 const float             k               (fp16type(in[0][getNdx(rows, 2, 2)]).asFloat());
15547                 const float             l               (fp16type(in[0][getNdx(rows, 3, 2)]).asFloat());
15548                 const float             m               (fp16type(in[0][getNdx(rows, 0, 3)]).asFloat());
15549                 const float             n               (fp16type(in[0][getNdx(rows, 1, 3)]).asFloat());
15550                 const float             o               (fp16type(in[0][getNdx(rows, 2, 3)]).asFloat());
15551                 const float             p               (fp16type(in[0][getNdx(rows, 3, 3)]).asFloat());
15552
15553                 // [ f g h ]
15554                 // [ j k l ]
15555                 // [ n o p ]
15556                 const fp16type  fkp             (f * k * p);
15557                 const fp16type  gln             (g * l * n);
15558                 const fp16type  hjo             (h * j * o);
15559                 const fp16type  hkn             (h * k * n);
15560                 const fp16type  gjp             (g * j * p);
15561                 const fp16type  flo             (f * l * o);
15562                 const fp16type  detA    (a * (fkp.asFloat() + gln.asFloat() + hjo.asFloat() - hkn.asFloat() - gjp.asFloat() - flo.asFloat()));
15563
15564                 // [ e g h ]
15565                 // [ i k l ]
15566                 // [ m o p ]
15567                 const fp16type  ekp             (e * k * p);
15568                 const fp16type  glm             (g * l * m);
15569                 const fp16type  hio             (h * i * o);
15570                 const fp16type  hkm             (h * k * m);
15571                 const fp16type  gip             (g * i * p);
15572                 const fp16type  elo             (e * l * o);
15573                 const fp16type  detB    (b * (ekp.asFloat() + glm.asFloat() + hio.asFloat() - hkm.asFloat() - gip.asFloat() - elo.asFloat()));
15574
15575                 // [ e f h ]
15576                 // [ i j l ]
15577                 // [ m n p ]
15578                 const fp16type  ejp             (e * j * p);
15579                 const fp16type  flm             (f * l * m);
15580                 const fp16type  hin             (h * i * n);
15581                 const fp16type  hjm             (h * j * m);
15582                 const fp16type  fip             (f * i * p);
15583                 const fp16type  eln             (e * l * n);
15584                 const fp16type  detC    (c * (ejp.asFloat() + flm.asFloat() + hin.asFloat() - hjm.asFloat() - fip.asFloat() - eln.asFloat()));
15585
15586                 // [ e f g ]
15587                 // [ i j k ]
15588                 // [ m n o ]
15589                 const fp16type  ejo             (e * j * o);
15590                 const fp16type  fkm             (f * k * m);
15591                 const fp16type  gin             (g * i * n);
15592                 const fp16type  gjm             (g * j * m);
15593                 const fp16type  fio             (f * i * o);
15594                 const fp16type  ekn             (e * k * n);
15595                 const fp16type  detD    (d * (ejo.asFloat() + fkm.asFloat() + gin.asFloat() - gjm.asFloat() - fio.asFloat() - ekn.asFloat()));
15596
15597                 const float             r               (detA.asFloat() - detB.asFloat() + detC.asFloat() - detD.asFloat());
15598                 const fp16type  rf16    (r);
15599
15600                 out[0] = rf16.bits();
15601                 min[0] = getMin(r, getULPs(in));
15602                 max[0] = getMax(r, getULPs(in));
15603
15604                 return true;
15605         }
15606 };
15607
15608 template<size_t size>
15609 struct fp16Inverse;
15610
15611 template<>
15612 struct fp16Inverse<2> : public fp16MatrixBase
15613 {
15614         virtual double getULPs (vector<const deFloat16*>& in)
15615         {
15616                 DE_UNREF(in);
15617
15618                 return 128.0; // This is not a precision test. Value is not from spec
15619         }
15620
15621         deUint32 getComponentValidity ()
15622         {
15623                 return getComponentMatrixValidityMask(2, 2);
15624         }
15625
15626         template<class fp16type>
15627         bool calc (vector<const deFloat16*>& in, deFloat16* out, double* min, double* max)
15628         {
15629                 const size_t    cols            = 2;
15630                 const size_t    rows            = 2;
15631                 const size_t    alignedCols     = (cols == 3) ? 4 : cols;
15632                 const size_t    alignedRows     = (rows == 3) ? 4 : rows;
15633
15634                 DE_ASSERT(in.size() == 1);
15635                 DE_ASSERT(getOutCompCount() == alignedRows * alignedCols);
15636                 DE_ASSERT(getArgCompCount(0) == alignedRows * alignedCols);
15637                 DE_UNREF(alignedCols);
15638
15639                 // [ a b ]
15640                 // [ c d ]
15641                 const float             a               (fp16type(in[0][getNdx(rows, 0, 0)]).asFloat());
15642                 const float             b               (fp16type(in[0][getNdx(rows, 1, 0)]).asFloat());
15643                 const float             c               (fp16type(in[0][getNdx(rows, 0, 1)]).asFloat());
15644                 const float             d               (fp16type(in[0][getNdx(rows, 1, 1)]).asFloat());
15645                 const float             ad              (a * d);
15646                 const fp16type  adf16   (ad);
15647                 const float             bc              (b * c);
15648                 const fp16type  bcf16   (bc);
15649                 const float             det             (adf16.asFloat() - bcf16.asFloat());
15650                 const fp16type  det16   (det);
15651
15652                 out[0] = fp16type( d / det16.asFloat()).bits();
15653                 out[1] = fp16type(-c / det16.asFloat()).bits();
15654                 out[2] = fp16type(-b / det16.asFloat()).bits();
15655                 out[3] = fp16type( a / det16.asFloat()).bits();
15656
15657                 for (size_t rowNdx = 0; rowNdx < rows; ++rowNdx)
15658                         for (size_t colNdx = 0; colNdx < cols; ++colNdx)
15659                         {
15660                                 const size_t    ndx     (colNdx * alignedRows + rowNdx);
15661                                 const fp16type  s       (out[ndx]);
15662
15663                                 min[ndx] = getMin(s.asDouble(), getULPs(in));
15664                                 max[ndx] = getMax(s.asDouble(), getULPs(in));
15665                         }
15666
15667                 return true;
15668         }
15669 };
15670
15671 inline std::string fp16ToString(deFloat16 val)
15672 {
15673         return tcu::toHex<4>(val).toString() + " (" + de::floatToString(tcu::Float16(val).asFloat(), 10) + ")";
15674 }
15675
15676 template <size_t RES_COMPONENTS, size_t ARG0_COMPONENTS, size_t ARG1_COMPONENTS, size_t ARG2_COMPONENTS, class TestedArithmeticFunction>
15677 bool compareFP16ArithmeticFunc (const std::vector<Resource>& inputs, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
15678 {
15679         if (inputs.size() < 1 || inputs.size() > 3 || outputAllocs.size() != 1 || expectedOutputs.size() != 1)
15680                 return false;
15681
15682         const size_t    resultStep                      = (RES_COMPONENTS == 3) ? 4 : RES_COMPONENTS;
15683         const size_t    iterationsCount         = expectedOutputs[0].getByteSize() / (sizeof(deFloat16) * resultStep);
15684         const size_t    inputsSteps[3]          =
15685         {
15686                 (ARG0_COMPONENTS == 3) ? 4 : ARG0_COMPONENTS,
15687                 (ARG1_COMPONENTS == 3) ? 4 : ARG1_COMPONENTS,
15688                 (ARG2_COMPONENTS == 3) ? 4 : ARG2_COMPONENTS,
15689         };
15690
15691         DE_ASSERT(expectedOutputs[0].getByteSize() > 0);
15692         DE_ASSERT(expectedOutputs[0].getByteSize() == sizeof(deFloat16) * iterationsCount * resultStep);
15693
15694         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15695         {
15696                 DE_ASSERT(inputs[inputNdx].getByteSize() > 0);
15697                 DE_ASSERT(inputs[inputNdx].getByteSize() == sizeof(deFloat16) * iterationsCount * inputsSteps[inputNdx]);
15698         }
15699
15700         const deFloat16* const          outputAsFP16                                    = (const deFloat16*)outputAllocs[0]->getHostPtr();
15701         TestedArithmeticFunction        func;
15702
15703         func.setOutCompCount(RES_COMPONENTS);
15704         func.setArgCompCount(0, ARG0_COMPONENTS);
15705         func.setArgCompCount(1, ARG1_COMPONENTS);
15706         func.setArgCompCount(2, ARG2_COMPONENTS);
15707
15708         const bool                                      callOncePerComponent                    = func.callOncePerComponent();
15709         const deUint32                          componentValidityMask                   = func.getComponentValidity();
15710         const size_t                            denormModesCount                                = 2;
15711         const char*                                     denormModes[denormModesCount]   = { "keep denormal numbers", "flush to zero" };
15712         const size_t                            successfulRunsPerComponent              = denormModesCount * func.getFlavorCount();
15713         bool                                            success                                                 = true;
15714         size_t                                          validatedCount                                  = 0;
15715
15716         vector<deUint8> inputBytes[3];
15717
15718         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15719                 inputs[inputNdx].getBytes(inputBytes[inputNdx]);
15720
15721         const deFloat16* const                  inputsAsFP16[3]                 =
15722         {
15723                 inputs.size() >= 1 ? (const deFloat16*)&inputBytes[0][0] : DE_NULL,
15724                 inputs.size() >= 2 ? (const deFloat16*)&inputBytes[1][0] : DE_NULL,
15725                 inputs.size() >= 3 ? (const deFloat16*)&inputBytes[2][0] : DE_NULL,
15726         };
15727
15728         for (size_t idx = 0; idx < iterationsCount; ++idx)
15729         {
15730                 std::vector<size_t>                     successfulRuns          (RES_COMPONENTS, successfulRunsPerComponent);
15731                 std::vector<std::string>        errors                          (RES_COMPONENTS);
15732                 bool                                            iterationValidated      (true);
15733
15734                 for (size_t denormNdx = 0; denormNdx < 2; ++denormNdx)
15735                 {
15736                         for (size_t flavorNdx = 0; flavorNdx < func.getFlavorCount(); ++flavorNdx)
15737                         {
15738                                 func.setFlavor(flavorNdx);
15739
15740                                 const deFloat16*                        iterationOutputFP16             = &outputAsFP16[idx * resultStep];
15741                                 vector<deFloat16>                       iterationCalculatedFP16 (resultStep, 0);
15742                                 vector<double>                          iterationEdgeMin                (resultStep, 0.0);
15743                                 vector<double>                          iterationEdgeMax                (resultStep, 0.0);
15744                                 vector<const deFloat16*>        arguments;
15745
15746                                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15747                                 {
15748                                         std::string     error;
15749                                         bool            reportError = false;
15750
15751                                         if (callOncePerComponent || componentNdx == 0)
15752                                         {
15753                                                 bool funcCallResult;
15754
15755                                                 arguments.clear();
15756
15757                                                 for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15758                                                         arguments.push_back(&inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + componentNdx]);
15759
15760                                                 if (denormNdx == 0)
15761                                                         funcCallResult = func.template calc<tcu::Float16>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15762                                                 else
15763                                                         funcCallResult = func.template calc<tcu::Float16Denormless>(arguments, &iterationCalculatedFP16[componentNdx], &iterationEdgeMin[componentNdx], &iterationEdgeMax[componentNdx]);
15764
15765                                                 if (!funcCallResult)
15766                                                 {
15767                                                         iterationValidated = false;
15768
15769                                                         if (callOncePerComponent)
15770                                                                 continue;
15771                                                         else
15772                                                                 break;
15773                                                 }
15774                                         }
15775
15776                                         if ((componentValidityMask != 0) && (componentValidityMask & (1<<componentNdx)) == 0)
15777                                                 continue;
15778
15779                                         reportError = !compare16BitFloat(iterationCalculatedFP16[componentNdx], iterationOutputFP16[componentNdx], error);
15780
15781                                         if (reportError)
15782                                         {
15783                                                 tcu::Float16 expected   (iterationCalculatedFP16[componentNdx]);
15784                                                 tcu::Float16 outputted  (iterationOutputFP16[componentNdx]);
15785
15786                                                 if (reportError && expected.isNaN())
15787                                                         reportError = false;
15788
15789                                                 if (reportError && !expected.isNaN() && !outputted.isNaN())
15790                                                 {
15791                                                         if (reportError && !expected.isInf() && !outputted.isInf())
15792                                                         {
15793                                                                 // Ignore rounding
15794                                                                 if (expected.bits() == outputted.bits() + 1 || expected.bits() + 1 == outputted.bits())
15795                                                                         reportError = false;
15796                                                         }
15797
15798                                                         if (reportError && expected.isInf())
15799                                                         {
15800                                                                 // RTZ rounding mode returns +/-65504 instead of Inf on overflow
15801                                                                 if (expected.sign() == 1 && outputted.bits() == 0x7bff && iterationEdgeMin[componentNdx] <= std::numeric_limits<double>::max())
15802                                                                         reportError = false;
15803                                                                 else if (expected.sign() == -1 && outputted.bits() == 0xfbff && iterationEdgeMax[componentNdx] >= -std::numeric_limits<double>::max())
15804                                                                         reportError = false;
15805                                                         }
15806
15807                                                         if (reportError)
15808                                                         {
15809                                                                 const double    outputtedDouble = outputted.asDouble();
15810
15811                                                                 DE_ASSERT(iterationEdgeMin[componentNdx] <= iterationEdgeMax[componentNdx]);
15812
15813                                                                 if (de::inRange(outputtedDouble, iterationEdgeMin[componentNdx], iterationEdgeMax[componentNdx]))
15814                                                                         reportError = false;
15815                                                         }
15816                                                 }
15817
15818                                                 if (reportError)
15819                                                 {
15820                                                         const size_t            inputsComps[3]  =
15821                                                         {
15822                                                                 ARG0_COMPONENTS,
15823                                                                 ARG1_COMPONENTS,
15824                                                                 ARG2_COMPONENTS,
15825                                                         };
15826                                                         string                          inputsValues    ("Inputs:");
15827                                                         string                          flavorName              (func.getFlavorCount() == 1 ? "" : string(" flavor ") + de::toString(flavorNdx) + " (" + func.getCurrentFlavorName() + ")");
15828                                                         std::stringstream       errStream;
15829
15830                                                         for (size_t inputNdx = 0; inputNdx < inputs.size(); ++inputNdx)
15831                                                         {
15832                                                                 const size_t    inputCompsCount = inputsComps[inputNdx];
15833
15834                                                                 inputsValues += " [" + de::toString(inputNdx) + "]=(";
15835
15836                                                                 for (size_t compNdx = 0; compNdx < inputCompsCount; ++compNdx)
15837                                                                 {
15838                                                                         const deFloat16 inputComponentValue = inputsAsFP16[inputNdx][idx * inputsSteps[inputNdx] + compNdx];
15839
15840                                                                         inputsValues += fp16ToString(inputComponentValue) + ((compNdx + 1 == inputCompsCount) ? ")": ", ");
15841                                                                 }
15842                                                         }
15843
15844                                                         errStream       << "At"
15845                                                                                 << " iteration " << de::toString(idx)
15846                                                                                 << " component " << de::toString(componentNdx)
15847                                                                                 << " denormMode " << de::toString(denormNdx)
15848                                                                                 << " (" << denormModes[denormNdx] << ")"
15849                                                                                 << " " << flavorName
15850                                                                                 << " " << inputsValues
15851                                                                                 << " outputted:" + fp16ToString(iterationOutputFP16[componentNdx])
15852                                                                                 << " expected:" + fp16ToString(iterationCalculatedFP16[componentNdx])
15853                                                                                 << " or in range: [" << iterationEdgeMin[componentNdx] << ", " << iterationEdgeMax[componentNdx] << "]."
15854                                                                                 << " " << error << "."
15855                                                                                 << std::endl;
15856
15857                                                         errors[componentNdx] += errStream.str();
15858
15859                                                         successfulRuns[componentNdx]--;
15860                                                 }
15861                                         }
15862                                 }
15863                         }
15864                 }
15865
15866                 for (size_t componentNdx = 0; componentNdx < RES_COMPONENTS; ++componentNdx)
15867                 {
15868                         // Check if any component has total failure
15869                         if (successfulRuns[componentNdx] == 0)
15870                         {
15871                                 // Test failed in all denorm modes and all flavors for certain component: dump errors
15872                                 log << TestLog::Message << errors[componentNdx] << TestLog::EndMessage;
15873
15874                                 success = false;
15875                         }
15876                 }
15877
15878                 if (iterationValidated)
15879                         validatedCount++;
15880         }
15881
15882         if (validatedCount < 16)
15883                 TCU_THROW(InternalError, "Too few samples has been validated.");
15884
15885         return success;
15886 }
15887
15888 // IEEE-754 floating point numbers:
15889 // +--------+------+----------+-------------+
15890 // | binary | sign | exponent | significand |
15891 // +--------+------+----------+-------------+
15892 // | 16-bit |  1   |    5     |     10      |
15893 // +--------+------+----------+-------------+
15894 // | 32-bit |  1   |    8     |     23      |
15895 // +--------+------+----------+-------------+
15896 //
15897 // 16-bit floats:
15898 //
15899 // 0   000 00   00 0000 0001 (0x0001: 2e-24:         minimum positive denormalized)
15900 // 0   000 00   11 1111 1111 (0x03ff: 2e-14 - 2e-24: maximum positive denormalized)
15901 // 0   000 01   00 0000 0000 (0x0400: 2e-14:         minimum positive normalized)
15902 // 0   111 10   11 1111 1111 (0x7bff: 65504:         maximum positive normalized)
15903 //
15904 // 0   000 00   00 0000 0000 (0x0000: +0)
15905 // 0   111 11   00 0000 0000 (0x7c00: +Inf)
15906 // 0   000 00   11 1111 0000 (0x03f0: +Denorm)
15907 // 0   000 01   00 0000 0001 (0x0401: +Norm)
15908 // 0   111 11   00 0000 1111 (0x7c0f: +SNaN)
15909 // 0   111 11   11 1111 0000 (0x7ff0: +QNaN)
15910 // Generate and return 16-bit floats and their corresponding 32-bit values.
15911 //
15912 // The first 14 number pairs are manually picked, while the rest are randomly generated.
15913 // Expected count to be at least 14 (numPicks).
15914 vector<deFloat16> getFloat16a (de::Random& rnd, deUint32 count)
15915 {
15916         vector<deFloat16>       float16;
15917
15918         float16.reserve(count);
15919
15920         // Zero
15921         float16.push_back(deUint16(0x0000));
15922         float16.push_back(deUint16(0x8000));
15923         // Infinity
15924         float16.push_back(deUint16(0x7c00));
15925         float16.push_back(deUint16(0xfc00));
15926         // Normalized
15927         float16.push_back(deUint16(0x0401));
15928         float16.push_back(deUint16(0x8401));
15929         // Some normal number
15930         float16.push_back(deUint16(0x14cb));
15931         float16.push_back(deUint16(0x94cb));
15932         // Min/max positive normal
15933         float16.push_back(deUint16(0x0400));
15934         float16.push_back(deUint16(0x7bff));
15935         // Min/max negative normal
15936         float16.push_back(deUint16(0x8400));
15937         float16.push_back(deUint16(0xfbff));
15938         // PI
15939         float16.push_back(deUint16(0x4248)); // 3.140625
15940         float16.push_back(deUint16(0xb248)); // -3.140625
15941         // PI/2
15942         float16.push_back(deUint16(0x3e48)); // 1.5703125
15943         float16.push_back(deUint16(0xbe48)); // -1.5703125
15944         float16.push_back(deUint16(0x3c00)); // 1.0
15945         float16.push_back(deUint16(0x3800)); // 0.5
15946         // Some useful constants
15947         float16.push_back(tcu::Float16(-2.5f).bits());
15948         float16.push_back(tcu::Float16(-1.0f).bits());
15949         float16.push_back(tcu::Float16( 0.4f).bits());
15950         float16.push_back(tcu::Float16( 2.5f).bits());
15951
15952         const deUint32          numPicks        = static_cast<deUint32>(float16.size());
15953
15954         DE_ASSERT(count >= numPicks);
15955         count -= numPicks;
15956
15957         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
15958         {
15959                 int                     sign            = (rnd.getUint16() % 2 == 0) ? +1 : -1;
15960                 int                     exponent        = (rnd.getUint16() % 29) - 14 + 1;
15961                 deUint16        mantissa        = static_cast<deUint16>(2 * (rnd.getUint16() % 512));
15962
15963                 // Exclude power of -14 to avoid denorms
15964                 DE_ASSERT(de::inRange(exponent, -13, 15));
15965
15966                 float16.push_back(tcu::Float16::constructBits(sign, exponent, mantissa).bits());
15967         }
15968
15969         return float16;
15970 }
15971
15972 static inline vector<deFloat16> getInputData1 (deUint32 seed, size_t count, size_t argNo)
15973 {
15974         DE_UNREF(argNo);
15975
15976         de::Random      rnd(seed);
15977
15978         return getFloat16a(rnd, static_cast<deUint32>(count));
15979 }
15980
15981 static inline vector<deFloat16> getInputData2 (deUint32 seed, size_t count, size_t argNo)
15982 {
15983         de::Random      rnd             (seed);
15984         size_t          newCount = static_cast<size_t>(deSqrt(double(count)));
15985
15986         DE_ASSERT(newCount * newCount == count);
15987
15988         vector<deFloat16>       float16 = getFloat16a(rnd, static_cast<deUint32>(newCount));
15989
15990         return squarize(float16, static_cast<deUint32>(argNo));
15991 }
15992
15993 static inline vector<deFloat16> getInputData3 (deUint32 seed, size_t count, size_t argNo)
15994 {
15995         if (argNo == 0 || argNo == 1)
15996                 return getInputData2(seed, count, argNo);
15997         else
15998                 return getInputData1(seed<<argNo, count, argNo);
15999 }
16000
16001 vector<deFloat16> getInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16002 {
16003         DE_UNREF(stride);
16004
16005         vector<deFloat16>       result;
16006
16007         switch (argCount)
16008         {
16009                 case 1:result = getInputData1(seed, count, argNo); break;
16010                 case 2:result = getInputData2(seed, count, argNo); break;
16011                 case 3:result = getInputData3(seed, count, argNo); break;
16012                 default: TCU_THROW(InternalError, "Invalid argument count specified");
16013         }
16014
16015         if (compCount == 3)
16016         {
16017                 const size_t            newCount = (3 * count) / 4;
16018                 vector<deFloat16>       newResult;
16019
16020                 newResult.reserve(result.size());
16021
16022                 for (size_t ndx = 0; ndx < newCount; ++ndx)
16023                 {
16024                         newResult.push_back(result[ndx]);
16025
16026                         if (ndx % 3 == 2)
16027                                 newResult.push_back(0);
16028                 }
16029
16030                 result = newResult;
16031         }
16032
16033         DE_ASSERT(result.size() == count);
16034
16035         return result;
16036 }
16037
16038 // Generator for functions requiring data in range [1, inf]
16039 vector<deFloat16> getInputDataAC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16040 {
16041         vector<deFloat16>       result;
16042
16043         result = getInputData(seed, count, compCount, stride, argCount, argNo);
16044
16045         // Filter out values below 1.0 from upper half of numbers
16046         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16047         {
16048                 const float f = tcu::Float16(result[idx]).asFloat();
16049
16050                 if (f < 1.0f)
16051                         result[idx] = tcu::Float16(1.0f - f).bits();
16052         }
16053
16054         return result;
16055 }
16056
16057 // Generator for functions requiring data in range [-1, 1]
16058 vector<deFloat16> getInputDataA (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16059 {
16060         vector<deFloat16>       result;
16061
16062         result = getInputData(seed, count, compCount, stride, argCount, argNo);
16063
16064         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16065         {
16066                 const float f = tcu::Float16(result[idx]).asFloat();
16067
16068                 if (!de::inRange(f, -1.0f, 1.0f))
16069                         result[idx] = tcu::Float16(deFloatFrac(f)).bits();
16070         }
16071
16072         return result;
16073 }
16074
16075 // Generator for functions requiring data in range [-pi, pi]
16076 vector<deFloat16> getInputDataPI (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16077 {
16078         vector<deFloat16>       result;
16079
16080         result = getInputData(seed, count, compCount, stride, argCount, argNo);
16081
16082         for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16083         {
16084                 const float f = tcu::Float16(result[idx]).asFloat();
16085
16086                 if (!de::inRange(f, -DE_PI, DE_PI))
16087                         result[idx] = tcu::Float16(fmodf(f, DE_PI)).bits();
16088         }
16089
16090         return result;
16091 }
16092
16093 // Generator for functions requiring data in range [0, inf]
16094 vector<deFloat16> getInputDataP (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16095 {
16096         vector<deFloat16>       result;
16097
16098         result = getInputData(seed, count, compCount, stride, argCount, argNo);
16099
16100         if (argNo == 0)
16101         {
16102                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16103                         result[idx] &= static_cast<deFloat16>(~0x8000);
16104         }
16105
16106         return result;
16107 }
16108
16109 vector<deFloat16> getInputDataV (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16110 {
16111         DE_UNREF(stride);
16112         DE_UNREF(argCount);
16113
16114         vector<deFloat16>       result;
16115
16116         if (argNo == 0)
16117                 result = getInputData2(seed, count, argNo);
16118         else
16119         {
16120                 const size_t            alignedCount    = (compCount == 3) ? 4 : compCount;
16121                 const size_t            newCountX               = static_cast<size_t>(deSqrt(double(count * alignedCount)));
16122                 const size_t            newCountY               = count / newCountX;
16123                 de::Random                      rnd                             (seed);
16124                 vector<deFloat16>       float16                 = getFloat16a(rnd, static_cast<deUint32>(newCountX));
16125
16126                 DE_ASSERT(newCountX * newCountX == alignedCount * count);
16127
16128                 for (size_t numIdx = 0; numIdx < newCountX; ++numIdx)
16129                 {
16130                         const vector<deFloat16> tmp(newCountY, float16[numIdx]);
16131
16132                         result.insert(result.end(), tmp.begin(), tmp.end());
16133                 }
16134         }
16135
16136         DE_ASSERT(result.size() == count);
16137
16138         return result;
16139 }
16140
16141 vector<deFloat16> getInputDataM (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16142 {
16143         DE_UNREF(compCount);
16144         DE_UNREF(stride);
16145         DE_UNREF(argCount);
16146
16147         de::Random                      rnd             (seed << argNo);
16148         vector<deFloat16>       result;
16149
16150         result = getFloat16a(rnd, static_cast<deUint32>(count));
16151
16152         DE_ASSERT(result.size() == count);
16153
16154         return result;
16155 }
16156
16157 vector<deFloat16> getInputDataD (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16158 {
16159         DE_UNREF(compCount);
16160         DE_UNREF(argCount);
16161
16162         de::Random                      rnd             (seed << argNo);
16163         vector<deFloat16>       result;
16164
16165         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16166         {
16167                 int num = (rnd.getUint16() % 16) - 8;
16168
16169                 result.push_back(tcu::Float16(float(num)).bits());
16170         }
16171
16172         result[0 * stride] = deUint16(0x7c00); // +Inf
16173         result[1 * stride] = deUint16(0xfc00); // -Inf
16174
16175         DE_ASSERT(result.size() == count);
16176
16177         return result;
16178 }
16179
16180 // Generator for smoothstep function
16181 vector<deFloat16> getInputDataSS (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16182 {
16183         vector<deFloat16>       result;
16184
16185         result = getInputDataD(seed, count, compCount, stride, argCount, argNo);
16186
16187         if (argNo == 0)
16188         {
16189                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16190                 {
16191                         const float f = tcu::Float16(result[idx]).asFloat();
16192
16193                         if (f > 4.0f)
16194                                 result[idx] = tcu::Float16(-f).bits();
16195                 }
16196         }
16197
16198         if (argNo == 1)
16199         {
16200                 for (size_t idx = result.size() / 2; idx < result.size(); ++idx)
16201                 {
16202                         const float f = tcu::Float16(result[idx]).asFloat();
16203
16204                         if (f < 4.0f)
16205                                 result[idx] = tcu::Float16(-f).bits();
16206                 }
16207         }
16208
16209         return result;
16210 }
16211
16212 // Generates normalized vectors for arguments 0 and 1
16213 vector<deFloat16> getInputDataN (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16214 {
16215         DE_UNREF(compCount);
16216         DE_UNREF(argCount);
16217
16218         de::Random                      rnd             (seed << argNo);
16219         vector<deFloat16>       result;
16220
16221         if (argNo == 0 || argNo == 1)
16222         {
16223                 // The input parameters for the incident vector I and the surface normal N must already be normalized
16224                 for (size_t numIdx = 0; numIdx < count; numIdx += stride)
16225                 {
16226                         vector <float>  unnormolized;
16227                         float                   sum                             = 0;
16228
16229                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16230                                 unnormolized.push_back(float((rnd.getUint16() % 16) - 8));
16231
16232                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16233                                 sum += unnormolized[compIdx] * unnormolized[compIdx];
16234
16235                         sum = deFloatSqrt(sum);
16236                         if (sum == 0.0f)
16237                                 unnormolized[0] = sum = 1.0f;
16238
16239                         for (size_t compIdx = 0; compIdx < compCount; ++compIdx)
16240                                 result.push_back(tcu::Float16(unnormolized[compIdx] / sum).bits());
16241
16242                         for (size_t compIdx = compCount; compIdx < stride; ++compIdx)
16243                                 result.push_back(0);
16244                 }
16245         }
16246         else
16247         {
16248                 // Input parameter eta
16249                 for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16250                 {
16251                         int num = (rnd.getUint16() % 16) - 8;
16252
16253                         result.push_back(tcu::Float16(float(num)).bits());
16254                 }
16255         }
16256
16257         DE_ASSERT(result.size() == count);
16258
16259         return result;
16260 }
16261
16262 // Data generator for complex matrix functions like determinant and inverse
16263 vector<deFloat16> getInputDataC (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo)
16264 {
16265         DE_UNREF(compCount);
16266         DE_UNREF(stride);
16267         DE_UNREF(argCount);
16268
16269         de::Random                      rnd             (seed << argNo);
16270         vector<deFloat16>       result;
16271
16272         for (deUint32 numIdx = 0; numIdx < count; ++numIdx)
16273         {
16274                 int num = (rnd.getUint16() % 16) - 8;
16275
16276                 result.push_back(tcu::Float16(float(num)).bits());
16277         }
16278
16279         DE_ASSERT(result.size() == count);
16280
16281         return result;
16282 }
16283
16284 struct Math16TestType
16285 {
16286         const char*             typePrefix;
16287         const size_t    typeComponents;
16288         const size_t    typeArrayStride;
16289         const size_t    typeStructStride;
16290 };
16291
16292 enum Math16DataTypes
16293 {
16294         NONE    = 0,
16295         SCALAR  = 1,
16296         VEC2    = 2,
16297         VEC3    = 3,
16298         VEC4    = 4,
16299         MAT2X2,
16300         MAT2X3,
16301         MAT2X4,
16302         MAT3X2,
16303         MAT3X3,
16304         MAT3X4,
16305         MAT4X2,
16306         MAT4X3,
16307         MAT4X4,
16308         MATH16_TYPE_LAST
16309 };
16310
16311 struct Math16ArgFragments
16312 {
16313         const char*     bodies;
16314         const char*     variables;
16315         const char*     decorations;
16316         const char*     funcVariables;
16317 };
16318
16319 typedef vector<deFloat16> Math16GetInputData (deUint32 seed, size_t count, size_t compCount, size_t stride, size_t argCount, size_t argNo);
16320
16321 struct Math16TestFunc
16322 {
16323         const char*                                     funcName;
16324         const char*                                     funcSuffix;
16325         size_t                                          funcArgsCount;
16326         size_t                                          typeResult;
16327         size_t                                          typeArg0;
16328         size_t                                          typeArg1;
16329         size_t                                          typeArg2;
16330         Math16GetInputData*                     getInputDataFunc;
16331         VerifyIOFunc                            verifyFunc;
16332 };
16333
16334 template<class SpecResource>
16335 void createFloat16ArithmeticFuncTest (tcu::TestContext& testCtx, tcu::TestCaseGroup& testGroup, const size_t testTypeIdx, const Math16TestFunc& testFunc)
16336 {
16337         const int                                       testSpecificSeed                        = deStringHash(testGroup.getName());
16338         const int                                       seed                                            = testCtx.getCommandLine().getBaseSeed() ^ testSpecificSeed;
16339         const size_t                            numDataPointsByAxis                     = 32;
16340         const size_t                            numDataPoints                           = numDataPointsByAxis * numDataPointsByAxis;
16341         const char*                                     componentType                           = "f16";
16342         const Math16TestType            testTypes[MATH16_TYPE_LAST]     =
16343         {
16344                 { "",           0,       0,                                              0,                                             },
16345                 { "",           1,       1 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16346                 { "v2",         2,       2 * sizeof(deFloat16),  2 * sizeof(deFloat16)  },
16347                 { "v3",         3,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16348                 { "v4",         4,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16349                 { "m2x2",       0,       4 * sizeof(deFloat16),  4 * sizeof(deFloat16)  },
16350                 { "m2x3",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16351                 { "m2x4",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16352                 { "m3x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16353                 { "m3x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16354                 { "m3x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16355                 { "m4x2",       0,       8 * sizeof(deFloat16),  8 * sizeof(deFloat16)  },
16356                 { "m4x3",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16357                 { "m4x4",       0,      16 * sizeof(deFloat16), 16 * sizeof(deFloat16)  },
16358         };
16359
16360         DE_ASSERT(testTypeIdx == testTypes[testTypeIdx].typeComponents);
16361
16362
16363         const StringTemplate preMain
16364         (
16365                 "     %c_i32_ndp  = OpConstant %i32 ${num_data_points}\n"
16366
16367                 "        %f16     = OpTypeFloat 16\n"
16368                 "        %v2f16   = OpTypeVector %f16 2\n"
16369                 "        %v3f16   = OpTypeVector %f16 3\n"
16370                 "        %v4f16   = OpTypeVector %f16 4\n"
16371                 "        %m2x2f16 = OpTypeMatrix %v2f16 2\n"
16372                 "        %m2x3f16 = OpTypeMatrix %v3f16 2\n"
16373                 "        %m2x4f16 = OpTypeMatrix %v4f16 2\n"
16374                 "        %m3x2f16 = OpTypeMatrix %v2f16 3\n"
16375                 "        %m3x3f16 = OpTypeMatrix %v3f16 3\n"
16376                 "        %m3x4f16 = OpTypeMatrix %v4f16 3\n"
16377                 "        %m4x2f16 = OpTypeMatrix %v2f16 4\n"
16378                 "        %m4x3f16 = OpTypeMatrix %v3f16 4\n"
16379                 "        %m4x4f16 = OpTypeMatrix %v4f16 4\n"
16380
16381                 "     %up_f16     = OpTypePointer Uniform %f16    \n"
16382                 "     %up_v2f16   = OpTypePointer Uniform %v2f16  \n"
16383                 "     %up_v3f16   = OpTypePointer Uniform %v3f16  \n"
16384                 "     %up_v4f16   = OpTypePointer Uniform %v4f16  \n"
16385                 "     %up_m2x2f16 = OpTypePointer Uniform %m2x2f16\n"
16386                 "     %up_m2x3f16 = OpTypePointer Uniform %m2x3f16\n"
16387                 "     %up_m2x4f16 = OpTypePointer Uniform %m2x4f16\n"
16388                 "     %up_m3x2f16 = OpTypePointer Uniform %m3x2f16\n"
16389                 "     %up_m3x3f16 = OpTypePointer Uniform %m3x3f16\n"
16390                 "     %up_m3x4f16 = OpTypePointer Uniform %m3x4f16\n"
16391                 "     %up_m4x2f16 = OpTypePointer Uniform %m4x2f16\n"
16392                 "     %up_m4x3f16 = OpTypePointer Uniform %m4x3f16\n"
16393                 "     %up_m4x4f16 = OpTypePointer Uniform %m4x4f16\n"
16394
16395                 "     %ra_f16     = OpTypeArray %f16     %c_i32_ndp\n"
16396                 "     %ra_v2f16   = OpTypeArray %v2f16   %c_i32_ndp\n"
16397                 "     %ra_v3f16   = OpTypeArray %v3f16   %c_i32_ndp\n"
16398                 "     %ra_v4f16   = OpTypeArray %v4f16   %c_i32_ndp\n"
16399                 "     %ra_m2x2f16 = OpTypeArray %m2x2f16 %c_i32_ndp\n"
16400                 "     %ra_m2x3f16 = OpTypeArray %m2x3f16 %c_i32_ndp\n"
16401                 "     %ra_m2x4f16 = OpTypeArray %m2x4f16 %c_i32_ndp\n"
16402                 "     %ra_m3x2f16 = OpTypeArray %m3x2f16 %c_i32_ndp\n"
16403                 "     %ra_m3x3f16 = OpTypeArray %m3x3f16 %c_i32_ndp\n"
16404                 "     %ra_m3x4f16 = OpTypeArray %m3x4f16 %c_i32_ndp\n"
16405                 "     %ra_m4x2f16 = OpTypeArray %m4x2f16 %c_i32_ndp\n"
16406                 "     %ra_m4x3f16 = OpTypeArray %m4x3f16 %c_i32_ndp\n"
16407                 "     %ra_m4x4f16 = OpTypeArray %m4x4f16 %c_i32_ndp\n"
16408
16409                 "   %SSBO_f16     = OpTypeStruct %ra_f16    \n"
16410                 "   %SSBO_v2f16   = OpTypeStruct %ra_v2f16  \n"
16411                 "   %SSBO_v3f16   = OpTypeStruct %ra_v3f16  \n"
16412                 "   %SSBO_v4f16   = OpTypeStruct %ra_v4f16  \n"
16413                 "   %SSBO_m2x2f16 = OpTypeStruct %ra_m2x2f16\n"
16414                 "   %SSBO_m2x3f16 = OpTypeStruct %ra_m2x3f16\n"
16415                 "   %SSBO_m2x4f16 = OpTypeStruct %ra_m2x4f16\n"
16416                 "   %SSBO_m3x2f16 = OpTypeStruct %ra_m3x2f16\n"
16417                 "   %SSBO_m3x3f16 = OpTypeStruct %ra_m3x3f16\n"
16418                 "   %SSBO_m3x4f16 = OpTypeStruct %ra_m3x4f16\n"
16419                 "   %SSBO_m4x2f16 = OpTypeStruct %ra_m4x2f16\n"
16420                 "   %SSBO_m4x3f16 = OpTypeStruct %ra_m4x3f16\n"
16421                 "   %SSBO_m4x4f16 = OpTypeStruct %ra_m4x4f16\n"
16422
16423                 "%up_SSBO_f16     = OpTypePointer Uniform %SSBO_f16    \n"
16424                 "%up_SSBO_v2f16   = OpTypePointer Uniform %SSBO_v2f16  \n"
16425                 "%up_SSBO_v3f16   = OpTypePointer Uniform %SSBO_v3f16  \n"
16426                 "%up_SSBO_v4f16   = OpTypePointer Uniform %SSBO_v4f16  \n"
16427                 "%up_SSBO_m2x2f16 = OpTypePointer Uniform %SSBO_m2x2f16\n"
16428                 "%up_SSBO_m2x3f16 = OpTypePointer Uniform %SSBO_m2x3f16\n"
16429                 "%up_SSBO_m2x4f16 = OpTypePointer Uniform %SSBO_m2x4f16\n"
16430                 "%up_SSBO_m3x2f16 = OpTypePointer Uniform %SSBO_m3x2f16\n"
16431                 "%up_SSBO_m3x3f16 = OpTypePointer Uniform %SSBO_m3x3f16\n"
16432                 "%up_SSBO_m3x4f16 = OpTypePointer Uniform %SSBO_m3x4f16\n"
16433                 "%up_SSBO_m4x2f16 = OpTypePointer Uniform %SSBO_m4x2f16\n"
16434                 "%up_SSBO_m4x3f16 = OpTypePointer Uniform %SSBO_m4x3f16\n"
16435                 "%up_SSBO_m4x4f16 = OpTypePointer Uniform %SSBO_m4x4f16\n"
16436
16437                 "       %fp_v2i32 = OpTypePointer Function %v2i32\n"
16438                 "       %fp_v3i32 = OpTypePointer Function %v3i32\n"
16439                 "       %fp_v4i32 = OpTypePointer Function %v4i32\n"
16440                 "${arg_vars}"
16441         );
16442
16443         const StringTemplate decoration
16444         (
16445                 "OpDecorate %ra_f16     ArrayStride 2 \n"
16446                 "OpDecorate %ra_v2f16   ArrayStride 4 \n"
16447                 "OpDecorate %ra_v3f16   ArrayStride 8 \n"
16448                 "OpDecorate %ra_v4f16   ArrayStride 8 \n"
16449                 "OpDecorate %ra_m2x2f16 ArrayStride 8 \n"
16450                 "OpDecorate %ra_m2x3f16 ArrayStride 16\n"
16451                 "OpDecorate %ra_m2x4f16 ArrayStride 16\n"
16452                 "OpDecorate %ra_m3x2f16 ArrayStride 16\n"
16453                 "OpDecorate %ra_m3x3f16 ArrayStride 32\n"
16454                 "OpDecorate %ra_m3x4f16 ArrayStride 32\n"
16455                 "OpDecorate %ra_m4x2f16 ArrayStride 16\n"
16456                 "OpDecorate %ra_m4x3f16 ArrayStride 32\n"
16457                 "OpDecorate %ra_m4x4f16 ArrayStride 32\n"
16458
16459                 "OpMemberDecorate %SSBO_f16     0 Offset 0\n"
16460                 "OpMemberDecorate %SSBO_v2f16   0 Offset 0\n"
16461                 "OpMemberDecorate %SSBO_v3f16   0 Offset 0\n"
16462                 "OpMemberDecorate %SSBO_v4f16   0 Offset 0\n"
16463                 "OpMemberDecorate %SSBO_m2x2f16 0 Offset 0\n"
16464                 "OpMemberDecorate %SSBO_m2x3f16 0 Offset 0\n"
16465                 "OpMemberDecorate %SSBO_m2x4f16 0 Offset 0\n"
16466                 "OpMemberDecorate %SSBO_m3x2f16 0 Offset 0\n"
16467                 "OpMemberDecorate %SSBO_m3x3f16 0 Offset 0\n"
16468                 "OpMemberDecorate %SSBO_m3x4f16 0 Offset 0\n"
16469                 "OpMemberDecorate %SSBO_m4x2f16 0 Offset 0\n"
16470                 "OpMemberDecorate %SSBO_m4x3f16 0 Offset 0\n"
16471                 "OpMemberDecorate %SSBO_m4x4f16 0 Offset 0\n"
16472
16473                 "OpDecorate %SSBO_f16     BufferBlock\n"
16474                 "OpDecorate %SSBO_v2f16   BufferBlock\n"
16475                 "OpDecorate %SSBO_v3f16   BufferBlock\n"
16476                 "OpDecorate %SSBO_v4f16   BufferBlock\n"
16477                 "OpDecorate %SSBO_m2x2f16 BufferBlock\n"
16478                 "OpDecorate %SSBO_m2x3f16 BufferBlock\n"
16479                 "OpDecorate %SSBO_m2x4f16 BufferBlock\n"
16480                 "OpDecorate %SSBO_m3x2f16 BufferBlock\n"
16481                 "OpDecorate %SSBO_m3x3f16 BufferBlock\n"
16482                 "OpDecorate %SSBO_m3x4f16 BufferBlock\n"
16483                 "OpDecorate %SSBO_m4x2f16 BufferBlock\n"
16484                 "OpDecorate %SSBO_m4x3f16 BufferBlock\n"
16485                 "OpDecorate %SSBO_m4x4f16 BufferBlock\n"
16486
16487                 "OpMemberDecorate %SSBO_m2x2f16 0 ColMajor\n"
16488                 "OpMemberDecorate %SSBO_m2x3f16 0 ColMajor\n"
16489                 "OpMemberDecorate %SSBO_m2x4f16 0 ColMajor\n"
16490                 "OpMemberDecorate %SSBO_m3x2f16 0 ColMajor\n"
16491                 "OpMemberDecorate %SSBO_m3x3f16 0 ColMajor\n"
16492                 "OpMemberDecorate %SSBO_m3x4f16 0 ColMajor\n"
16493                 "OpMemberDecorate %SSBO_m4x2f16 0 ColMajor\n"
16494                 "OpMemberDecorate %SSBO_m4x3f16 0 ColMajor\n"
16495                 "OpMemberDecorate %SSBO_m4x4f16 0 ColMajor\n"
16496
16497                 "OpMemberDecorate %SSBO_m2x2f16 0 MatrixStride 4\n"
16498                 "OpMemberDecorate %SSBO_m2x3f16 0 MatrixStride 8\n"
16499                 "OpMemberDecorate %SSBO_m2x4f16 0 MatrixStride 8\n"
16500                 "OpMemberDecorate %SSBO_m3x2f16 0 MatrixStride 4\n"
16501                 "OpMemberDecorate %SSBO_m3x3f16 0 MatrixStride 8\n"
16502                 "OpMemberDecorate %SSBO_m3x4f16 0 MatrixStride 8\n"
16503                 "OpMemberDecorate %SSBO_m4x2f16 0 MatrixStride 4\n"
16504                 "OpMemberDecorate %SSBO_m4x3f16 0 MatrixStride 8\n"
16505                 "OpMemberDecorate %SSBO_m4x4f16 0 MatrixStride 8\n"
16506
16507                 "${arg_decorations}"
16508         );
16509
16510         const StringTemplate testFun
16511         (
16512                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
16513                 "    %param = OpFunctionParameter %v4f32\n"
16514                 "    %entry = OpLabel\n"
16515
16516                 "        %i = OpVariable %fp_i32 Function\n"
16517                 "${arg_infunc_vars}"
16518                 "             OpStore %i %c_i32_0\n"
16519                 "             OpBranch %loop\n"
16520
16521                 "     %loop = OpLabel\n"
16522                 "    %i_cmp = OpLoad %i32 %i\n"
16523                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
16524                 "             OpLoopMerge %merge %next None\n"
16525                 "             OpBranchConditional %lt %write %merge\n"
16526
16527                 "    %write = OpLabel\n"
16528                 "      %ndx = OpLoad %i32 %i\n"
16529
16530                 "${arg_func_call}"
16531
16532                 "             OpBranch %next\n"
16533
16534                 "     %next = OpLabel\n"
16535                 "    %i_cur = OpLoad %i32 %i\n"
16536                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
16537                 "             OpStore %i %i_new\n"
16538                 "             OpBranch %loop\n"
16539
16540                 "    %merge = OpLabel\n"
16541                 "             OpReturnValue %param\n"
16542                 "             OpFunctionEnd\n"
16543         );
16544
16545         const Math16ArgFragments        argFragment1    =
16546         {
16547                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16548                 " %val_src0 = OpLoad %${t0} %src0\n"
16549                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0\n"
16550                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16551                 "             OpStore %dst %val_dst\n",
16552                 "",
16553                 "",
16554                 "",
16555         };
16556
16557         const Math16ArgFragments        argFragment2    =
16558         {
16559                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16560                 " %val_src0 = OpLoad %${t0} %src0\n"
16561                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16562                 " %val_src1 = OpLoad %${t1} %src1\n"
16563                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1\n"
16564                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16565                 "             OpStore %dst %val_dst\n",
16566                 "",
16567                 "",
16568                 "",
16569         };
16570
16571         const Math16ArgFragments        argFragment3    =
16572         {
16573                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16574                 " %val_src0 = OpLoad %${t0} %src0\n"
16575                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16576                 " %val_src1 = OpLoad %${t1} %src1\n"
16577                 "     %src2 = OpAccessChain %up_${t2} %ssbo_src2 %c_i32_0 %ndx\n"
16578                 " %val_src2 = OpLoad %${t2} %src2\n"
16579                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1 %val_src2\n"
16580                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16581                 "             OpStore %dst %val_dst\n",
16582                 "",
16583                 "",
16584                 "",
16585         };
16586
16587         const Math16ArgFragments        argFragmentLdExp        =
16588         {
16589                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16590                 " %val_src0 = OpLoad %${t0} %src0\n"
16591                 "     %src1 = OpAccessChain %up_${t1} %ssbo_src1 %c_i32_0 %ndx\n"
16592                 " %val_src1 = OpLoad %${t1} %src1\n"
16593                 "%val_src1i = OpConvertFToS %${dr}i32 %val_src1\n"
16594                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %val_src1i\n"
16595                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16596                 "             OpStore %dst %val_dst\n",
16597
16598                 "",
16599
16600                 "",
16601
16602                 "",
16603         };
16604
16605         const Math16ArgFragments        argFragmentModfFrac     =
16606         {
16607                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16608                 " %val_src0 = OpLoad %${t0} %src0\n"
16609                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16610                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16611                 "             OpStore %dst %val_dst\n",
16612
16613                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16614
16615                 "",
16616
16617                 "      %tmp = OpVariable %fp_tmp Function\n",
16618         };
16619
16620         const Math16ArgFragments        argFragmentModfInt      =
16621         {
16622                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16623                 " %val_src0 = OpLoad %${t0} %src0\n"
16624                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %tmp\n"
16625                 "     %tmp0 = OpAccessChain %fp_tmp %tmp\n"
16626                 "  %val_dst = OpLoad %${tr} %tmp0\n"
16627                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16628                 "             OpStore %dst %val_dst\n",
16629
16630                 "   %fp_tmp = OpTypePointer Function %${tr}\n",
16631
16632                 "",
16633
16634                 "      %tmp = OpVariable %fp_tmp Function\n",
16635         };
16636
16637         const Math16ArgFragments        argFragmentModfStruct   =
16638         {
16639                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16640                 " %val_src0 = OpLoad %${t0} %src0\n"
16641                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16642                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16643                 "             OpStore %tmp_ptr_s %val_tmp\n"
16644                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_${struct_member}\n"
16645                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16646                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16647                 "             OpStore %dst %val_dst\n",
16648
16649                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16650                 "   %st_tmp = OpTypeStruct %${tr} %${tr}\n"
16651                 "   %fp_tmp = OpTypePointer Function %st_tmp\n"
16652                 "   %c_frac = OpConstant %i32 0\n"
16653                 "    %c_int = OpConstant %i32 1\n",
16654
16655                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16656                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16657
16658                 "      %tmp = OpVariable %fp_tmp Function\n",
16659         };
16660
16661         const Math16ArgFragments        argFragmentFrexpStructS =
16662         {
16663                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16664                 " %val_src0 = OpLoad %${t0} %src0\n"
16665                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16666                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16667                 "             OpStore %tmp_ptr_s %val_tmp\n"
16668                 "%tmp_ptr_l = OpAccessChain %fp_${tr} %tmp %c_i32_0\n"
16669                 "  %val_dst = OpLoad %${tr} %tmp_ptr_l\n"
16670                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16671                 "             OpStore %dst %val_dst\n",
16672
16673                 "  %fp_${tr} = OpTypePointer Function %${tr}\n"
16674                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16675                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16676
16677                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16678                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16679
16680                 "      %tmp = OpVariable %fp_tmp Function\n",
16681         };
16682
16683         const Math16ArgFragments        argFragmentFrexpStructE =
16684         {
16685                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16686                 " %val_src0 = OpLoad %${t0} %src0\n"
16687                 "  %val_tmp = ${op} %st_tmp ${ext_inst} %val_src0\n"
16688                 "%tmp_ptr_s = OpAccessChain %fp_tmp %tmp\n"
16689                 "             OpStore %tmp_ptr_s %val_tmp\n"
16690                 "%tmp_ptr_l = OpAccessChain %fp_${dr}i32 %tmp %c_i32_1\n"
16691                 "%val_dst_i = OpLoad %${dr}i32 %tmp_ptr_l\n"
16692                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16693                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16694                 "             OpStore %dst %val_dst\n",
16695
16696                 "   %st_tmp = OpTypeStruct %${tr} %${dr}i32\n"
16697                 "   %fp_tmp = OpTypePointer Function %st_tmp\n",
16698
16699                 "OpMemberDecorate %st_tmp 0 Offset 0\n"
16700                 "OpMemberDecorate %st_tmp 1 Offset ${struct_stride}\n",
16701
16702                 "      %tmp = OpVariable %fp_tmp Function\n",
16703         };
16704
16705         const Math16ArgFragments        argFragmentFrexpS               =
16706         {
16707                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16708                 " %val_src0 = OpLoad %${t0} %src0\n"
16709                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16710                 "  %val_dst = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16711                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16712                 "             OpStore %dst %val_dst\n",
16713
16714                 "",
16715
16716                 "",
16717
16718                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16719         };
16720
16721         const Math16ArgFragments        argFragmentFrexpE               =
16722         {
16723                 "     %src0 = OpAccessChain %up_${t0} %ssbo_src0 %c_i32_0 %ndx\n"
16724                 " %val_src0 = OpLoad %${t0} %src0\n"
16725                 "  %out_exp = OpAccessChain %fp_${dr}i32 %tmp\n"
16726                 "%val_dummy = ${op} %${tr} ${ext_inst} %val_src0 %out_exp\n"
16727                 "%val_dst_i = OpLoad %${dr}i32 %out_exp\n"
16728                 "  %val_dst = OpConvertSToF %${tr} %val_dst_i\n"
16729                 "      %dst = OpAccessChain %up_${tr} %ssbo_dst %c_i32_0 %ndx\n"
16730                 "             OpStore %dst %val_dst\n",
16731
16732                 "",
16733
16734                 "",
16735
16736                 "      %tmp = OpVariable %fp_${dr}i32 Function\n",
16737         };
16738
16739         const Math16TestType&           testType                                = testTypes[testTypeIdx];
16740         const string                            funcNameString                  = string(testFunc.funcName) + string(testFunc.funcSuffix);
16741         const string                            testName                                = de::toLower(funcNameString);
16742         const Math16ArgFragments*       argFragments                    = DE_NULL;
16743         const size_t                            typeStructStride                = testType.typeStructStride;
16744         const bool                                      extInst                                 = !(testFunc.funcName[0] == 'O' && testFunc.funcName[1] == 'p');
16745         const size_t                            numFloatsPerArg0Type    = testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16);
16746         const size_t                            iterations                              = numDataPoints / numFloatsPerArg0Type;
16747         const size_t                            numFloatsPerResultType  = testTypes[testFunc.typeResult].typeArrayStride / sizeof(deFloat16);
16748         const vector<deFloat16>         float16DummyOutput              (iterations * numFloatsPerResultType, 0);
16749         VulkanFeatures                          features;
16750         SpecResource                            specResource;
16751         map<string, string>                     specs;
16752         map<string, string>                     fragments;
16753         vector<string>                          extensions;
16754         string                                          funcCall;
16755         string                                          funcVariables;
16756         string                                          variables;
16757         string                                          declarations;
16758         string                                          decorations;
16759
16760         switch (testFunc.funcArgsCount)
16761         {
16762                 case 1:
16763                 {
16764                         argFragments = &argFragment1;
16765
16766                         if (funcNameString == "ModfFrac")               argFragments = &argFragmentModfFrac;
16767                         if (funcNameString == "ModfInt")                argFragments = &argFragmentModfInt;
16768                         if (funcNameString == "ModfStructFrac") argFragments = &argFragmentModfStruct;
16769                         if (funcNameString == "ModfStructInt")  argFragments = &argFragmentModfStruct;
16770                         if (funcNameString == "FrexpS")                 argFragments = &argFragmentFrexpS;
16771                         if (funcNameString == "FrexpE")                 argFragments = &argFragmentFrexpE;
16772                         if (funcNameString == "FrexpStructS")   argFragments = &argFragmentFrexpStructS;
16773                         if (funcNameString == "FrexpStructE")   argFragments = &argFragmentFrexpStructE;
16774
16775                         break;
16776                 }
16777                 case 2:
16778                 {
16779                         argFragments = &argFragment2;
16780
16781                         if (funcNameString == "Ldexp")                  argFragments = &argFragmentLdExp;
16782
16783                         break;
16784                 }
16785                 case 3:
16786                 {
16787                         argFragments = &argFragment3;
16788
16789                         break;
16790                 }
16791                 default:
16792                 {
16793                         TCU_THROW(InternalError, "Invalid number of arguments");
16794                 }
16795         }
16796
16797         if (testFunc.funcArgsCount == 1)
16798         {
16799                 variables +=
16800                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16801                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16802
16803                 decorations +=
16804                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16805                         "OpDecorate %ssbo_src0 Binding 0\n"
16806                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16807                         "OpDecorate %ssbo_dst Binding 1\n";
16808         }
16809         else if (testFunc.funcArgsCount == 2)
16810         {
16811                 variables +=
16812                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16813                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16814                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16815
16816                 decorations +=
16817                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16818                         "OpDecorate %ssbo_src0 Binding 0\n"
16819                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16820                         "OpDecorate %ssbo_src1 Binding 1\n"
16821                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16822                         "OpDecorate %ssbo_dst Binding 2\n";
16823         }
16824         else if (testFunc.funcArgsCount == 3)
16825         {
16826                 variables +=
16827                         " %ssbo_src0 = OpVariable %up_SSBO_${t0} Uniform\n"
16828                         " %ssbo_src1 = OpVariable %up_SSBO_${t1} Uniform\n"
16829                         " %ssbo_src2 = OpVariable %up_SSBO_${t2} Uniform\n"
16830                         "  %ssbo_dst = OpVariable %up_SSBO_${tr} Uniform\n";
16831
16832                 decorations +=
16833                         "OpDecorate %ssbo_src0 DescriptorSet 0\n"
16834                         "OpDecorate %ssbo_src0 Binding 0\n"
16835                         "OpDecorate %ssbo_src1 DescriptorSet 0\n"
16836                         "OpDecorate %ssbo_src1 Binding 1\n"
16837                         "OpDecorate %ssbo_src2 DescriptorSet 0\n"
16838                         "OpDecorate %ssbo_src2 Binding 2\n"
16839                         "OpDecorate %ssbo_dst DescriptorSet 0\n"
16840                         "OpDecorate %ssbo_dst Binding 3\n";
16841         }
16842         else
16843         {
16844                 TCU_THROW(InternalError, "Invalid number of function arguments");
16845         }
16846
16847         variables       += argFragments->variables;
16848         decorations     += argFragments->decorations;
16849
16850         specs["dr"]                                     = testTypes[testFunc.typeResult].typePrefix;
16851         specs["d0"]                                     = testTypes[testFunc.typeArg0].typePrefix;
16852         specs["d1"]                                     = testTypes[testFunc.typeArg1].typePrefix;
16853         specs["d2"]                                     = testTypes[testFunc.typeArg2].typePrefix;
16854         specs["tr"]                                     = string(testTypes[testFunc.typeResult].typePrefix) + componentType;
16855         specs["t0"]                                     = string(testTypes[testFunc.typeArg0].typePrefix) + componentType;
16856         specs["t1"]                                     = string(testTypes[testFunc.typeArg1].typePrefix) + componentType;
16857         specs["t2"]                                     = string(testTypes[testFunc.typeArg2].typePrefix) + componentType;
16858         specs["struct_stride"]          = de::toString(typeStructStride);
16859         specs["op"]                                     = extInst ? "OpExtInst" : testFunc.funcName;
16860         specs["ext_inst"]                       = extInst ? string("%ext_import ") + testFunc.funcName : "";
16861         specs["struct_member"]          = de::toLower(testFunc.funcSuffix);
16862
16863         variables                                       = StringTemplate(variables).specialize(specs);
16864         decorations                                     = StringTemplate(decorations).specialize(specs);
16865         funcVariables                           = StringTemplate(argFragments->funcVariables).specialize(specs);
16866         funcCall                                        = StringTemplate(argFragments->bodies).specialize(specs);
16867
16868         specs["num_data_points"]        = de::toString(iterations);
16869         specs["arg_vars"]                       = variables;
16870         specs["arg_decorations"]        = decorations;
16871         specs["arg_infunc_vars"]        = funcVariables;
16872         specs["arg_func_call"]          = funcCall;
16873
16874         fragments["extension"]          = "OpExtension \"SPV_KHR_16bit_storage\"\n%ext_import = OpExtInstImport \"GLSL.std.450\"";
16875         fragments["capability"]         = "OpCapability Matrix\nOpCapability StorageUniformBufferBlock16";
16876         fragments["decoration"]         = decoration.specialize(specs);
16877         fragments["pre_main"]           = preMain.specialize(specs);
16878         fragments["testfun"]            = testFun.specialize(specs);
16879
16880         for (size_t inputArgNdx = 0; inputArgNdx < testFunc.funcArgsCount; ++inputArgNdx)
16881         {
16882                 const size_t                    numFloatsPerItem        = (inputArgNdx == 0) ? testTypes[testFunc.typeArg0].typeArrayStride / sizeof(deFloat16)
16883                                                                                                         : (inputArgNdx == 1) ? testTypes[testFunc.typeArg1].typeArrayStride / sizeof(deFloat16)
16884                                                                                                         : (inputArgNdx == 2) ? testTypes[testFunc.typeArg2].typeArrayStride / sizeof(deFloat16)
16885                                                                                                         : -1;
16886                 const vector<deFloat16> inputData                       = testFunc.getInputDataFunc(seed, numFloatsPerItem * iterations, testTypeIdx, numFloatsPerItem, testFunc.funcArgsCount, inputArgNdx);
16887
16888                 specResource.inputs.push_back(Resource(BufferSp(new Float16Buffer(inputData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16889         }
16890
16891         specResource.outputs.push_back(Resource(BufferSp(new Float16Buffer(float16DummyOutput)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
16892         specResource.verifyIO = testFunc.verifyFunc;
16893
16894         extensions.push_back("VK_KHR_16bit_storage");
16895         extensions.push_back("VK_KHR_shader_float16_int8");
16896
16897         features.ext16BitStorage        = EXT16BITSTORAGEFEATURES_UNIFORM_BUFFER_BLOCK;
16898         features.extFloat16Int8         = EXTFLOAT16INT8FEATURES_FLOAT16;
16899
16900         finalizeTestsCreation(specResource, fragments, testCtx, testGroup, testName, features, extensions, IVec3(1, 1, 1));
16901 }
16902
16903 template<size_t C, class SpecResource>
16904 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16905 {
16906         DE_STATIC_ASSERT(C >= 1 && C <= 4);
16907
16908         const std::string                               testGroupName   (string("arithmetic_") + de::toString(C));
16909         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16910         const Math16TestFunc                    testFuncs[]             =
16911         {
16912                 {       "OpFNegate",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16OpFNegate>                                       },
16913                 {       "Round",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Round>                                           },
16914                 {       "RoundEven",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16RoundEven>                                       },
16915                 {       "Trunc",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Trunc>                                           },
16916                 {       "FAbs",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FAbs>                                            },
16917                 {       "FSign",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FSign>                                           },
16918                 {       "Floor",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Floor>                                           },
16919                 {       "Ceil",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Ceil>                                            },
16920                 {       "Fract",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Fract>                                           },
16921                 {       "Radians",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Radians>                                         },
16922                 {       "Degrees",                              "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Degrees>                                         },
16923                 {       "Sin",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sin>                                                     },
16924                 {       "Cos",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cos>                                                     },
16925                 {       "Tan",                                  "",                     1,      C,              C,              0,              0, &getInputDataPI,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tan>                                                     },
16926                 {       "Asin",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asin>                                            },
16927                 {       "Acos",                                 "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acos>                                            },
16928                 {       "Atan",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atan>                                            },
16929                 {       "Sinh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sinh>                                            },
16930                 {       "Cosh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Cosh>                                            },
16931                 {       "Tanh",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Tanh>                                            },
16932                 {       "Asinh",                                "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Asinh>                                           },
16933                 {       "Acosh",                                "",                     1,      C,              C,              0,              0, &getInputDataAC,     compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Acosh>                                           },
16934                 {       "Atanh",                                "",                     1,      C,              C,              0,              0, &getInputDataA,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Atanh>                                           },
16935                 {       "Exp",                                  "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp>                                                     },
16936                 {       "Log",                                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log>                                                     },
16937                 {       "Exp2",                                 "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Exp2>                                            },
16938                 {       "Log2",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Log2>                                            },
16939                 {       "Sqrt",                                 "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Sqrt>                                            },
16940                 {       "InverseSqrt",                  "",                     1,      C,              C,              0,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16InverseSqrt>                                     },
16941                 {       "Modf",                                 "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16942                 {       "Modf",                                 "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16943                 {       "ModfStruct",                   "Frac",         1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfFrac>                                        },
16944                 {       "ModfStruct",                   "Int",          1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16ModfInt>                                         },
16945                 {       "Frexp",                                "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16946                 {       "Frexp",                                "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16947                 {       "FrexpStruct",                  "S",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpS>                                          },
16948                 {       "FrexpStruct",                  "E",            1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16FrexpE>                                          },
16949                 {       "OpFAdd",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFAdd>                                          },
16950                 {       "OpFSub",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFSub>                                          },
16951                 {       "OpFMul",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFMul>                                          },
16952                 {       "OpFDiv",                               "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16OpFDiv>                                          },
16953                 {       "Atan2",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Atan2>                                           },
16954                 {       "Pow",                                  "",                     2,      C,              C,              C,              0, &getInputDataP,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Pow>                                                     },
16955                 {       "FMin",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMin>                                            },
16956                 {       "FMax",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16FMax>                                            },
16957                 {       "Step",                                 "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Step>                                            },
16958                 {       "Ldexp",                                "",                     2,      C,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Ldexp>                                           },
16959                 {       "FClamp",                               "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FClamp>                                          },
16960                 {       "FMix",                                 "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FMix>                                            },
16961                 {       "SmoothStep",                   "",                     3,      C,              C,              C,              C, &getInputDataSS,     compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16SmoothStep>                                      },
16962                 {       "Fma",                                  "",                     3,      C,              C,              C,              C, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16Fma>                                                     },
16963                 {       "Length",                               "",                     1,      1,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  0,  0, fp16Length>                                          },
16964                 {       "Distance",                             "",                     2,      1,              C,              C,              0, &getInputData,       compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Distance>                                        },
16965                 {       "Cross",                                "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Cross>                                           },
16966                 {       "Normalize",                    "",                     1,      C,              C,              0,              0, &getInputData,       compareFP16ArithmeticFunc<  C,  C,  0,  0, fp16Normalize>                                       },
16967                 {       "FaceForward",                  "",                     3,      C,              C,              C,              C, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  C, fp16FaceForward>                                     },
16968                 {       "Reflect",                              "",                     2,      C,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  C,  C,  C,  0, fp16Reflect>                                         },
16969                 {       "Refract",                              "",                     3,      C,              C,              C,              1, &getInputDataN,      compareFP16ArithmeticFunc<  C,  C,  C,  1, fp16Refract>                                         },
16970                 {       "OpDot",                                "",                     2,      1,              C,              C,              0, &getInputDataD,      compareFP16ArithmeticFunc<  1,  C,  C,  0, fp16Dot>                                                     },
16971                 {       "OpVectorTimesScalar",  "",                     2,      C,              C,              1,              0, &getInputDataV,      compareFP16ArithmeticFunc<  C,  C,  1,  0, fp16VectorTimesScalar>                       },
16972         };
16973
16974         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
16975         {
16976                 const Math16TestFunc&   testFunc                = testFuncs[testFuncIdx];
16977                 const string                    funcNameString  = testFunc.funcName;
16978
16979                 if ((C != 3) && funcNameString == "Cross")
16980                         continue;
16981
16982                 if ((C < 2) && funcNameString == "OpDot")
16983                         continue;
16984
16985                 if ((C < 2) && funcNameString == "OpVectorTimesScalar")
16986                         continue;
16987
16988                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), C, testFunc);
16989         }
16990
16991         return testGroup.release();
16992 }
16993
16994 template<class SpecResource>
16995 tcu::TestCaseGroup* createFloat16ArithmeticSet (tcu::TestContext& testCtx)
16996 {
16997         const std::string                               testGroupName   ("arithmetic");
16998         de::MovePtr<tcu::TestCaseGroup> testGroup               (new tcu::TestCaseGroup(testCtx, testGroupName.c_str(), "Float 16 arithmetic and related tests"));
16999         const Math16TestFunc                    testFuncs[]             =
17000         {
17001                 {       "OpTranspose",                  "2x2",          1,      MAT2X2, MAT2X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Transpose<2,2> >                         },
17002                 {       "OpTranspose",                  "3x2",          1,      MAT2X3, MAT3X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<3,2> >                         },
17003                 {       "OpTranspose",                  "4x2",          1,      MAT2X4, MAT4X2, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<4,2> >                         },
17004                 {       "OpTranspose",                  "2x3",          1,      MAT3X2, MAT2X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,3> >                         },
17005                 {       "OpTranspose",                  "3x3",          1,      MAT3X3, MAT3X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,3> >                         },
17006                 {       "OpTranspose",                  "4x3",          1,      MAT3X4, MAT4X3, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,3> >                         },
17007                 {       "OpTranspose",                  "2x4",          1,      MAT4X2, MAT2X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc<  8,  8,  0,  0, fp16Transpose<2,4> >                         },
17008                 {       "OpTranspose",                  "3x4",          1,      MAT4X3, MAT3X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<3,4> >                         },
17009                 {       "OpTranspose",                  "4x4",          1,      MAT4X4, MAT4X4, 0,              0, &getInputDataM,      compareFP16ArithmeticFunc< 16, 16,  0,  0, fp16Transpose<4,4> >                         },
17010                 {       "OpMatrixTimesScalar",  "2x2",          2,      MAT2X2, MAT2X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  1,  0, fp16MatrixTimesScalar<2,2> >         },
17011                 {       "OpMatrixTimesScalar",  "2x3",          2,      MAT2X3, MAT2X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,3> >         },
17012                 {       "OpMatrixTimesScalar",  "2x4",          2,      MAT2X4, MAT2X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<2,4> >         },
17013                 {       "OpMatrixTimesScalar",  "3x2",          2,      MAT3X2, MAT3X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<3,2> >         },
17014                 {       "OpMatrixTimesScalar",  "3x3",          2,      MAT3X3, MAT3X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,3> >         },
17015                 {       "OpMatrixTimesScalar",  "3x4",          2,      MAT3X4, MAT3X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<3,4> >         },
17016                 {       "OpMatrixTimesScalar",  "4x2",          2,      MAT4X2, MAT4X2, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  1,  0, fp16MatrixTimesScalar<4,2> >         },
17017                 {       "OpMatrixTimesScalar",  "4x3",          2,      MAT4X3, MAT4X3, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,3> >         },
17018                 {       "OpMatrixTimesScalar",  "4x4",          2,      MAT4X4, MAT4X4, 1,              0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16,  1,  0, fp16MatrixTimesScalar<4,4> >         },
17019                 {       "OpVectorTimesMatrix",  "2x2",          2,      VEC2,   VEC2,   MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  2,  4,  0, fp16VectorTimesMatrix<2,2> >         },
17020                 {       "OpVectorTimesMatrix",  "2x3",          2,      VEC2,   VEC3,   MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  3,  8,  0, fp16VectorTimesMatrix<2,3> >         },
17021                 {       "OpVectorTimesMatrix",  "2x4",          2,      VEC2,   VEC4,   MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  8,  0, fp16VectorTimesMatrix<2,4> >         },
17022                 {       "OpVectorTimesMatrix",  "3x2",          2,      VEC3,   VEC2,   MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  2,  8,  0, fp16VectorTimesMatrix<3,2> >         },
17023                 {       "OpVectorTimesMatrix",  "3x3",          2,      VEC3,   VEC3,   MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  3, 16,  0, fp16VectorTimesMatrix<3,3> >         },
17024                 {       "OpVectorTimesMatrix",  "3x4",          2,      VEC3,   VEC4,   MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  4, 16,  0, fp16VectorTimesMatrix<3,4> >         },
17025                 {       "OpVectorTimesMatrix",  "4x2",          2,      VEC4,   VEC2,   MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  8,  0, fp16VectorTimesMatrix<4,2> >         },
17026                 {       "OpVectorTimesMatrix",  "4x3",          2,      VEC4,   VEC3,   MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  3, 16,  0, fp16VectorTimesMatrix<4,3> >         },
17027                 {       "OpVectorTimesMatrix",  "4x4",          2,      VEC4,   VEC4,   MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4, 16,  0, fp16VectorTimesMatrix<4,4> >         },
17028                 {       "OpMatrixTimesVector",  "2x2",          2,      VEC2,   MAT2X2, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  4,  2,  0, fp16MatrixTimesVector<2,2> >         },
17029                 {       "OpMatrixTimesVector",  "2x3",          2,      VEC3,   MAT2X3, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3,  8,  2,  0, fp16MatrixTimesVector<2,3> >         },
17030                 {       "OpMatrixTimesVector",  "2x4",          2,      VEC4,   MAT2X4, VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  2,  0, fp16MatrixTimesVector<2,4> >         },
17031                 {       "OpMatrixTimesVector",  "3x2",          2,      VEC2,   MAT3X2, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  3,  0, fp16MatrixTimesVector<3,2> >         },
17032                 {       "OpMatrixTimesVector",  "3x3",          2,      VEC3,   MAT3X3, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  3,  0, fp16MatrixTimesVector<3,3> >         },
17033                 {       "OpMatrixTimesVector",  "3x4",          2,      VEC4,   MAT3X4, VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  3,  0, fp16MatrixTimesVector<3,4> >         },
17034                 {       "OpMatrixTimesVector",  "4x2",          2,      VEC2,   MAT4X2, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  2,  8,  4,  0, fp16MatrixTimesVector<4,2> >         },
17035                 {       "OpMatrixTimesVector",  "4x3",          2,      VEC3,   MAT4X3, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  3, 16,  4,  0, fp16MatrixTimesVector<4,3> >         },
17036                 {       "OpMatrixTimesVector",  "4x4",          2,      VEC4,   MAT4X4, VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4, 16,  4,  0, fp16MatrixTimesVector<4,4> >         },
17037                 {       "OpMatrixTimesMatrix",  "2x2_2x2",      2,      MAT2X2, MAT2X2, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  4,  4,  0, fp16MatrixTimesMatrix<2,2,2,2> >     },
17038                 {       "OpMatrixTimesMatrix",  "2x2_3x2",      2,      MAT3X2, MAT2X2, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,3,2> >     },
17039                 {       "OpMatrixTimesMatrix",  "2x2_4x2",      2,      MAT4X2, MAT2X2, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  8,  0, fp16MatrixTimesMatrix<2,2,4,2> >     },
17040                 {       "OpMatrixTimesMatrix",  "2x3_2x2",      2,      MAT2X3, MAT2X3, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,3,2,2> >     },
17041                 {       "OpMatrixTimesMatrix",  "2x3_3x2",      2,      MAT3X3, MAT2X3, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,3,2> >     },
17042                 {       "OpMatrixTimesMatrix",  "2x3_4x2",      2,      MAT4X3, MAT2X3, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,3,4,2> >     },
17043                 {       "OpMatrixTimesMatrix",  "2x4_2x2",      2,      MAT2X4, MAT2X4, MAT2X2, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8,  4,  0, fp16MatrixTimesMatrix<2,4,2,2> >     },
17044                 {       "OpMatrixTimesMatrix",  "2x4_3x2",      2,      MAT3X4, MAT2X4, MAT3X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,3,2> >     },
17045                 {       "OpMatrixTimesMatrix",  "2x4_4x2",      2,      MAT4X4, MAT2X4, MAT4X2, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  8,  8,  0, fp16MatrixTimesMatrix<2,4,4,2> >     },
17046                 {       "OpMatrixTimesMatrix",  "3x2_2x3",      2,      MAT2X2, MAT3X2, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<3,2,2,3> >     },
17047                 {       "OpMatrixTimesMatrix",  "3x2_3x3",      2,      MAT3X2, MAT3X2, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,3,3> >     },
17048                 {       "OpMatrixTimesMatrix",  "3x2_4x3",      2,      MAT4X2, MAT3X2, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<3,2,4,3> >     },
17049                 {       "OpMatrixTimesMatrix",  "3x3_2x3",      2,      MAT2X3, MAT3X3, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,3,2,3> >     },
17050                 {       "OpMatrixTimesMatrix",  "3x3_3x3",      2,      MAT3X3, MAT3X3, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,3,3> >     },
17051                 {       "OpMatrixTimesMatrix",  "3x3_4x3",      2,      MAT4X3, MAT3X3, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,3,4,3> >     },
17052                 {       "OpMatrixTimesMatrix",  "3x4_2x3",      2,      MAT2X4, MAT3X4, MAT2X3, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<3,4,2,3> >     },
17053                 {       "OpMatrixTimesMatrix",  "3x4_3x3",      2,      MAT3X4, MAT3X4, MAT3X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,3,3> >     },
17054                 {       "OpMatrixTimesMatrix",  "3x4_4x3",      2,      MAT4X4, MAT3X4, MAT4X3, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<3,4,4,3> >     },
17055                 {       "OpMatrixTimesMatrix",  "4x2_2x4",      2,      MAT2X2, MAT4X2, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  8,  8,  0, fp16MatrixTimesMatrix<4,2,2,4> >     },
17056                 {       "OpMatrixTimesMatrix",  "4x2_3x4",      2,      MAT3X2, MAT4X2, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,3,4> >     },
17057                 {       "OpMatrixTimesMatrix",  "4x2_4x4",      2,      MAT4X2, MAT4X2, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  8, 16,  0, fp16MatrixTimesMatrix<4,2,4,4> >     },
17058                 {       "OpMatrixTimesMatrix",  "4x3_2x4",      2,      MAT2X3, MAT4X3, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,3,2,4> >     },
17059                 {       "OpMatrixTimesMatrix",  "4x3_3x4",      2,      MAT3X3, MAT4X3, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,3,4> >     },
17060                 {       "OpMatrixTimesMatrix",  "4x3_4x4",      2,      MAT4X3, MAT4X3, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,3,4,4> >     },
17061                 {       "OpMatrixTimesMatrix",  "4x4_2x4",      2,      MAT2X4, MAT4X4, MAT2X4, 0, &getInputDataD,      compareFP16ArithmeticFunc<  8, 16,  8,  0, fp16MatrixTimesMatrix<4,4,2,4> >     },
17062                 {       "OpMatrixTimesMatrix",  "4x4_3x4",      2,      MAT3X4, MAT4X4, MAT3X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,3,4> >     },
17063                 {       "OpMatrixTimesMatrix",  "4x4_4x4",      2,      MAT4X4, MAT4X4, MAT4X4, 0, &getInputDataD,      compareFP16ArithmeticFunc< 16, 16, 16,  0, fp16MatrixTimesMatrix<4,4,4,4> >     },
17064                 {       "OpOuterProduct",               "2x2",          2,      MAT2X2, VEC2,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  4,  2,  2,  0, fp16OuterProduct<2,2> >                      },
17065                 {       "OpOuterProduct",               "2x3",          2,      MAT2X3, VEC3,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  3,  2,  0, fp16OuterProduct<2,3> >                      },
17066                 {       "OpOuterProduct",               "2x4",          2,      MAT2X4, VEC4,   VEC2,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  4,  2,  0, fp16OuterProduct<2,4> >                      },
17067                 {       "OpOuterProduct",               "3x2",          2,      MAT3X2, VEC2,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  3,  0, fp16OuterProduct<3,2> >                      },
17068                 {       "OpOuterProduct",               "3x3",          2,      MAT3X3, VEC3,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  3,  0, fp16OuterProduct<3,3> >                      },
17069                 {       "OpOuterProduct",               "3x4",          2,      MAT3X4, VEC4,   VEC3,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  3,  0, fp16OuterProduct<3,4> >                      },
17070                 {       "OpOuterProduct",               "4x2",          2,      MAT4X2, VEC2,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc<  8,  2,  4,  0, fp16OuterProduct<4,2> >                      },
17071                 {       "OpOuterProduct",               "4x3",          2,      MAT4X3, VEC3,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  3,  4,  0, fp16OuterProduct<4,3> >                      },
17072                 {       "OpOuterProduct",               "4x4",          2,      MAT4X4, VEC4,   VEC4,   0, &getInputDataD,      compareFP16ArithmeticFunc< 16,  4,  4,  0, fp16OuterProduct<4,4> >                      },
17073                 {       "Determinant",                  "2x2",          1,      SCALAR, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1,  4,  0,  0, fp16Determinant<2> >                         },
17074                 {       "Determinant",                  "3x3",          1,      SCALAR, MAT3X3, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<3> >                         },
17075                 {       "Determinant",                  "4x4",          1,      SCALAR, MAT4X4, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  1, 16,  0,  0, fp16Determinant<4> >                         },
17076                 {       "MatrixInverse",                "2x2",          1,      MAT2X2, MAT2X2, NONE,   0, &getInputDataC,      compareFP16ArithmeticFunc<  4,  4,  0,  0, fp16Inverse<2> >                                     },
17077         };
17078
17079         for (deUint32 testFuncIdx = 0; testFuncIdx < DE_LENGTH_OF_ARRAY(testFuncs); ++testFuncIdx)
17080         {
17081                 const Math16TestFunc&   testFunc        = testFuncs[testFuncIdx];
17082
17083                 createFloat16ArithmeticFuncTest<SpecResource>(testCtx, *testGroup.get(), 0, testFunc);
17084         }
17085
17086         return testGroup.release();
17087 }
17088
17089 const string getNumberTypeName (const NumberType type)
17090 {
17091         if (type == NUMBERTYPE_INT32)
17092         {
17093                 return "int";
17094         }
17095         else if (type == NUMBERTYPE_UINT32)
17096         {
17097                 return "uint";
17098         }
17099         else if (type == NUMBERTYPE_FLOAT32)
17100         {
17101                 return "float";
17102         }
17103         else
17104         {
17105                 DE_ASSERT(false);
17106                 return "";
17107         }
17108 }
17109
17110 deInt32 getInt(de::Random& rnd)
17111 {
17112         return rnd.getInt(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
17113 }
17114
17115 const string repeatString (const string& str, int times)
17116 {
17117         string filler;
17118         for (int i = 0; i < times; ++i)
17119         {
17120                 filler += str;
17121         }
17122         return filler;
17123 }
17124
17125 const string getRandomConstantString (const NumberType type, de::Random& rnd)
17126 {
17127         if (type == NUMBERTYPE_INT32)
17128         {
17129                 return numberToString<deInt32>(getInt(rnd));
17130         }
17131         else if (type == NUMBERTYPE_UINT32)
17132         {
17133                 return numberToString<deUint32>(rnd.getUint32());
17134         }
17135         else if (type == NUMBERTYPE_FLOAT32)
17136         {
17137                 return numberToString<float>(rnd.getFloat());
17138         }
17139         else
17140         {
17141                 DE_ASSERT(false);
17142                 return "";
17143         }
17144 }
17145
17146 void createVectorCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17147 {
17148         map<string, string> params;
17149
17150         // Vec2 to Vec4
17151         for (int width = 2; width <= 4; ++width)
17152         {
17153                 const string randomConst = numberToString(getInt(rnd));
17154                 const string widthStr = numberToString(width);
17155                 const string composite_type = "${customType}vec" + widthStr;
17156                 const int index = rnd.getInt(0, width-1);
17157
17158                 params["type"]                  = "vec";
17159                 params["name"]                  = params["type"] + "_" + widthStr;
17160                 params["compositeDecl"]         = composite_type + " = OpTypeVector ${customType} " + widthStr +"\n";
17161                 params["compositeType"]         = composite_type;
17162                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
17163                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct " + composite_type + repeatString(" %filler", width) + "\n";
17164                 params["indexes"]               = numberToString(index);
17165                 testCases.push_back(params);
17166         }
17167 }
17168
17169 void createArrayCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17170 {
17171         const int limit = 10;
17172         map<string, string> params;
17173
17174         for (int width = 2; width <= limit; ++width)
17175         {
17176                 string randomConst = numberToString(getInt(rnd));
17177                 string widthStr = numberToString(width);
17178                 int index = rnd.getInt(0, width-1);
17179
17180                 params["type"]                  = "array";
17181                 params["name"]                  = params["type"] + "_" + widthStr;
17182                 params["compositeDecl"]         = string("%arraywidth = OpConstant %u32 " + widthStr + "\n")
17183                                                                                         +        "%composite = OpTypeArray ${customType} %arraywidth\n";
17184                 params["compositeType"]         = "%composite";
17185                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
17186                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
17187                 params["indexes"]               = numberToString(index);
17188                 testCases.push_back(params);
17189         }
17190 }
17191
17192 void createStructCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17193 {
17194         const int limit = 10;
17195         map<string, string> params;
17196
17197         for (int width = 2; width <= limit; ++width)
17198         {
17199                 string randomConst = numberToString(getInt(rnd));
17200                 int index = rnd.getInt(0, width-1);
17201
17202                 params["type"]                  = "struct";
17203                 params["name"]                  = params["type"] + "_" + numberToString(width);
17204                 params["compositeDecl"]         = "%composite = OpTypeStruct" + repeatString(" ${customType}", width) + "\n";
17205                 params["compositeType"]         = "%composite";
17206                 params["filler"]                = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n";
17207                 params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %filler", width) + "\n";
17208                 params["indexes"]               = numberToString(index);
17209                 testCases.push_back(params);
17210         }
17211 }
17212
17213 void createMatrixCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17214 {
17215         map<string, string> params;
17216
17217         // Vec2 to Vec4
17218         for (int width = 2; width <= 4; ++width)
17219         {
17220                 string widthStr = numberToString(width);
17221
17222                 for (int column = 2 ; column <= 4; ++column)
17223                 {
17224                         int index_0 = rnd.getInt(0, column-1);
17225                         int index_1 = rnd.getInt(0, width-1);
17226                         string columnStr = numberToString(column);
17227
17228                         params["type"]          = "matrix";
17229                         params["name"]          = params["type"] + "_" + widthStr + "x" + columnStr;
17230                         params["compositeDecl"] = string("%vectype   = OpTypeVector ${customType} " + widthStr + "\n")
17231                                                                                                 +        "%composite = OpTypeMatrix %vectype " + columnStr + "\n";
17232                         params["compositeType"] = "%composite";
17233
17234                         params["filler"]        = string("%filler    = OpConstant ${customType} ") + getRandomConstantString(type, rnd) + "\n"
17235                                                                                                 +        "%fillerVec = OpConstantComposite %vectype" + repeatString(" %filler", width) + "\n";
17236
17237                         params["compositeConstruct"]    = "%instance  = OpCompositeConstruct %composite" + repeatString(" %fillerVec", column) + "\n";
17238                         params["indexes"]       = numberToString(index_0) + " " + numberToString(index_1);
17239                         testCases.push_back(params);
17240                 }
17241         }
17242 }
17243
17244 void createCompositeCases (vector<map<string, string> >& testCases, de::Random& rnd, const NumberType type)
17245 {
17246         createVectorCompositeCases(testCases, rnd, type);
17247         createArrayCompositeCases(testCases, rnd, type);
17248         createStructCompositeCases(testCases, rnd, type);
17249         // Matrix only supports float types
17250         if (type == NUMBERTYPE_FLOAT32)
17251         {
17252                 createMatrixCompositeCases(testCases, rnd, type);
17253         }
17254 }
17255
17256 const string getAssemblyTypeDeclaration (const NumberType type)
17257 {
17258         switch (type)
17259         {
17260                 case NUMBERTYPE_INT32:          return "OpTypeInt 32 1";
17261                 case NUMBERTYPE_UINT32:         return "OpTypeInt 32 0";
17262                 case NUMBERTYPE_FLOAT32:        return "OpTypeFloat 32";
17263                 default:                        DE_ASSERT(false); return "";
17264         }
17265 }
17266
17267 const string getAssemblyTypeName (const NumberType type)
17268 {
17269         switch (type)
17270         {
17271                 case NUMBERTYPE_INT32:          return "%i32";
17272                 case NUMBERTYPE_UINT32:         return "%u32";
17273                 case NUMBERTYPE_FLOAT32:        return "%f32";
17274                 default:                        DE_ASSERT(false); return "";
17275         }
17276 }
17277
17278 const string specializeCompositeInsertShaderTemplate (const NumberType type, const map<string, string>& params)
17279 {
17280         map<string, string>     parameters(params);
17281
17282         const string customType = getAssemblyTypeName(type);
17283         map<string, string> substCustomType;
17284         substCustomType["customType"] = customType;
17285         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17286         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17287         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17288         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17289         parameters["customType"] = customType;
17290         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17291
17292         if (parameters.at("compositeType") != "%u32vec3")
17293         {
17294                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17295         }
17296
17297         return StringTemplate(
17298                 "OpCapability Shader\n"
17299                 "OpCapability Matrix\n"
17300                 "OpMemoryModel Logical GLSL450\n"
17301                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17302                 "OpExecutionMode %main LocalSize 1 1 1\n"
17303
17304                 "OpSource GLSL 430\n"
17305                 "OpName %main           \"main\"\n"
17306                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17307
17308                 // Decorators
17309                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17310                 "OpDecorate %buf BufferBlock\n"
17311                 "OpDecorate %indata DescriptorSet 0\n"
17312                 "OpDecorate %indata Binding 0\n"
17313                 "OpDecorate %outdata DescriptorSet 0\n"
17314                 "OpDecorate %outdata Binding 1\n"
17315                 "OpDecorate %customarr ArrayStride 4\n"
17316                 "${compositeDecorator}"
17317                 "OpMemberDecorate %buf 0 Offset 0\n"
17318
17319                 // General types
17320                 "%void      = OpTypeVoid\n"
17321                 "%voidf     = OpTypeFunction %void\n"
17322                 "%u32       = OpTypeInt 32 0\n"
17323                 "%i32       = OpTypeInt 32 1\n"
17324                 "%f32       = OpTypeFloat 32\n"
17325
17326                 // Composite declaration
17327                 "${compositeDecl}"
17328
17329                 // Constants
17330                 "${filler}"
17331
17332                 "${u32vec3Decl:opt}"
17333                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17334
17335                 // Inherited from custom
17336                 "%customptr = OpTypePointer Uniform ${customType}\n"
17337                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17338                 "%buf       = OpTypeStruct %customarr\n"
17339                 "%bufptr    = OpTypePointer Uniform %buf\n"
17340
17341                 "%indata    = OpVariable %bufptr Uniform\n"
17342                 "%outdata   = OpVariable %bufptr Uniform\n"
17343
17344                 "%id        = OpVariable %uvec3ptr Input\n"
17345                 "%zero      = OpConstant %i32 0\n"
17346
17347                 "%main      = OpFunction %void None %voidf\n"
17348                 "%label     = OpLabel\n"
17349                 "%idval     = OpLoad %u32vec3 %id\n"
17350                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17351
17352                 "%inloc     = OpAccessChain %customptr %indata %zero %x\n"
17353                 "%outloc    = OpAccessChain %customptr %outdata %zero %x\n"
17354                 // Read the input value
17355                 "%inval     = OpLoad ${customType} %inloc\n"
17356                 // Create the composite and fill it
17357                 "${compositeConstruct}"
17358                 // Insert the input value to a place
17359                 "%instance2 = OpCompositeInsert ${compositeType} %inval %instance ${indexes}\n"
17360                 // Read back the value from the position
17361                 "%out_val   = OpCompositeExtract ${customType} %instance2 ${indexes}\n"
17362                 // Store it in the output position
17363                 "             OpStore %outloc %out_val\n"
17364                 "             OpReturn\n"
17365                 "             OpFunctionEnd\n"
17366         ).specialize(parameters);
17367 }
17368
17369 template<typename T>
17370 BufferSp createCompositeBuffer(T number)
17371 {
17372         return BufferSp(new Buffer<T>(vector<T>(1, number)));
17373 }
17374
17375 tcu::TestCaseGroup* createOpCompositeInsertGroup (tcu::TestContext& testCtx)
17376 {
17377         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "opcompositeinsert", "Test the OpCompositeInsert instruction"));
17378         de::Random                                              rnd             (deStringHash(group->getName()));
17379
17380         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17381         {
17382                 NumberType                                              numberType              = NumberType(type);
17383                 const string                                    typeName                = getNumberTypeName(numberType);
17384                 const string                                    description             = "Test the OpCompositeInsert instruction with " + typeName + "s";
17385                 de::MovePtr<tcu::TestCaseGroup> subGroup                (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17386                 vector<map<string, string> >    testCases;
17387
17388                 createCompositeCases(testCases, rnd, numberType);
17389
17390                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17391                 {
17392                         ComputeShaderSpec       spec;
17393
17394                         spec.assembly = specializeCompositeInsertShaderTemplate(numberType, *test);
17395
17396                         switch (numberType)
17397                         {
17398                                 case NUMBERTYPE_INT32:
17399                                 {
17400                                         deInt32 number = getInt(rnd);
17401                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17402                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17403                                         break;
17404                                 }
17405                                 case NUMBERTYPE_UINT32:
17406                                 {
17407                                         deUint32 number = rnd.getUint32();
17408                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17409                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17410                                         break;
17411                                 }
17412                                 case NUMBERTYPE_FLOAT32:
17413                                 {
17414                                         float number = rnd.getFloat();
17415                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17416                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17417                                         break;
17418                                 }
17419                                 default:
17420                                         DE_ASSERT(false);
17421                         }
17422
17423                         spec.numWorkGroups = IVec3(1, 1, 1);
17424                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpCompositeInsert test", spec));
17425                 }
17426                 group->addChild(subGroup.release());
17427         }
17428         return group.release();
17429 }
17430
17431 struct AssemblyStructInfo
17432 {
17433         AssemblyStructInfo (const deUint32 comp, const deUint32 idx)
17434         : components    (comp)
17435         , index                 (idx)
17436         {}
17437
17438         deUint32 components;
17439         deUint32 index;
17440 };
17441
17442 const string specializeInBoundsShaderTemplate (const NumberType type, const AssemblyStructInfo& structInfo, const map<string, string>& params)
17443 {
17444         // Create the full index string
17445         string                          fullIndex       = numberToString(structInfo.index) + " " + params.at("indexes");
17446         // Convert it to list of indexes
17447         vector<string>          indexes         = de::splitString(fullIndex, ' ');
17448
17449         map<string, string>     parameters      (params);
17450         parameters["structType"]        = repeatString(" ${compositeType}", structInfo.components);
17451         parameters["structConstruct"]   = repeatString(" %instance", structInfo.components);
17452         parameters["insertIndexes"]     = fullIndex;
17453
17454         // In matrix cases the last two index is the CompositeExtract indexes
17455         const deUint32 extractIndexes = (parameters["type"] == "matrix") ? 2 : 1;
17456
17457         // Construct the extractIndex
17458         for (vector<string>::const_iterator index = indexes.end() - extractIndexes; index != indexes.end(); ++index)
17459         {
17460                 parameters["extractIndexes"] += " " + *index;
17461         }
17462
17463         // Remove the last 1 or 2 element depends on matrix case or not
17464         indexes.erase(indexes.end() - extractIndexes, indexes.end());
17465
17466         deUint32 id = 0;
17467         // Generate AccessChain index expressions (except for the last one, because we use ptr to the composite)
17468         for (vector<string>::const_iterator index = indexes.begin(); index != indexes.end(); ++index)
17469         {
17470                 string indexId = "%index_" + numberToString(id++);
17471                 parameters["accessChainConstDeclaration"] += indexId + "   = OpConstant %u32 " + *index + "\n";
17472                 parameters["accessChainIndexes"] += " " + indexId;
17473         }
17474
17475         parameters["compositeDecorator"] = (parameters["type"] == "array") ? "OpDecorate %composite ArrayStride 4\n" : "";
17476
17477         const string customType = getAssemblyTypeName(type);
17478         map<string, string> substCustomType;
17479         substCustomType["customType"] = customType;
17480         parameters["compositeDecl"] = StringTemplate(parameters.at("compositeDecl")).specialize(substCustomType);
17481         parameters["compositeType"] = StringTemplate(parameters.at("compositeType")).specialize(substCustomType);
17482         parameters["compositeConstruct"] = StringTemplate(parameters.at("compositeConstruct")).specialize(substCustomType);
17483         parameters["filler"] = StringTemplate(parameters.at("filler")).specialize(substCustomType);
17484         parameters["customType"] = customType;
17485
17486         const string compositeType = parameters.at("compositeType");
17487         map<string, string> substCompositeType;
17488         substCompositeType["compositeType"] = compositeType;
17489         parameters["structType"] = StringTemplate(parameters.at("structType")).specialize(substCompositeType);
17490         if (compositeType != "%u32vec3")
17491         {
17492                 parameters["u32vec3Decl"] = "%u32vec3   = OpTypeVector %u32 3\n";
17493         }
17494
17495         return StringTemplate(
17496                 "OpCapability Shader\n"
17497                 "OpCapability Matrix\n"
17498                 "OpMemoryModel Logical GLSL450\n"
17499                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17500                 "OpExecutionMode %main LocalSize 1 1 1\n"
17501
17502                 "OpSource GLSL 430\n"
17503                 "OpName %main           \"main\"\n"
17504                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17505                 // Decorators
17506                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17507                 "OpDecorate %buf BufferBlock\n"
17508                 "OpDecorate %indata DescriptorSet 0\n"
17509                 "OpDecorate %indata Binding 0\n"
17510                 "OpDecorate %outdata DescriptorSet 0\n"
17511                 "OpDecorate %outdata Binding 1\n"
17512                 "OpDecorate %customarr ArrayStride 4\n"
17513                 "${compositeDecorator}"
17514                 "OpMemberDecorate %buf 0 Offset 0\n"
17515                 // General types
17516                 "%void      = OpTypeVoid\n"
17517                 "%voidf     = OpTypeFunction %void\n"
17518                 "%i32       = OpTypeInt 32 1\n"
17519                 "%u32       = OpTypeInt 32 0\n"
17520                 "%f32       = OpTypeFloat 32\n"
17521                 // Custom types
17522                 "${compositeDecl}"
17523                 // %u32vec3 if not already declared in ${compositeDecl}
17524                 "${u32vec3Decl:opt}"
17525                 "%uvec3ptr  = OpTypePointer Input %u32vec3\n"
17526                 // Inherited from composite
17527                 "%composite_p = OpTypePointer Function ${compositeType}\n"
17528                 "%struct_t  = OpTypeStruct${structType}\n"
17529                 "%struct_p  = OpTypePointer Function %struct_t\n"
17530                 // Constants
17531                 "${filler}"
17532                 "${accessChainConstDeclaration}"
17533                 // Inherited from custom
17534                 "%customptr = OpTypePointer Uniform ${customType}\n"
17535                 "%customarr = OpTypeRuntimeArray ${customType}\n"
17536                 "%buf       = OpTypeStruct %customarr\n"
17537                 "%bufptr    = OpTypePointer Uniform %buf\n"
17538                 "%indata    = OpVariable %bufptr Uniform\n"
17539                 "%outdata   = OpVariable %bufptr Uniform\n"
17540
17541                 "%id        = OpVariable %uvec3ptr Input\n"
17542                 "%zero      = OpConstant %u32 0\n"
17543                 "%main      = OpFunction %void None %voidf\n"
17544                 "%label     = OpLabel\n"
17545                 "%struct_v  = OpVariable %struct_p Function\n"
17546                 "%idval     = OpLoad %u32vec3 %id\n"
17547                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17548                 // Create the input/output type
17549                 "%inloc     = OpInBoundsAccessChain %customptr %indata %zero %x\n"
17550                 "%outloc    = OpInBoundsAccessChain %customptr %outdata %zero %x\n"
17551                 // Read the input value
17552                 "%inval     = OpLoad ${customType} %inloc\n"
17553                 // Create the composite and fill it
17554                 "${compositeConstruct}"
17555                 // Create the struct and fill it with the composite
17556                 "%struct    = OpCompositeConstruct %struct_t${structConstruct}\n"
17557                 // Insert the value
17558                 "%comp_obj  = OpCompositeInsert %struct_t %inval %struct ${insertIndexes}\n"
17559                 // Store the object
17560                 "             OpStore %struct_v %comp_obj\n"
17561                 // Get deepest possible composite pointer
17562                 "%inner_ptr = OpInBoundsAccessChain %composite_p %struct_v${accessChainIndexes}\n"
17563                 "%read_obj  = OpLoad ${compositeType} %inner_ptr\n"
17564                 // Read back the stored value
17565                 "%read_val  = OpCompositeExtract ${customType} %read_obj${extractIndexes}\n"
17566                 "             OpStore %outloc %read_val\n"
17567                 "             OpReturn\n"
17568                 "             OpFunctionEnd\n"
17569         ).specialize(parameters);
17570 }
17571
17572 tcu::TestCaseGroup* createOpInBoundsAccessChainGroup (tcu::TestContext& testCtx)
17573 {
17574         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "opinboundsaccesschain", "Test the OpInBoundsAccessChain instruction"));
17575         de::Random                                              rnd                             (deStringHash(group->getName()));
17576
17577         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17578         {
17579                 NumberType                                              numberType      = NumberType(type);
17580                 const string                                    typeName        = getNumberTypeName(numberType);
17581                 const string                                    description     = "Test the OpInBoundsAccessChain instruction with " + typeName + "s";
17582                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17583
17584                 vector<map<string, string> >    testCases;
17585                 createCompositeCases(testCases, rnd, numberType);
17586
17587                 for (vector<map<string, string> >::const_iterator test = testCases.begin(); test != testCases.end(); ++test)
17588                 {
17589                         ComputeShaderSpec       spec;
17590
17591                         // Number of components inside of a struct
17592                         deUint32 structComponents = rnd.getInt(2, 8);
17593                         // Component index value
17594                         deUint32 structIndex = rnd.getInt(0, structComponents - 1);
17595                         AssemblyStructInfo structInfo(structComponents, structIndex);
17596
17597                         spec.assembly = specializeInBoundsShaderTemplate(numberType, structInfo, *test);
17598
17599                         switch (numberType)
17600                         {
17601                                 case NUMBERTYPE_INT32:
17602                                 {
17603                                         deInt32 number = getInt(rnd);
17604                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17605                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17606                                         break;
17607                                 }
17608                                 case NUMBERTYPE_UINT32:
17609                                 {
17610                                         deUint32 number = rnd.getUint32();
17611                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17612                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17613                                         break;
17614                                 }
17615                                 case NUMBERTYPE_FLOAT32:
17616                                 {
17617                                         float number = rnd.getFloat();
17618                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17619                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17620                                         break;
17621                                 }
17622                                 default:
17623                                         DE_ASSERT(false);
17624                         }
17625                         spec.numWorkGroups = IVec3(1, 1, 1);
17626                         subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, test->at("name").c_str(), "OpInBoundsAccessChain test", spec));
17627                 }
17628                 group->addChild(subGroup.release());
17629         }
17630         return group.release();
17631 }
17632
17633 // If the params missing, uninitialized case
17634 const string specializeDefaultOutputShaderTemplate (const NumberType type, const map<string, string>& params = map<string, string>())
17635 {
17636         map<string, string> parameters(params);
17637
17638         parameters["customType"]        = getAssemblyTypeName(type);
17639
17640         // Declare the const value, and use it in the initializer
17641         if (params.find("constValue") != params.end())
17642         {
17643                 parameters["variableInitializer"]       = " %const";
17644         }
17645         // Uninitialized case
17646         else
17647         {
17648                 parameters["commentDecl"]       = ";";
17649         }
17650
17651         return StringTemplate(
17652                 "OpCapability Shader\n"
17653                 "OpMemoryModel Logical GLSL450\n"
17654                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17655                 "OpExecutionMode %main LocalSize 1 1 1\n"
17656                 "OpSource GLSL 430\n"
17657                 "OpName %main           \"main\"\n"
17658                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17659                 // Decorators
17660                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17661                 "OpDecorate %indata DescriptorSet 0\n"
17662                 "OpDecorate %indata Binding 0\n"
17663                 "OpDecorate %outdata DescriptorSet 0\n"
17664                 "OpDecorate %outdata Binding 1\n"
17665                 "OpDecorate %in_arr ArrayStride 4\n"
17666                 "OpDecorate %in_buf BufferBlock\n"
17667                 "OpMemberDecorate %in_buf 0 Offset 0\n"
17668                 // Base types
17669                 "%void       = OpTypeVoid\n"
17670                 "%voidf      = OpTypeFunction %void\n"
17671                 "%u32        = OpTypeInt 32 0\n"
17672                 "%i32        = OpTypeInt 32 1\n"
17673                 "%f32        = OpTypeFloat 32\n"
17674                 "%uvec3      = OpTypeVector %u32 3\n"
17675                 "%uvec3ptr   = OpTypePointer Input %uvec3\n"
17676                 "${commentDecl:opt}%const      = OpConstant ${customType} ${constValue:opt}\n"
17677                 // Derived types
17678                 "%in_ptr     = OpTypePointer Uniform ${customType}\n"
17679                 "%in_arr     = OpTypeRuntimeArray ${customType}\n"
17680                 "%in_buf     = OpTypeStruct %in_arr\n"
17681                 "%in_bufptr  = OpTypePointer Uniform %in_buf\n"
17682                 "%indata     = OpVariable %in_bufptr Uniform\n"
17683                 "%outdata    = OpVariable %in_bufptr Uniform\n"
17684                 "%id         = OpVariable %uvec3ptr Input\n"
17685                 "%var_ptr    = OpTypePointer Function ${customType}\n"
17686                 // Constants
17687                 "%zero       = OpConstant %i32 0\n"
17688                 // Main function
17689                 "%main       = OpFunction %void None %voidf\n"
17690                 "%label      = OpLabel\n"
17691                 "%out_var    = OpVariable %var_ptr Function${variableInitializer:opt}\n"
17692                 "%idval      = OpLoad %uvec3 %id\n"
17693                 "%x          = OpCompositeExtract %u32 %idval 0\n"
17694                 "%inloc      = OpAccessChain %in_ptr %indata %zero %x\n"
17695                 "%outloc     = OpAccessChain %in_ptr %outdata %zero %x\n"
17696
17697                 "%outval     = OpLoad ${customType} %out_var\n"
17698                 "              OpStore %outloc %outval\n"
17699                 "              OpReturn\n"
17700                 "              OpFunctionEnd\n"
17701         ).specialize(parameters);
17702 }
17703
17704 bool compareFloats (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog& log)
17705 {
17706         DE_ASSERT(outputAllocs.size() != 0);
17707         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17708
17709         // Use custom epsilon because of the float->string conversion
17710         const float     epsilon = 0.00001f;
17711
17712         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17713         {
17714                 vector<deUint8> expectedBytes;
17715                 float                   expected;
17716                 float                   actual;
17717
17718                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17719                 memcpy(&expected, &expectedBytes.front(), expectedBytes.size());
17720                 memcpy(&actual, outputAllocs[outputNdx]->getHostPtr(), expectedBytes.size());
17721
17722                 // Test with epsilon
17723                 if (fabs(expected - actual) > epsilon)
17724                 {
17725                         log << TestLog::Message << "Error: The actual and expected values not matching."
17726                                 << " Expected: " << expected << " Actual: " << actual << " Epsilon: " << epsilon << TestLog::EndMessage;
17727                         return false;
17728                 }
17729         }
17730         return true;
17731 }
17732
17733 // Checks if the driver crash with uninitialized cases
17734 bool passthruVerify (const std::vector<Resource>&, const vector<AllocationSp>& outputAllocs, const std::vector<Resource>& expectedOutputs, TestLog&)
17735 {
17736         DE_ASSERT(outputAllocs.size() != 0);
17737         DE_ASSERT(outputAllocs.size() == expectedOutputs.size());
17738
17739         // Copy and discard the result.
17740         for (size_t outputNdx = 0; outputNdx < outputAllocs.size(); ++outputNdx)
17741         {
17742                 vector<deUint8> expectedBytes;
17743                 expectedOutputs[outputNdx].getBytes(expectedBytes);
17744
17745                 const size_t    width                   = expectedBytes.size();
17746                 vector<char>    data                    (width);
17747
17748                 memcpy(&data[0], outputAllocs[outputNdx]->getHostPtr(), width);
17749         }
17750         return true;
17751 }
17752
17753 tcu::TestCaseGroup* createShaderDefaultOutputGroup (tcu::TestContext& testCtx)
17754 {
17755         de::MovePtr<tcu::TestCaseGroup> group   (new tcu::TestCaseGroup(testCtx, "shader_default_output", "Test shader default output."));
17756         de::Random                                              rnd             (deStringHash(group->getName()));
17757
17758         for (int type = NUMBERTYPE_INT32; type != NUMBERTYPE_END32; ++type)
17759         {
17760                 NumberType                                              numberType      = NumberType(type);
17761                 const string                                    typeName        = getNumberTypeName(numberType);
17762                 const string                                    description     = "Test the OpVariable initializer with " + typeName + ".";
17763                 de::MovePtr<tcu::TestCaseGroup> subGroup        (new tcu::TestCaseGroup(testCtx, typeName.c_str(), description.c_str()));
17764
17765                 // 2 similar subcases (initialized and uninitialized)
17766                 for (int subCase = 0; subCase < 2; ++subCase)
17767                 {
17768                         ComputeShaderSpec spec;
17769                         spec.numWorkGroups = IVec3(1, 1, 1);
17770
17771                         map<string, string>                             params;
17772
17773                         switch (numberType)
17774                         {
17775                                 case NUMBERTYPE_INT32:
17776                                 {
17777                                         deInt32 number = getInt(rnd);
17778                                         spec.inputs.push_back(createCompositeBuffer<deInt32>(number));
17779                                         spec.outputs.push_back(createCompositeBuffer<deInt32>(number));
17780                                         params["constValue"] = numberToString(number);
17781                                         break;
17782                                 }
17783                                 case NUMBERTYPE_UINT32:
17784                                 {
17785                                         deUint32 number = rnd.getUint32();
17786                                         spec.inputs.push_back(createCompositeBuffer<deUint32>(number));
17787                                         spec.outputs.push_back(createCompositeBuffer<deUint32>(number));
17788                                         params["constValue"] = numberToString(number);
17789                                         break;
17790                                 }
17791                                 case NUMBERTYPE_FLOAT32:
17792                                 {
17793                                         float number = rnd.getFloat();
17794                                         spec.inputs.push_back(createCompositeBuffer<float>(number));
17795                                         spec.outputs.push_back(createCompositeBuffer<float>(number));
17796                                         spec.verifyIO = &compareFloats;
17797                                         params["constValue"] = numberToString(number);
17798                                         break;
17799                                 }
17800                                 default:
17801                                         DE_ASSERT(false);
17802                         }
17803
17804                         // Initialized subcase
17805                         if (!subCase)
17806                         {
17807                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType, params);
17808                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "initialized", "OpVariable initializer tests.", spec));
17809                         }
17810                         // Uninitialized subcase
17811                         else
17812                         {
17813                                 spec.assembly = specializeDefaultOutputShaderTemplate(numberType);
17814                                 spec.verifyIO = &passthruVerify;
17815                                 subGroup->addChild(new SpvAsmComputeShaderCase(testCtx, "uninitialized", "OpVariable initializer tests.", spec));
17816                         }
17817                 }
17818                 group->addChild(subGroup.release());
17819         }
17820         return group.release();
17821 }
17822
17823 tcu::TestCaseGroup* createOpNopTests (tcu::TestContext& testCtx)
17824 {
17825         de::MovePtr<tcu::TestCaseGroup> testGroup (new tcu::TestCaseGroup(testCtx, "opnop", "Test OpNop"));
17826         RGBA                                                    defaultColors[4];
17827         map<string, string>                             opNopFragments;
17828
17829         getDefaultColors(defaultColors);
17830
17831         opNopFragments["testfun"]               =
17832                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17833                 "%param1 = OpFunctionParameter %v4f32\n"
17834                 "%label_testfun = OpLabel\n"
17835                 "OpNop\n"
17836                 "OpNop\n"
17837                 "OpNop\n"
17838                 "OpNop\n"
17839                 "OpNop\n"
17840                 "OpNop\n"
17841                 "OpNop\n"
17842                 "OpNop\n"
17843                 "%a = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17844                 "%b = OpFAdd %f32 %a %a\n"
17845                 "OpNop\n"
17846                 "%c = OpFSub %f32 %b %a\n"
17847                 "%ret = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17848                 "OpNop\n"
17849                 "OpNop\n"
17850                 "OpReturnValue %ret\n"
17851                 "OpFunctionEnd\n";
17852
17853         createTestsForAllStages("opnop", defaultColors, defaultColors, opNopFragments, testGroup.get());
17854
17855         return testGroup.release();
17856 }
17857
17858 tcu::TestCaseGroup* createOpNameTests (tcu::TestContext& testCtx)
17859 {
17860         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "opname","Test OpName"));
17861         RGBA                                                    defaultColors[4];
17862         map<string, string>                             opNameFragments;
17863
17864         getDefaultColors(defaultColors);
17865
17866         opNameFragments["testfun"] =
17867                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
17868                 "%param1     = OpFunctionParameter %v4f32\n"
17869                 "%label_func = OpLabel\n"
17870                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
17871                 "%b          = OpFAdd %f32 %a %a\n"
17872                 "%c          = OpFSub %f32 %b %a\n"
17873                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
17874                 "OpReturnValue %ret\n"
17875                 "OpFunctionEnd\n";
17876
17877         opNameFragments["debug"] =
17878                 "OpName %BP_main \"not_main\"";
17879
17880         createTestsForAllStages("opname", defaultColors, defaultColors, opNameFragments, testGroup.get());
17881
17882         return testGroup.release();
17883 }
17884
17885 tcu::TestCaseGroup* createFloat16Tests (tcu::TestContext& testCtx)
17886 {
17887         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17888
17889         testGroup->addChild(createOpConstantFloat16Tests(testCtx));
17890         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITH_NAN));
17891         testGroup->addChild(createFloat16LogicalSet<GraphicsResources>(testCtx, TEST_WITHOUT_NAN));
17892         testGroup->addChild(createFloat16FuncSet<GraphicsResources>(testCtx));
17893         testGroup->addChild(createDerivativeTests<256, 1>(testCtx));
17894         testGroup->addChild(createDerivativeTests<256, 2>(testCtx));
17895         testGroup->addChild(createDerivativeTests<256, 4>(testCtx));
17896         testGroup->addChild(createFloat16VectorExtractSet<GraphicsResources>(testCtx));
17897         testGroup->addChild(createFloat16VectorInsertSet<GraphicsResources>(testCtx));
17898         testGroup->addChild(createFloat16VectorShuffleSet<GraphicsResources>(testCtx));
17899         testGroup->addChild(createFloat16CompositeConstructSet<GraphicsResources>(testCtx));
17900         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeExtract"));
17901         testGroup->addChild(createFloat16CompositeInsertExtractSet<GraphicsResources>(testCtx, "OpCompositeInsert"));
17902         testGroup->addChild(createFloat16ArithmeticSet<GraphicsResources>(testCtx));
17903         testGroup->addChild(createFloat16ArithmeticSet<1, GraphicsResources>(testCtx));
17904         testGroup->addChild(createFloat16ArithmeticSet<2, GraphicsResources>(testCtx));
17905         testGroup->addChild(createFloat16ArithmeticSet<3, GraphicsResources>(testCtx));
17906         testGroup->addChild(createFloat16ArithmeticSet<4, GraphicsResources>(testCtx));
17907
17908         return testGroup.release();
17909 }
17910
17911 tcu::TestCaseGroup* createFloat16Group (tcu::TestContext& testCtx)
17912 {
17913         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "float16", "Float 16 tests"));
17914
17915         testGroup->addChild(createFloat16OpConstantCompositeGroup(testCtx));
17916         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITH_NAN));
17917         testGroup->addChild(createFloat16LogicalSet<ComputeShaderSpec>(testCtx, TEST_WITHOUT_NAN));
17918         testGroup->addChild(createFloat16FuncSet<ComputeShaderSpec>(testCtx));
17919         testGroup->addChild(createFloat16VectorExtractSet<ComputeShaderSpec>(testCtx));
17920         testGroup->addChild(createFloat16VectorInsertSet<ComputeShaderSpec>(testCtx));
17921         testGroup->addChild(createFloat16VectorShuffleSet<ComputeShaderSpec>(testCtx));
17922         testGroup->addChild(createFloat16CompositeConstructSet<ComputeShaderSpec>(testCtx));
17923         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeExtract"));
17924         testGroup->addChild(createFloat16CompositeInsertExtractSet<ComputeShaderSpec>(testCtx, "OpCompositeInsert"));
17925         testGroup->addChild(createFloat16ArithmeticSet<ComputeShaderSpec>(testCtx));
17926         testGroup->addChild(createFloat16ArithmeticSet<1, ComputeShaderSpec>(testCtx));
17927         testGroup->addChild(createFloat16ArithmeticSet<2, ComputeShaderSpec>(testCtx));
17928         testGroup->addChild(createFloat16ArithmeticSet<3, ComputeShaderSpec>(testCtx));
17929         testGroup->addChild(createFloat16ArithmeticSet<4, ComputeShaderSpec>(testCtx));
17930
17931         return testGroup.release();
17932 }
17933
17934 tcu::TestCaseGroup* createBoolMixedBitSizeGroup (tcu::TestContext& testCtx)
17935 {
17936         de::MovePtr<tcu::TestCaseGroup> group                   (new tcu::TestCaseGroup(testCtx, "mixed_bitsize", "Tests boolean operands produced from instructions of different bit-sizes"));
17937
17938         de::Random                                              rnd                             (deStringHash(group->getName()));
17939         const int               numElements             = 100;
17940         vector<float>   inputData               (numElements, 0);
17941         vector<float>   outputData              (numElements, 0);
17942         fillRandomScalars(rnd, 0.0f, 100.0f, &inputData[0], 100);
17943
17944         const StringTemplate                    shaderTemplate  (
17945                 "${CAPS}\n"
17946                 "OpMemoryModel Logical GLSL450\n"
17947                 "OpEntryPoint GLCompute %main \"main\" %id\n"
17948                 "OpExecutionMode %main LocalSize 1 1 1\n"
17949                 "OpSource GLSL 430\n"
17950                 "OpName %main           \"main\"\n"
17951                 "OpName %id             \"gl_GlobalInvocationID\"\n"
17952
17953                 "OpDecorate %id BuiltIn GlobalInvocationId\n"
17954
17955                 + string(getComputeAsmInputOutputBufferTraits()) + string(getComputeAsmCommonTypes()) + string(getComputeAsmInputOutputBuffer()) +
17956
17957                 "%id        = OpVariable %uvec3ptr Input\n"
17958                 "${CONST}\n"
17959                 "%main      = OpFunction %void None %voidf\n"
17960                 "%label     = OpLabel\n"
17961                 "%idval     = OpLoad %uvec3 %id\n"
17962                 "%x         = OpCompositeExtract %u32 %idval 0\n"
17963                 "%inloc     = OpAccessChain %f32ptr %indata %c0i32 %x\n"
17964
17965                 "${TEST}\n"
17966
17967                 "%outloc    = OpAccessChain %f32ptr %outdata %c0i32 %x\n"
17968                 "             OpStore %outloc %res\n"
17969                 "             OpReturn\n"
17970                 "             OpFunctionEnd\n"
17971         );
17972
17973         // Each test case produces 4 boolean values, and we want each of these values
17974         // to come froma different combination of the available bit-sizes, so compute
17975         // all possible combinations here.
17976         vector<deUint32>        widths;
17977         widths.push_back(32);
17978         widths.push_back(16);
17979         widths.push_back(8);
17980
17981         vector<IVec4>   cases;
17982         for (size_t width0 = 0; width0 < widths.size(); width0++)
17983         {
17984                 for (size_t width1 = 0; width1 < widths.size(); width1++)
17985                 {
17986                         for (size_t width2 = 0; width2 < widths.size(); width2++)
17987                         {
17988                                 for (size_t width3 = 0; width3 < widths.size(); width3++)
17989                                 {
17990                                         cases.push_back(IVec4(widths[width0], widths[width1], widths[width2], widths[width3]));
17991                                 }
17992                         }
17993                 }
17994         }
17995
17996         for (size_t caseNdx = 0; caseNdx < cases.size(); caseNdx++)
17997         {
17998                 /// Skip cases where all bitsizes are the same, we are only interested in testing booleans produced from instructions with different native bit-sizes
17999                 if (cases[caseNdx][0] == cases[caseNdx][1] && cases[caseNdx][0] == cases[caseNdx][2] && cases[caseNdx][0] == cases[caseNdx][3])
18000                         continue;
18001
18002                 map<string, string>     specializations;
18003                 ComputeShaderSpec       spec;
18004
18005                 // Inject appropriate capabilities and reference constants depending
18006                 // on the bit-sizes required by this test case
18007                 bool hasFloat32 = cases[caseNdx][0] == 32 || cases[caseNdx][1] == 32 || cases[caseNdx][2] == 32 || cases[caseNdx][3] == 32;
18008                 bool hasFloat16 = cases[caseNdx][0] == 16 || cases[caseNdx][1] == 16 || cases[caseNdx][2] == 16 || cases[caseNdx][3] == 16;
18009                 bool hasInt8    = cases[caseNdx][0] == 8 || cases[caseNdx][1] == 8 || cases[caseNdx][2] == 8 || cases[caseNdx][3] == 8;
18010
18011                 string capsStr  = "OpCapability Shader\n";
18012                 string constStr =
18013                         "%c0i32     = OpConstant %i32 0\n"
18014                         "%c1f32     = OpConstant %f32 1.0\n"
18015                         "%c0f32     = OpConstant %f32 0.0\n";
18016
18017                 if (hasFloat32)
18018                 {
18019                         constStr        +=
18020                                 "%c10f32    = OpConstant %f32 10.0\n"
18021                                 "%c25f32    = OpConstant %f32 25.0\n"
18022                                 "%c50f32    = OpConstant %f32 50.0\n"
18023                                 "%c90f32    = OpConstant %f32 90.0\n";
18024                 }
18025
18026                 if (hasFloat16)
18027                 {
18028                         capsStr         += "OpCapability Float16\n";
18029                         constStr        +=
18030                                 "%f16       = OpTypeFloat 16\n"
18031                                 "%c10f16    = OpConstant %f16 10.0\n"
18032                                 "%c25f16    = OpConstant %f16 25.0\n"
18033                                 "%c50f16    = OpConstant %f16 50.0\n"
18034                                 "%c90f16    = OpConstant %f16 90.0\n";
18035                 }
18036
18037                 if (hasInt8)
18038                 {
18039                         capsStr         += "OpCapability Int8\n";
18040                         constStr        +=
18041                                 "%i8        = OpTypeInt 8 1\n"
18042                                 "%c10i8     = OpConstant %i8 10\n"
18043                                 "%c25i8     = OpConstant %i8 25\n"
18044                                 "%c50i8     = OpConstant %i8 50\n"
18045                                 "%c90i8     = OpConstant %i8 90\n";
18046                 }
18047
18048                 // Each invocation reads a different float32 value as input. Depending on
18049                 // the bit-sizes required by the particular test case, we also produce
18050                 // float16 and/or and int8 values by converting from the 32-bit float.
18051                 string testStr  = "";
18052                 testStr                 += "%inval32   = OpLoad %f32 %inloc\n";
18053                 if (hasFloat16)
18054                         testStr         += "%inval16   = OpFConvert %f16 %inval32\n";
18055                 if (hasInt8)
18056                         testStr         += "%inval8    = OpConvertFToS %i8 %inval32\n";
18057
18058                 // Because conversions from Float to Int round towards 0 we want our "greater" comparisons to be >=,
18059                 // that way a float32/float16 comparison such as 50.6f >= 50.0f will preserve its result
18060                 // when converted to int8, since FtoS(50.6f) results in 50. For "less" comparisons, it is the
18061                 // other way around, so in this case we want < instead of <=.
18062                 if (cases[caseNdx][0] == 32)
18063                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval32 %c25f32\n";
18064                 else if (cases[caseNdx][0] == 16)
18065                         testStr         += "%cmp1      = OpFOrdGreaterThanEqual %bool %inval16 %c25f16\n";
18066                 else
18067                         testStr         += "%cmp1      = OpSGreaterThanEqual %bool %inval8 %c25i8\n";
18068
18069                 if (cases[caseNdx][1] == 32)
18070                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval32 %c50f32\n";
18071                 else if (cases[caseNdx][1] == 16)
18072                         testStr         += "%cmp2      = OpFOrdLessThan %bool %inval16 %c50f16\n";
18073                 else
18074                         testStr         += "%cmp2      = OpSLessThan %bool %inval8 %c50i8\n";
18075
18076                 if (cases[caseNdx][2] == 32)
18077                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval32 %c10f32\n";
18078                 else if (cases[caseNdx][2] == 16)
18079                         testStr         += "%cmp3      = OpFOrdLessThan %bool %inval16 %c10f16\n";
18080                 else
18081                         testStr         += "%cmp3      = OpSLessThan %bool %inval8 %c10i8\n";
18082
18083                 if (cases[caseNdx][3] == 32)
18084                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval32 %c90f32\n";
18085                 else if (cases[caseNdx][3] == 16)
18086                         testStr         += "%cmp4      = OpFOrdGreaterThanEqual %bool %inval16 %c90f16\n";
18087                 else
18088                         testStr         += "%cmp4      = OpSGreaterThanEqual %bool %inval8 %c90i8\n";
18089
18090                 testStr                 += "%and1      = OpLogicalAnd %bool %cmp1 %cmp2\n";
18091                 testStr                 += "%or1       = OpLogicalOr %bool %cmp3 %cmp4\n";
18092                 testStr                 += "%or2       = OpLogicalOr %bool %and1 %or1\n";
18093                 testStr                 += "%not1      = OpLogicalNot %bool %or2\n";
18094                 testStr                 += "%res       = OpSelect %f32 %not1 %c1f32 %c0f32\n";
18095
18096                 specializations["CAPS"]         = capsStr;
18097                 specializations["CONST"]        = constStr;
18098                 specializations["TEST"]         = testStr;
18099
18100                 // Compute expected result by evaluating the boolean expression computed in the shader for each input value
18101                 for (size_t ndx = 0; ndx < numElements; ++ndx)
18102                         outputData[ndx] = !((inputData[ndx] >= 25.0f && inputData[ndx] < 50.0f) || (inputData[ndx] < 10.0f || inputData[ndx] >= 90.0f));
18103
18104                 spec.assembly = shaderTemplate.specialize(specializations);
18105                 spec.inputs.push_back(BufferSp(new Float32Buffer(inputData)));
18106                 spec.outputs.push_back(BufferSp(new Float32Buffer(outputData)));
18107                 spec.numWorkGroups = IVec3(numElements, 1, 1);
18108                 if (hasFloat16)
18109                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_FLOAT16;
18110                 if (hasInt8)
18111                         spec.requestedVulkanFeatures.extFloat16Int8 |= EXTFLOAT16INT8FEATURES_INT8;
18112                 spec.extensions.push_back("VK_KHR_shader_float16_int8");
18113
18114                 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]);
18115                 group->addChild(new SpvAsmComputeShaderCase(testCtx, testName.c_str(), "", spec));
18116         }
18117
18118         return group.release();
18119 }
18120
18121 tcu::TestCaseGroup* createBoolGroup (tcu::TestContext& testCtx)
18122 {
18123         de::MovePtr<tcu::TestCaseGroup>         testGroup                       (new tcu::TestCaseGroup(testCtx, "bool", "Boolean tests"));
18124
18125         testGroup->addChild(createBoolMixedBitSizeGroup(testCtx));
18126
18127         return testGroup.release();
18128 }
18129
18130 tcu::TestCaseGroup* createOpNameAbuseTests (tcu::TestContext& testCtx)
18131 {
18132         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opname_abuse", "OpName abuse tests"));
18133         vector<CaseParameter>                   abuseCases;
18134         RGBA                                                    defaultColors[4];
18135         map<string, string>                             opNameFragments;
18136
18137         getOpNameAbuseCases(abuseCases);
18138         getDefaultColors(defaultColors);
18139
18140         opNameFragments["testfun"] =
18141                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18142                 "%param1     = OpFunctionParameter %v4f32\n"
18143                 "%label_func = OpLabel\n"
18144                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
18145                 "%b          = OpFAdd %f32 %a %a\n"
18146                 "%c          = OpFSub %f32 %b %a\n"
18147                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %c %c_i32_0\n"
18148                 "OpReturnValue %ret\n"
18149                 "OpFunctionEnd\n";
18150
18151         for (unsigned int i = 0; i < abuseCases.size(); i++)
18152         {
18153                 string casename;
18154                 casename = string("main") + abuseCases[i].name;
18155
18156                 opNameFragments["debug"] =
18157                         "OpName %BP_main \"" + abuseCases[i].param + "\"";
18158
18159                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18160         }
18161
18162         for (unsigned int i = 0; i < abuseCases.size(); i++)
18163         {
18164                 string casename;
18165                 casename = string("b") + abuseCases[i].name;
18166
18167                 opNameFragments["debug"] =
18168                         "OpName %b \"" + abuseCases[i].param + "\"";
18169
18170                 createTestsForAllStages(casename, defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18171         }
18172
18173         {
18174                 opNameFragments["debug"] =
18175                         "OpName %test_code \"name1\"\n"
18176                         "OpName %param1    \"name2\"\n"
18177                         "OpName %a         \"name3\"\n"
18178                         "OpName %b         \"name4\"\n"
18179                         "OpName %c         \"name5\"\n"
18180                         "OpName %ret       \"name6\"\n";
18181
18182                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18183         }
18184
18185         {
18186                 opNameFragments["debug"] =
18187                         "OpName %test_code \"the_same\"\n"
18188                         "OpName %param1    \"the_same\"\n"
18189                         "OpName %a         \"the_same\"\n"
18190                         "OpName %b         \"the_same\"\n"
18191                         "OpName %c         \"the_same\"\n"
18192                         "OpName %ret       \"the_same\"\n";
18193
18194                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18195         }
18196
18197         {
18198                 opNameFragments["debug"] =
18199                         "OpName %BP_main \"to_be\"\n"
18200                         "OpName %BP_main \"or_not\"\n"
18201                         "OpName %BP_main \"to_be\"\n";
18202
18203                 createTestsForAllStages("main_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18204         }
18205
18206         {
18207                 opNameFragments["debug"] =
18208                         "OpName %b \"to_be\"\n"
18209                         "OpName %b \"or_not\"\n"
18210                         "OpName %b \"to_be\"\n";
18211
18212                 createTestsForAllStages("b_has_multiple_names", defaultColors, defaultColors, opNameFragments, abuseGroup.get());
18213         }
18214
18215         return abuseGroup.release();
18216 }
18217
18218
18219 tcu::TestCaseGroup* createOpMemberNameAbuseTests (tcu::TestContext& testCtx)
18220 {
18221         de::MovePtr<tcu::TestCaseGroup> abuseGroup(new tcu::TestCaseGroup(testCtx, "opmembername_abuse", "OpName abuse tests"));
18222         vector<CaseParameter>                   abuseCases;
18223         RGBA                                                    defaultColors[4];
18224         map<string, string>                             opMemberNameFragments;
18225
18226         getOpNameAbuseCases(abuseCases);
18227         getDefaultColors(defaultColors);
18228
18229         opMemberNameFragments["pre_main"] =
18230                 "%f3str = OpTypeStruct %f32 %f32 %f32\n";
18231
18232         opMemberNameFragments["testfun"] =
18233                 "%test_code  = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18234                 "%param1     = OpFunctionParameter %v4f32\n"
18235                 "%label_func = OpLabel\n"
18236                 "%a          = OpVectorExtractDynamic %f32 %param1 %c_i32_0\n"
18237                 "%b          = OpFAdd %f32 %a %a\n"
18238                 "%c          = OpFSub %f32 %b %a\n"
18239                 "%cstr       = OpCompositeConstruct %f3str %c %c %c\n"
18240                 "%d          = OpCompositeExtract %f32 %cstr 0\n"
18241                 "%ret        = OpVectorInsertDynamic %v4f32 %param1 %d %c_i32_0\n"
18242                 "OpReturnValue %ret\n"
18243                 "OpFunctionEnd\n";
18244
18245         for (unsigned int i = 0; i < abuseCases.size(); i++)
18246         {
18247                 string casename;
18248                 casename = string("f3str_x") + abuseCases[i].name;
18249
18250                 opMemberNameFragments["debug"] =
18251                         "OpMemberName %f3str 0 \"" + abuseCases[i].param + "\"";
18252
18253                 createTestsForAllStages(casename, defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18254         }
18255
18256         {
18257                 opMemberNameFragments["debug"] =
18258                         "OpMemberName %f3str 0 \"name1\"\n"
18259                         "OpMemberName %f3str 1 \"name2\"\n"
18260                         "OpMemberName %f3str 2 \"name3\"\n";
18261
18262                 createTestsForAllStages("everything_named", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18263         }
18264
18265         {
18266                 opMemberNameFragments["debug"] =
18267                         "OpMemberName %f3str 0 \"the_same\"\n"
18268                         "OpMemberName %f3str 1 \"the_same\"\n"
18269                         "OpMemberName %f3str 2 \"the_same\"\n";
18270
18271                 createTestsForAllStages("everything_named_the_same", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18272         }
18273
18274         {
18275                 opMemberNameFragments["debug"] =
18276                         "OpMemberName %f3str 0 \"to_be\"\n"
18277                         "OpMemberName %f3str 1 \"or_not\"\n"
18278                         "OpMemberName %f3str 0 \"to_be\"\n"
18279                         "OpMemberName %f3str 2 \"makes_no\"\n"
18280                         "OpMemberName %f3str 0 \"difference\"\n"
18281                         "OpMemberName %f3str 0 \"to_me\"\n";
18282
18283
18284                 createTestsForAllStages("f3str_x_has_multiple_names", defaultColors, defaultColors, opMemberNameFragments, abuseGroup.get());
18285         }
18286
18287         return abuseGroup.release();
18288 }
18289
18290 vector<deUint32> getSparseIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18291 {
18292         vector<deUint32>        result;
18293         de::Random                      rnd             (seed);
18294
18295         result.reserve(numDataPoints);
18296
18297         for (deUint32 dataPointNdx = 0; dataPointNdx < numDataPoints; ++dataPointNdx)
18298                 result.push_back(rnd.getUint32());
18299
18300         return result;
18301 }
18302
18303 vector<deUint32> getSparseIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2)
18304 {
18305         vector<deUint32>        result;
18306
18307         result.reserve(inData1.size());
18308
18309         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18310                 result.push_back(inData1[dataPointNdx] + inData2[dataPointNdx]);
18311
18312         return result;
18313 }
18314
18315 template<class SpecResource>
18316 void createSparseIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18317 {
18318         const deUint32                  numDataPoints   = 16;
18319         const std::string               testName                ("sparse_ids");
18320         const deUint32                  seed                    (deStringHash(testName.c_str()));
18321         const vector<deUint32>  inData1                 (getSparseIdsAbuseData(numDataPoints, seed + 1));
18322         const vector<deUint32>  inData2                 (getSparseIdsAbuseData(numDataPoints, seed + 2));
18323         const vector<deUint32>  outData                 (getSparseIdsAbuseResults(inData1, inData2));
18324         const StringTemplate    preMain
18325         (
18326                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18327                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18328                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18329                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18330                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18331                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18332                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18333                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18334         );
18335         const StringTemplate    decoration
18336         (
18337                 "OpDecorate %ra_u32 ArrayStride 4\n"
18338                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18339                 "OpDecorate %SSBO32 BufferBlock\n"
18340                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18341                 "OpDecorate %ssbo_src0 Binding 0\n"
18342                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18343                 "OpDecorate %ssbo_src1 Binding 1\n"
18344                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18345                 "OpDecorate %ssbo_dst Binding 2\n"
18346         );
18347         const StringTemplate    testFun
18348         (
18349                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18350                 "    %param = OpFunctionParameter %v4f32\n"
18351
18352                 "    %entry = OpLabel\n"
18353                 "        %i = OpVariable %fp_i32 Function\n"
18354                 "             OpStore %i %c_i32_0\n"
18355                 "             OpBranch %loop\n"
18356
18357                 "     %loop = OpLabel\n"
18358                 "    %i_cmp = OpLoad %i32 %i\n"
18359                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18360                 "             OpLoopMerge %merge %next None\n"
18361                 "             OpBranchConditional %lt %write %merge\n"
18362
18363                 "    %write = OpLabel\n"
18364                 "      %ndx = OpLoad %i32 %i\n"
18365
18366                 "      %127 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18367                 "      %128 = OpLoad %u32 %127\n"
18368
18369                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18370                 "  %4194000 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18371                 "  %4194001 = OpLoad %u32 %4194000\n"
18372
18373                 "  %2097151 = OpIAdd %u32 %128 %4194001\n"
18374                 "  %2097152 = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18375                 "             OpStore %2097152 %2097151\n"
18376                 "             OpBranch %next\n"
18377
18378                 "     %next = OpLabel\n"
18379                 "    %i_cur = OpLoad %i32 %i\n"
18380                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18381                 "             OpStore %i %i_new\n"
18382                 "             OpBranch %loop\n"
18383
18384                 "    %merge = OpLabel\n"
18385                 "             OpReturnValue %param\n"
18386
18387                 "             OpFunctionEnd\n"
18388         );
18389         SpecResource                    specResource;
18390         map<string, string>             specs;
18391         VulkanFeatures                  features;
18392         map<string, string>             fragments;
18393         vector<string>                  extensions;
18394
18395         specs["num_data_points"]        = de::toString(numDataPoints);
18396
18397         fragments["decoration"]         = decoration.specialize(specs);
18398         fragments["pre_main"]           = preMain.specialize(specs);
18399         fragments["testfun"]            = testFun.specialize(specs);
18400
18401         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18402         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18403         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18404
18405         features.coreFeatures.vertexPipelineStoresAndAtomics    = true;
18406         features.coreFeatures.fragmentStoresAndAtomics                  = true;
18407
18408         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18409 }
18410
18411 vector<deUint32> getLotsIdsAbuseData (const deUint32 numDataPoints, const deUint32 seed)
18412 {
18413         vector<deUint32>        result;
18414         de::Random                      rnd             (seed);
18415
18416         result.reserve(numDataPoints);
18417
18418         // Fixed value
18419         result.push_back(1u);
18420
18421         // Random values
18422         for (deUint32 dataPointNdx = 1; dataPointNdx < numDataPoints; ++dataPointNdx)
18423                 result.push_back(rnd.getUint8());
18424
18425         return result;
18426 }
18427
18428 vector<deUint32> getLotsIdsAbuseResults (const vector<deUint32>& inData1, const vector<deUint32>& inData2, const deUint32 count)
18429 {
18430         vector<deUint32>        result;
18431
18432         result.reserve(inData1.size());
18433
18434         for (size_t dataPointNdx = 0; dataPointNdx < inData1.size(); ++dataPointNdx)
18435                 result.push_back(inData1[dataPointNdx] + count * inData2[dataPointNdx]);
18436
18437         return result;
18438 }
18439
18440 template<class SpecResource>
18441 void createLotsIdsAbuseTest (tcu::TestContext& testCtx, de::MovePtr<tcu::TestCaseGroup>& testGroup)
18442 {
18443         const deUint32                  numDataPoints   = 16;
18444         const deUint32                  firstNdx                = 100u;
18445         const deUint32                  sequenceCount   = 10000u;
18446         const std::string               testName                ("lots_ids");
18447         const deUint32                  seed                    (deStringHash(testName.c_str()));
18448         const vector<deUint32>  inData1                 (getLotsIdsAbuseData(numDataPoints, seed + 1));
18449         const vector<deUint32>  inData2                 (getLotsIdsAbuseData(numDataPoints, seed + 2));
18450         const vector<deUint32>  outData                 (getLotsIdsAbuseResults(inData1, inData2, sequenceCount));
18451         const StringTemplate preMain
18452         (
18453                 "%c_i32_ndp = OpConstant %i32 ${num_data_points}\n"
18454                 "   %up_u32 = OpTypePointer Uniform %u32\n"
18455                 "   %ra_u32 = OpTypeArray %u32 %c_i32_ndp\n"
18456                 "   %SSBO32 = OpTypeStruct %ra_u32\n"
18457                 "%up_SSBO32 = OpTypePointer Uniform %SSBO32\n"
18458                 "%ssbo_src0 = OpVariable %up_SSBO32 Uniform\n"
18459                 "%ssbo_src1 = OpVariable %up_SSBO32 Uniform\n"
18460                 " %ssbo_dst = OpVariable %up_SSBO32 Uniform\n"
18461         );
18462         const StringTemplate decoration
18463         (
18464                 "OpDecorate %ra_u32 ArrayStride 4\n"
18465                 "OpMemberDecorate %SSBO32 0 Offset 0\n"
18466                 "OpDecorate %SSBO32 BufferBlock\n"
18467                 "OpDecorate %ssbo_src0 DescriptorSet 0\n"
18468                 "OpDecorate %ssbo_src0 Binding 0\n"
18469                 "OpDecorate %ssbo_src1 DescriptorSet 0\n"
18470                 "OpDecorate %ssbo_src1 Binding 1\n"
18471                 "OpDecorate %ssbo_dst DescriptorSet 0\n"
18472                 "OpDecorate %ssbo_dst Binding 2\n"
18473         );
18474         const StringTemplate testFun
18475         (
18476                 "%test_code = OpFunction %v4f32 None %v4f32_v4f32_function\n"
18477                 "    %param = OpFunctionParameter %v4f32\n"
18478
18479                 "    %entry = OpLabel\n"
18480                 "        %i = OpVariable %fp_i32 Function\n"
18481                 "             OpStore %i %c_i32_0\n"
18482                 "             OpBranch %loop\n"
18483
18484                 "     %loop = OpLabel\n"
18485                 "    %i_cmp = OpLoad %i32 %i\n"
18486                 "       %lt = OpSLessThan %bool %i_cmp %c_i32_ndp\n"
18487                 "             OpLoopMerge %merge %next None\n"
18488                 "             OpBranchConditional %lt %write %merge\n"
18489
18490                 "    %write = OpLabel\n"
18491                 "      %ndx = OpLoad %i32 %i\n"
18492
18493                 "       %90 = OpAccessChain %up_u32 %ssbo_src1 %c_i32_0 %ndx\n"
18494                 "       %91 = OpLoad %u32 %90\n"
18495
18496                 "       %98 = OpAccessChain %up_u32 %ssbo_src0 %c_i32_0 %ndx\n"
18497                 "       %${zeroth_id} = OpLoad %u32 %98\n"
18498
18499                 "${seq}\n"
18500
18501                 // The test relies on SPIR-V compiler option SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS set in assembleSpirV()
18502                 "      %dst = OpAccessChain %up_u32 %ssbo_dst %c_i32_0 %ndx\n"
18503                 "             OpStore %dst %${last_id}\n"
18504                 "             OpBranch %next\n"
18505
18506                 "     %next = OpLabel\n"
18507                 "    %i_cur = OpLoad %i32 %i\n"
18508                 "    %i_new = OpIAdd %i32 %i_cur %c_i32_1\n"
18509                 "             OpStore %i %i_new\n"
18510                 "             OpBranch %loop\n"
18511
18512                 "    %merge = OpLabel\n"
18513                 "             OpReturnValue %param\n"
18514
18515                 "             OpFunctionEnd\n"
18516         );
18517         deUint32                                lastId                  = firstNdx;
18518         SpecResource                    specResource;
18519         map<string, string>             specs;
18520         VulkanFeatures                  features;
18521         map<string, string>             fragments;
18522         vector<string>                  extensions;
18523         std::string                             sequence;
18524
18525         for (deUint32 sequenceNdx = 0; sequenceNdx < sequenceCount; ++sequenceNdx)
18526         {
18527                 const deUint32          sequenceId              = sequenceNdx + firstNdx;
18528                 const std::string       sequenceIdStr   = de::toString(sequenceId);
18529
18530                 sequence += "%" + sequenceIdStr + " = OpIAdd %u32 %91 %" + de::toString(sequenceId - 1) + "\n";
18531                 lastId = sequenceId;
18532
18533                 if (sequenceNdx == 0)
18534                         sequence.reserve((10 + sequence.length()) * sequenceCount);
18535         }
18536
18537         specs["num_data_points"]        = de::toString(numDataPoints);
18538         specs["zeroth_id"]                      = de::toString(firstNdx - 1);
18539         specs["last_id"]                        = de::toString(lastId);
18540         specs["seq"]                            = sequence;
18541
18542         fragments["decoration"]         = decoration.specialize(specs);
18543         fragments["pre_main"]           = preMain.specialize(specs);
18544         fragments["testfun"]            = testFun.specialize(specs);
18545
18546         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData1)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18547         specResource.inputs.push_back(Resource(BufferSp(new Uint32Buffer(inData2)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18548         specResource.outputs.push_back(Resource(BufferSp(new Uint32Buffer(outData)), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER));
18549
18550         features.coreFeatures.vertexPipelineStoresAndAtomics    = true;
18551         features.coreFeatures.fragmentStoresAndAtomics                  = true;
18552
18553         finalizeTestsCreation(specResource, fragments, testCtx, *testGroup.get(), testName, features, extensions, IVec3(1, 1, 1));
18554 }
18555
18556 tcu::TestCaseGroup* createSpirvIdsAbuseTests (tcu::TestContext& testCtx)
18557 {
18558         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18559
18560         createSparseIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18561         createLotsIdsAbuseTest<GraphicsResources>(testCtx, testGroup);
18562
18563         return testGroup.release();
18564 }
18565
18566 tcu::TestCaseGroup* createSpirvIdsAbuseGroup (tcu::TestContext& testCtx)
18567 {
18568         de::MovePtr<tcu::TestCaseGroup> testGroup       (new tcu::TestCaseGroup(testCtx, "spirv_ids_abuse", "SPIR-V abuse tests"));
18569
18570         createSparseIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18571         createLotsIdsAbuseTest<ComputeShaderSpec>(testCtx, testGroup);
18572
18573         return testGroup.release();
18574 }
18575
18576 tcu::TestCaseGroup* createInstructionTests (tcu::TestContext& testCtx)
18577 {
18578         const bool testComputePipeline = true;
18579
18580         de::MovePtr<tcu::TestCaseGroup> instructionTests        (new tcu::TestCaseGroup(testCtx, "instruction", "Instructions with special opcodes/operands"));
18581         de::MovePtr<tcu::TestCaseGroup> computeTests            (new tcu::TestCaseGroup(testCtx, "compute", "Compute Instructions with special opcodes/operands"));
18582         de::MovePtr<tcu::TestCaseGroup> graphicsTests           (new tcu::TestCaseGroup(testCtx, "graphics", "Graphics Instructions with special opcodes/operands"));
18583
18584         computeTests->addChild(createSpivVersionCheckTests(testCtx, testComputePipeline));
18585         computeTests->addChild(createLocalSizeGroup(testCtx));
18586         computeTests->addChild(createOpNopGroup(testCtx));
18587         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITHOUT_NAN));
18588         computeTests->addChild(createOpFUnordGroup(testCtx, TEST_WITH_NAN));
18589         computeTests->addChild(createOpAtomicGroup(testCtx, false));
18590         computeTests->addChild(createOpAtomicGroup(testCtx, true));                                     // Using new StorageBuffer decoration
18591         computeTests->addChild(createOpAtomicGroup(testCtx, false, 1024, true));        // Return value validation
18592         computeTests->addChild(createOpLineGroup(testCtx));
18593         computeTests->addChild(createOpModuleProcessedGroup(testCtx));
18594         computeTests->addChild(createOpNoLineGroup(testCtx));
18595         computeTests->addChild(createOpConstantNullGroup(testCtx));
18596         computeTests->addChild(createOpConstantCompositeGroup(testCtx));
18597         computeTests->addChild(createOpConstantUsageGroup(testCtx));
18598         computeTests->addChild(createSpecConstantGroup(testCtx));
18599         computeTests->addChild(createOpSourceGroup(testCtx));
18600         computeTests->addChild(createOpSourceExtensionGroup(testCtx));
18601         computeTests->addChild(createDecorationGroupGroup(testCtx));
18602         computeTests->addChild(createOpPhiGroup(testCtx));
18603         computeTests->addChild(createLoopControlGroup(testCtx));
18604         computeTests->addChild(createFunctionControlGroup(testCtx));
18605         computeTests->addChild(createSelectionControlGroup(testCtx));
18606         computeTests->addChild(createBlockOrderGroup(testCtx));
18607         computeTests->addChild(createMultipleShaderGroup(testCtx));
18608         computeTests->addChild(createMemoryAccessGroup(testCtx));
18609         computeTests->addChild(createOpCopyMemoryGroup(testCtx));
18610         computeTests->addChild(createOpCopyObjectGroup(testCtx));
18611         computeTests->addChild(createNoContractionGroup(testCtx));
18612         computeTests->addChild(createOpUndefGroup(testCtx));
18613         computeTests->addChild(createOpUnreachableGroup(testCtx));
18614         computeTests->addChild(createOpQuantizeToF16Group(testCtx));
18615         computeTests->addChild(createOpFRemGroup(testCtx));
18616         computeTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18617         computeTests->addChild(createOpSRemComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18618         computeTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_PASS));
18619         computeTests->addChild(createOpSModComputeGroup64(testCtx, QP_TEST_RESULT_PASS));
18620         computeTests->addChild(createConvertComputeTests(testCtx, "OpSConvert", "sconvert"));
18621         computeTests->addChild(createConvertComputeTests(testCtx, "OpUConvert", "uconvert"));
18622         computeTests->addChild(createConvertComputeTests(testCtx, "OpFConvert", "fconvert"));
18623         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertSToF", "convertstof"));
18624         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToS", "convertftos"));
18625         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertUToF", "convertutof"));
18626         computeTests->addChild(createConvertComputeTests(testCtx, "OpConvertFToU", "convertftou"));
18627         computeTests->addChild(createOpCompositeInsertGroup(testCtx));
18628         computeTests->addChild(createOpInBoundsAccessChainGroup(testCtx));
18629         computeTests->addChild(createShaderDefaultOutputGroup(testCtx));
18630         computeTests->addChild(createOpNMinGroup(testCtx));
18631         computeTests->addChild(createOpNMaxGroup(testCtx));
18632         computeTests->addChild(createOpNClampGroup(testCtx));
18633         {
18634                 de::MovePtr<tcu::TestCaseGroup> computeAndroidTests     (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18635
18636                 computeAndroidTests->addChild(createOpSRemComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18637                 computeAndroidTests->addChild(createOpSModComputeGroup(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18638
18639                 computeTests->addChild(computeAndroidTests.release());
18640         }
18641
18642         computeTests->addChild(create8BitStorageComputeGroup(testCtx));
18643         computeTests->addChild(create16BitStorageComputeGroup(testCtx));
18644         computeTests->addChild(createFloatControlsComputeGroup(testCtx));
18645         computeTests->addChild(createUboMatrixPaddingComputeGroup(testCtx));
18646         computeTests->addChild(createCompositeInsertComputeGroup(testCtx));
18647         computeTests->addChild(createVariableInitComputeGroup(testCtx));
18648         computeTests->addChild(createConditionalBranchComputeGroup(testCtx));
18649         computeTests->addChild(createIndexingComputeGroup(testCtx));
18650         computeTests->addChild(createVariablePointersComputeGroup(testCtx));
18651         computeTests->addChild(createPhysicalPointersComputeGroup(testCtx));
18652         computeTests->addChild(createImageSamplerComputeGroup(testCtx));
18653         computeTests->addChild(createOpNameGroup(testCtx));
18654         computeTests->addChild(createOpMemberNameGroup(testCtx));
18655         computeTests->addChild(createPointerParameterComputeGroup(testCtx));
18656         computeTests->addChild(createFloat16Group(testCtx));
18657         computeTests->addChild(createBoolGroup(testCtx));
18658         computeTests->addChild(createWorkgroupMemoryComputeGroup(testCtx));
18659         computeTests->addChild(createSpirvIdsAbuseGroup(testCtx));
18660         computeTests->addChild(createSignedIntCompareGroup(testCtx));
18661         computeTests->addChild(createUnusedVariableComputeTests(testCtx));
18662
18663         graphicsTests->addChild(createCrossStageInterfaceTests(testCtx));
18664         graphicsTests->addChild(createSpivVersionCheckTests(testCtx, !testComputePipeline));
18665         graphicsTests->addChild(createOpNopTests(testCtx));
18666         graphicsTests->addChild(createOpSourceTests(testCtx));
18667         graphicsTests->addChild(createOpSourceContinuedTests(testCtx));
18668         graphicsTests->addChild(createOpModuleProcessedTests(testCtx));
18669         graphicsTests->addChild(createOpLineTests(testCtx));
18670         graphicsTests->addChild(createOpNoLineTests(testCtx));
18671         graphicsTests->addChild(createOpConstantNullTests(testCtx));
18672         graphicsTests->addChild(createOpConstantCompositeTests(testCtx));
18673         graphicsTests->addChild(createMemoryAccessTests(testCtx));
18674         graphicsTests->addChild(createOpUndefTests(testCtx));
18675         graphicsTests->addChild(createSelectionBlockOrderTests(testCtx));
18676         graphicsTests->addChild(createModuleTests(testCtx));
18677         graphicsTests->addChild(createUnusedVariableTests(testCtx));
18678         graphicsTests->addChild(createSwitchBlockOrderTests(testCtx));
18679         graphicsTests->addChild(createOpPhiTests(testCtx));
18680         graphicsTests->addChild(createNoContractionTests(testCtx));
18681         graphicsTests->addChild(createOpQuantizeTests(testCtx));
18682         graphicsTests->addChild(createLoopTests(testCtx));
18683         graphicsTests->addChild(createSpecConstantTests(testCtx));
18684         graphicsTests->addChild(createSpecConstantOpQuantizeToF16Group(testCtx));
18685         graphicsTests->addChild(createBarrierTests(testCtx));
18686         graphicsTests->addChild(createDecorationGroupTests(testCtx));
18687         graphicsTests->addChild(createFRemTests(testCtx));
18688         graphicsTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18689         graphicsTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_PASS));
18690
18691         {
18692                 de::MovePtr<tcu::TestCaseGroup> graphicsAndroidTests    (new tcu::TestCaseGroup(testCtx, "android", "Android CTS Tests"));
18693
18694                 graphicsAndroidTests->addChild(createOpSRemGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18695                 graphicsAndroidTests->addChild(createOpSModGraphicsTests(testCtx, QP_TEST_RESULT_QUALITY_WARNING));
18696
18697                 graphicsTests->addChild(graphicsAndroidTests.release());
18698         }
18699         graphicsTests->addChild(createOpNameTests(testCtx));
18700         graphicsTests->addChild(createOpNameAbuseTests(testCtx));
18701         graphicsTests->addChild(createOpMemberNameAbuseTests(testCtx));
18702
18703         graphicsTests->addChild(create8BitStorageGraphicsGroup(testCtx));
18704         graphicsTests->addChild(create16BitStorageGraphicsGroup(testCtx));
18705         graphicsTests->addChild(createFloatControlsGraphicsGroup(testCtx));
18706         graphicsTests->addChild(createUboMatrixPaddingGraphicsGroup(testCtx));
18707         graphicsTests->addChild(createCompositeInsertGraphicsGroup(testCtx));
18708         graphicsTests->addChild(createVariableInitGraphicsGroup(testCtx));
18709         graphicsTests->addChild(createConditionalBranchGraphicsGroup(testCtx));
18710         graphicsTests->addChild(createIndexingGraphicsGroup(testCtx));
18711         graphicsTests->addChild(createVariablePointersGraphicsGroup(testCtx));
18712         graphicsTests->addChild(createImageSamplerGraphicsGroup(testCtx));
18713         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpSConvert", "sconvert"));
18714         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpUConvert", "uconvert"));
18715         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpFConvert", "fconvert"));
18716         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertSToF", "convertstof"));
18717         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToS", "convertftos"));
18718         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertUToF", "convertutof"));
18719         graphicsTests->addChild(createConvertGraphicsTests(testCtx, "OpConvertFToU", "convertftou"));
18720         graphicsTests->addChild(createPointerParameterGraphicsGroup(testCtx));
18721         graphicsTests->addChild(createVaryingNameGraphicsGroup(testCtx));
18722         graphicsTests->addChild(createFloat16Tests(testCtx));
18723         graphicsTests->addChild(createSpirvIdsAbuseTests(testCtx));
18724
18725         instructionTests->addChild(computeTests.release());
18726         instructionTests->addChild(graphicsTests.release());
18727
18728         return instructionTests.release();
18729 }
18730
18731 } // SpirVAssembly
18732 } // vkt