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