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