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