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