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